// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A TLS handshake carried in real QUIC packets. //! //! Every piece of this library at once, doing the thing they were each built //! for: `tls_handshake` behind the seam produces handshake bytes, `frame` //! puts them in CRYPTO frames, `packet.Builder` puts those in Initial and //! Handshake packets, `protection` protects them — with Initial keys derived //! from a connection ID and Handshake keys derived from the traffic secret //! TLS just produced — and the other end takes it all apart again through //! `packet.open`, `frame.Iterator` and `reassembly`. //! //! What this file is *not* is the connection state machine. It plays that //! part by hand, and deliberately: until the sequence has been written out //! once and made to work, a state machine that encapsulated it would be //! encapsulating a guess. What it demonstrates is that the pieces compose, //! which is the question that has been open since the seam was written with //! nothing behind it. const std = @import("std"); const testing = std.testing; const quic = @import("quic"); const frame = quic.frame; const packet = quic.packet; const protection = quic.protection; const reassembly = quic.reassembly; const tls = quic.tls; /// The client picks this and both ends derive their Initial keys from it /// (RFC 9001 §5.2), which is why the first packet can be read before anything /// has been agreed. const destination_connection_id = [_]u8{ 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08 }; /// The connection IDs the two ends of a test connection choose for /// themselves, which §7.3 then has each of them prove inside the handshake. const client_connection_id = [_]u8{ 0xc1, 0xc2, 0xc3, 0xc4 }; const server_connection_id = [_]u8{ 0x5e, 0x51 }; /// One end's view of one packet number space. const Space = struct { /// Keys for writing, and for reading what the peer wrote. write: protection.Keys, read: protection.Keys, /// The next packet number to send; §12.3 starts every space at zero. next: u64 = 0, /// The CRYPTO stream for this level, which arrives out of order in /// general and in order here. window: [16 * 1024]u8 = undefined, present: [2 * 1024]u8 = undefined, stream: reassembly.Reassembler = undefined, acks: quic.ack.Tracker = .{}, /// In place, and it has to be: the reassembler borrows this struct's own /// buffers, so a `Space` returned by value would hand back one whose /// stream pointed at the local it was built in. See the note on /// `Reassembler.init`. fn start(s: *Space, write: protection.Keys, read: protection.Keys) void { s.write = write; s.read = read; s.stream = .init(&s.window, &s.present); } }; /// Puts `data` in a CRYPTO frame in one packet, and returns the datagram. fn send( space: *Space, kind: packet.Kind, destination: []const u8, source: []const u8, offset: u64, data: []const u8, buffer: []u8, pad_to: usize, ) ![]u8 { var b = try packet.Builder.initLong(buffer, .{ .kind = kind, .destination = destination, .source = source, }, space.next, 4); try b.add(.{ .crypto = .{ .offset = offset, .data = data } }); if (pad_to > 0) try b.padTo(pad_to); space.next += 1; return b.finish(&space.write); } /// Opens a datagram, walks its frames, and feeds any CRYPTO data to `h`. fn receive(space: *Space, h: tls.Handshake, level: tls.Level, datagram: []u8) !void { var payload: [2048]u8 = undefined; const largest = space.acks.largest() orelse 0; const opened = try packet.open(&space.read, largest, datagram, 0, &payload); var eliciting = false; var it: frame.Iterator = .init(opened.payload); while (try it.next()) |f| { if (f.isAckEliciting()) eliciting = true; // Everything a handshake packet may carry is allowed at its level, // and a frame that is not is a connection error rather than // something to ignore. try testing.expect(f.allowedIn(level)); switch (f) { .crypto => |c| try space.stream.insert(c.offset, c.data), .padding, .ack, .ping => {}, else => return error.UnexpectedFrame, } } space.acks.record(opened.number, eliciting); // Whatever is contiguous goes to TLS, once each. §4.1.3 wants it in // order, which is exactly what the reassembler guarantees and what a // caller feeding frames straight through would not. const readable = space.stream.readable(); if (readable.len > 0) { try h.provide(level, readable); space.stream.consume(readable.len); } } /// The transport parameters each end of a test connection sends. /// /// §7.3 puts the connection IDs of the handshake inside the encrypted /// handshake and has the other end check them, so an arbitrary blob no longer /// gets a connection — which is the point of the rule. These are the smallest /// parameters that satisfy it, built at compile time so that they have the /// static lifetime the TLS handshake borrows them for. const client_transport_parameters = encoded: { var buffer: [64]u8 = undefined; const written = quic.parameters.write(&.{ .initial_source_connection_id = &client_connection_id, }, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; /// The same, with a thousand octets of §18.1's reserved parameter on the end. /// /// "Transport parameters with an identifier of the form 31 * N + 27 are /// reserved to exercise the requirement that unknown transport parameters be /// ignored", which makes this the honest way to inflate a ClientHello past /// one packet: the peer must both ignore it and still read what follows. const padded_client_transport_parameters = encoded: { var buffer: [1100]u8 = undefined; const written = quic.parameters.write(&.{ .initial_source_connection_id = &client_connection_id, }, &buffer, .client) catch unreachable; var at = written.len; // 31 * 1 + 27. at += quic.varint.write(buffer[at..], 58).len; at += quic.varint.write(buffer[at..], 950).len; @memset(buffer[at..][0..950], 0x5a); at += 950; break :encoded buffer[0..at].*; }; const server_transport_parameters = encoded: { var buffer: [64]u8 = undefined; const written = quic.parameters.write(&.{ .initial_source_connection_id = &server_connection_id, .original_destination_connection_id = &destination_connection_id, }, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; test "a TLS handshake carried end to end in QUIC packets" { var rng_impl = std.Random.DefaultPrng.init(0x9001); const rng = rng_impl.random(); const client_params = [_]u8{ 0x01, 0x02, 0x03 }; const server_params = [_]u8{ 0x0a, 0x0b }; const server_cid = [_]u8{ 0xf0, 0x67, 0xa5, 0x50 }; var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_params, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_params, .alpn_protocols = &.{"doq"}, .rng = rng, }); const c = client_tls.handshake(); const s = server_tls.handshake(); // §5.2: both ends derive the Initial keys from the client's chosen // connection ID, so this much needs no TLS at all. var client_initial: Space = undefined; client_initial.start( .initialKeys(&destination_connection_id, .client), .initialKeys(&destination_connection_id, .server), ); client_initial.next = 0; client_initial.acks = .{}; var server_initial: Space = undefined; server_initial.start( .initialKeys(&destination_connection_id, .server), .initialKeys(&destination_connection_id, .client), ); server_initial.next = 0; server_initial.acks = .{}; var datagram: [1500]u8 = undefined; // -- the client's Initial --------------------------------------------- // // §14.1 requires it to be padded to 1200 octets: a server may not send // more than three times what it has received from an unvalidated address, // so the client has to make room for the answer. { const hello = (try c.emit(.initial)).?; const wire = try send( &client_initial, .initial, &destination_connection_id, &.{}, 0, hello, &datagram, 1200, ); try testing.expectEqual(@as(usize, 1200), wire.len); try receive(&server_initial, s, .initial, wire); } try testing.expectEqualSlices(u8, &client_params, s.peerTransportParameters().?); // -- the server's Initial, carrying the ServerHello -------------------- { const server_hello = (try s.emit(.initial)).?; const wire = try send( &server_initial, .initial, &.{}, &server_cid, 0, server_hello, &datagram, 0, ); try receive(&client_initial, c, .initial, wire); } // Both ends now have handshake keys, and the packets that carry the rest // of the handshake are protected with keys derived from them — §5.1 of // RFC 9001, which is `Keys.fromSecret`. var client_hs: Space = undefined; client_hs.start( .fromSecret(c.writeSecret(.handshake).?), .fromSecret(c.readSecret(.handshake).?), ); client_hs.next = 0; client_hs.acks = .{}; var server_hs: Space = undefined; server_hs.start( .fromSecret(s.writeSecret(.handshake).?), .fromSecret(s.readSecret(.handshake).?), ); server_hs.next = 0; server_hs.acks = .{}; // -- the server's Handshake flight ------------------------------------ { const rest = (try s.emit(.handshake)).?; const wire = try send( &server_hs, .handshake, &.{}, &server_cid, 0, rest, &datagram, 0, ); try receive(&client_hs, c, .handshake, wire); } try testing.expect(c.isComplete()); try testing.expectEqualSlices(u8, &server_params, c.peerTransportParameters().?); // -- and the client's Finished ---------------------------------------- { const finished = (try c.emit(.handshake)).?; const wire = try send( &client_hs, .handshake, &server_cid, &.{}, 0, finished, &datagram, 0, ); try receive(&server_hs, s, .handshake, wire); } try testing.expect(s.isComplete()); // -- what it was all for ---------------------------------------------- // // Both ends can now protect 1-RTT packets, and with the same keys: what // one writes is what the other reads. const client_app: protection.Keys = .fromSecret(c.writeSecret(.application).?); const server_app: protection.Keys = .fromSecret(s.readSecret(.application).?); try testing.expectEqualSlices(u8, client_app.key(), server_app.key()); try testing.expectEqualSlices(u8, client_app.iv(), server_app.iv()); try testing.expectEqualSlices(u8, client_app.hp(), server_app.hp()); // And each end acknowledged what it received, in the right space. try testing.expectEqual(@as(?u64, 0), server_initial.acks.largest()); try testing.expectEqual(@as(?u64, 0), client_initial.acks.largest()); try testing.expectEqual(@as(?u64, 0), client_hs.acks.largest()); try testing.expectEqual(@as(?u64, 0), server_hs.acks.largest()); } test "a 1-RTT packet protected with the negotiated keys reads back" { // The handshake's whole purpose, exercised: application data in a short // header packet, protected with keys derived from the traffic secret the // handshake produced. var rng_impl = std.Random.DefaultPrng.init(77); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &.{1}, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_transport_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); const c = client_tls.handshake(); const s = server_tls.handshake(); // Driven directly this time; the packets are the point below, not here. try s.provide(.initial, (try c.emit(.initial)).?); try c.provide(.initial, (try s.emit(.initial)).?); try c.provide(.handshake, (try s.emit(.handshake)).?); try s.provide(.handshake, (try c.emit(.handshake)).?); const write: protection.Keys = .fromSecret(c.writeSecret(.application).?); const read: protection.Keys = .fromSecret(s.readSecret(.application).?); const cid = [_]u8{ 1, 2, 3, 4 }; var datagram: [256]u8 = undefined; var b = try packet.Builder.initShort(&datagram, &cid, 0, 1, false); try b.add(.{ .stream = .{ .stream = 0, .offset = 0, .data = "application data at last", .fin = true, .had_length = true, } }); const wire = try b.finish(&write); var payload: [256]u8 = undefined; const opened = try packet.open(&read, 0, wire, cid.len, &payload); try testing.expectEqual(packet.Kind.one_rtt, opened.header.kind); try testing.expectEqual(@as(u64, 0), opened.number); var it: frame.Iterator = .init(opened.payload); const f = (try it.next()).?; try testing.expectEqualStrings("application data at last", f.stream.data); try testing.expect(f.stream.fin); } test "two connections complete a handshake by exchanging datagrams" { // The same handshake as above, with the hand-driving taken out. Nothing // here knows about encryption levels, packet number spaces, CRYPTO frames // or key derivation: it moves datagrams between two `Connection`s until // neither has anything more to say. var rng_impl = std.Random.DefaultPrng.init(0x9001); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_transport_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_transport_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, }); var buffer: [2048]u8 = undefined; var datagrams: usize = 0; var first_len: usize = 0; // A notional 10ms path, so that the round trips this takes are visible in // what the estimator ends up believing. var now: u64 = 0; // Until both ends are established. Stopping there rather than when // neither has anything to say is deliberate: §14.3 has a connection start // searching for the path's MTU the moment its handshake is confirmed, so // "nothing left to say" now includes a series of probes that are not part // of the handshake and would be counted as if they were. while (datagrams < 16) { if (client.isEstablished() and server.isEstablished() and client.isConfirmed()) break; const from_client = try client.send(&buffer, now); if (from_client) |datagram| { if (datagrams == 0) first_len = datagram.bytes.len; datagrams += 1; now += 10 * std.time.ns_per_ms; try server.receive(datagram.bytes, datagram.path, now); } const from_server = try server.send(&buffer, now); if (from_server) |datagram| { datagrams += 1; now += 10 * std.time.ns_per_ms; try client.receive(datagram.bytes, datagram.path, now); } if (from_client == null and from_server == null) break; } try testing.expect(client.isEstablished()); try testing.expect(server.isEstablished()); // §14.1: the client's first datagram is padded to 1200 octets, which is // what leaves a server room to answer an address it has not validated. try testing.expectEqual(@as(usize, quic.Connection.min_initial_datagram), first_len); // The server learned the client's connection ID from the first packet it // saw, which is the only way it could have. try testing.expectEqualSlices(u8, &.{ 0xc1, 0xc2, 0xc3, 0xc4 }, server.peerId()); // A handshake in a small number of datagrams, which is the whole point of // coalescing packets of different encryption levels into one. // // Four: the client's Initial, the server's Initial+Handshake coalesced, // the client's Handshake carrying its Finished and the acknowledgements, // and the server's answer to those — which also carries the HANDSHAKE_DONE // of §19.20, because §4.1.2 gives a client no other way to learn that its // handshake is confirmed. Everything after that, including the // acknowledgement of the confirmation, is ordinary traffic. try testing.expectEqual(@as(usize, 4), datagrams); // And both ends measured the path while they were at it. Every delivery // above advanced the clock by 10ms, so a round trip is 20ms -- the // client's Initial went out at zero and the packet acknowledging it // arrived at twenty. try testing.expect(client.rtt.sampled); try testing.expect(server.rtt.sampled); try testing.expectEqual(20 * std.time.ns_per_ms, client.rtt.latest); try testing.expectEqual(20 * std.time.ns_per_ms, server.rtt.latest); // A first sample replaces the 333ms assumption rather than averaging with // it (§5.3), which is why a fast path is believed immediately. try testing.expectEqual(20 * std.time.ns_per_ms, client.rtt.smoothed); // The window did not grow. A handshake is almost entirely application // limited -- each side says what it has and then waits -- and §B.5 is // explicit that an unused window is not evidence the path would have // carried it. Without that rule four acknowledged packets would have // doubled the window on no evidence at all. try testing.expectEqual( quic.congestion.initialWindow(quic.congestion.min_datagram_size), client.congestion.window, ); try testing.expectEqual(@as(usize, 0), client.congestion.in_flight); // Nothing is left in flight: everything either side sent has been // acknowledged, so nothing is waiting to be recovered. for (&client.spaces) |*space| try testing.expectEqual(@as(usize, 0), space.loss.inFlight()); } test "a handshake completes across a network that drops a packet" { // The same exchange, run once for each datagram in it, dropping that one. // Nothing above the connection notices: the loop delivers what it is // given, and when neither end has anything to say it asks the timers what // to do about it -- which is exactly the shape of a real event loop with // a UDP socket and a timerfd. // // This is what RFC 9002 buys. Before it, dropping any one of these four // datagrams stalled the handshake permanently, because `emit` hands its // bytes over once and nothing kept a copy. for (0..4) |drop| { var rng_impl = std.Random.DefaultPrng.init(0x9002); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_transport_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_transport_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, }); var buffer: [2048]u8 = undefined; var now: u64 = 0; var datagrams: usize = 0; var timeouts: usize = 0; var steps: usize = 0; while (steps < 32) : (steps += 1) { if (client.isEstablished() and server.isEstablished()) break; var moved = false; if (try client.send(&buffer, now)) |datagram| { const wire = datagram.bytes; now += 5 * std.time.ns_per_ms; if (datagrams != drop) try server.receive(wire, 0, now); datagrams += 1; moved = true; } if (try server.send(&buffer, now)) |datagram| { const wire = datagram.bytes; now += 5 * std.time.ns_per_ms; if (datagrams != drop) try client.receive(wire, 0, now); datagrams += 1; moved = true; } if (moved) continue; // Neither end has anything to say and the handshake is not // finished, so something is missing. The timers are the only // thing that can find that out: nothing later arrived to declare // the lost packet lost, which is precisely the case §6.2 invented // the probe timeout for. var at: ?u64 = client.timeout(); if (server.timeout()) |s| { if (at == null or s < at.?) at = s; } now = @max(now, at orelse break); client.onTimeout(now); server.onTimeout(now); timeouts += 1; } try testing.expect(client.isEstablished()); try testing.expect(server.isEstablished()); if (drop < 3) { // A timer had to fire: the lost datagram was the newest thing // sent, so no acknowledgement could ever point at it and nothing // but the probe timeout was going to notice. try testing.expect(timeouts > 0); // And it cost more than the four datagrams the clean run took. try testing.expect(datagrams > 4); } else { // The fourth is the odd one out, and instructively so. It carries // nothing but the server's acknowledgements: by the time it is // sent the client already has 1-RTT keys, taken from the second // datagram, and the server already has the client's Finished. So // losing it costs the handshake nothing and no timer fires. try testing.expectEqual(@as(usize, 0), timeouts); try testing.expectEqual(@as(usize, 4), datagrams); // What it does cost is the client's *knowledge* that its Finished // arrived, which is still unacknowledged and still on a timer. // That is the whole reason a client keeps a probe timeout running // after it considers the handshake complete. try testing.expect(client.spaces[1].loss.inFlight() > 0); try testing.expect(client.timeout() != null); } } } test "a connection drops a packet it cannot read rather than answering it" { // §5.2 of RFC 9000: an endpoint MUST NOT send anything in response to a // packet it could not process, because anything sent to an unvalidated // address is an amplification vector. §5.5 of RFC 9001 says a packet // failing authentication is simply discarded -- anyone can send rubbish // to a UDP port. var rng_impl = std.Random.DefaultPrng.init(13); const rng = rng_impl.random(); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_transport_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, }); var buffer: [2048]u8 = undefined; // Noise that happens to look like an Initial packet. var noise: [1200]u8 = @splat(0); noise[0] = 0xc0; std.mem.writeInt(u32, noise[1..5], 1, .big); noise[5] = 8; @memcpy(noise[6..14], &destination_connection_id); noise[14] = 0; // no source noise[15] = 0; // no token noise[16] = 0x44; // a two-octet length noise[17] = 0x9e; try server.receive(&noise, 0, 0); // Nothing to say: it could not read the packet, so it has nothing to // acknowledge and no handshake to answer with. try testing.expectEqual(@as(?quic.Connection.Datagram, null), try server.send(&buffer, 0)); try testing.expect(!server.isEstablished()); // And a datagram too short to be anything at all. try server.receive(buffer[0..3], 0, 0); try testing.expectEqual(@as(?quic.Connection.Datagram, null), try server.send(&buffer, 0)); } test "a handshake message larger than a packet is split across datagrams" { // §19.6 gives a CRYPTO frame an offset and a length and says nothing // about message boundaries, which is the only reason a TLS message larger // than a packet is expressible at all. What makes one here is the // client's transport parameters: they travel in a ClientHello extension, // so a large enough blob puts the ClientHello over any datagram size. // // That this works at all is loss recovery's doing. A sender may only // split a message across packets if it can put a lost piece back, and // before RFC 9002 was implemented this path refused to split and demanded // the whole flight fit in one packet. var rng_impl = std.Random.DefaultPrng.init(0x9003); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &padded_client_transport_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_transport_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, }); // Exactly the minimum datagram, which is what an endpoint may assume the // path carries before it has measured anything. var buffer: [quic.Connection.min_initial_datagram]u8 = undefined; var now: u64 = 0; var datagrams: usize = 0; var steps: usize = 0; while (steps < 32) : (steps += 1) { if (client.isEstablished() and server.isEstablished()) break; var moved = false; if (try client.send(&buffer, now)) |datagram| { const wire = datagram.bytes; // Every one of them is a legal datagram, including the ones // carrying the middle of a message. try testing.expect(wire.len <= buffer.len); now += std.time.ns_per_ms; try server.receive(wire, 0, now); datagrams += 1; moved = true; } if (try server.send(&buffer, now)) |datagram| { const wire = datagram.bytes; now += std.time.ns_per_ms; try client.receive(wire, 0, now); datagrams += 1; moved = true; } if (!moved) break; } try testing.expect(client.isEstablished()); try testing.expect(server.isEstablished()); // More than the four a small handshake takes: the ClientHello alone did // not fit in one. try testing.expect(datagrams > 4); // And the server put the pieces back in the right order, which is what // the reassembler is for: it read the transport parameters out of the // extension that spanned three packets, ignored the reserved one, and // found the connection ID §7.3 makes it check. try testing.expectEqualSlices( u8, &padded_client_transport_parameters, server.handshake.peerTransportParameters().?, ); try testing.expectEqualSlices( u8, &client_connection_id, server.peer.?.initial_source_connection_id.?, ); } test "the congestion window holds a sender back until the path answers" { // §7: "An endpoint MUST NOT send a packet if it would cause // bytes_in_flight to be larger than the congestion window." The window is // set to a single datagram here so that the rule bites on a handshake; // the ClientHello is inflated past one packet so that there is a second // one waiting to be held back. var rng_impl = std.Random.DefaultPrng.init(0x9004); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &padded_client_transport_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_transport_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, }); // One datagram's worth of window. client.congestion.window = quic.Connection.min_initial_datagram; var buffer: [quic.Connection.min_initial_datagram]u8 = undefined; const first = (try client.send(&buffer, 0)).?.bytes; try testing.expectEqual(@as(usize, quic.Connection.min_initial_datagram), first.len); try testing.expectEqual(@as(usize, 0), client.congestion.available()); // Held back, and not for want of anything to say: the rest of the // ClientHello is sitting there waiting for room. try testing.expect(client.hasDataToSend()); try testing.expectEqual(@as(?quic.Connection.Datagram, null), try client.send(&buffer, 1)); // The path answers. The server cannot reply to half a ClientHello with a // handshake, but it acknowledges what arrived -- and that acknowledgement // is what takes the first datagram out of flight. try server.receive(first, 0, 10); const ack_only = (try server.send(&buffer, 11)).?.bytes; try client.receive(ack_only, 0, 20); try testing.expectEqual(@as(usize, 0), client.congestion.in_flight); // And now the rest goes. const second = (try client.send(&buffer, 21)).?.bytes; try testing.expect(second.len > 0); } test "a probe is not blocked by the congestion window" { // §7.5: "Probe packets MUST NOT be blocked by the congestion // controller." The case this exists for is a window that is full of // packets nobody has acknowledged -- which is exactly the state a sender // is in when the path has died, and exactly when it most needs to send // something to find out. var rng_impl = std.Random.DefaultPrng.init(0x9005); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_transport_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, }); var buffer: [quic.Connection.min_initial_datagram]u8 = undefined; const first = (try client.send(&buffer, 0)).?.bytes; try testing.expect(first.len > 0); // Nothing comes back. The window is now full of one unacknowledged // datagram and there is nothing new to send, so an ordinary call has // nothing to say. client.congestion.window = quic.Connection.min_initial_datagram; try testing.expectEqual(@as(usize, 0), client.congestion.available()); try testing.expectEqual(@as(?quic.Connection.Datagram, null), try client.send(&buffer, 1)); // The probe timeout fires, which marks the unacknowledged flight for // sending again and exempts the next datagram from the window. const at = client.timeout().?; client.onTimeout(at); try testing.expect(client.probe_pending); const probe = (try client.send(&buffer, at)).?.bytes; try testing.expectEqual(@as(usize, quic.Connection.min_initial_datagram), probe.len); // §7.5: "A sender MUST however count these packets as being additionally // in flight, since these packets add network load without establishing // packet loss." try testing.expect(client.congestion.in_flight > client.congestion.window); // And the exemption is spent: it covers the probe, not everything after. try testing.expect(!client.probe_pending); } test "RFC 9000 7.2: a client adopts the connection ID the server chose" { // "Upon first receiving an Initial or Retry packet from the server, the // client uses the Source Connection ID supplied by the server as the // Destination Connection ID for subsequent packets." Until then the // client is addressing packets to an identifier it invented, which is the // only thing it can do and the reason §7.3 exists. var rng_impl = std.Random.DefaultPrng.init(0x9006); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_transport_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_transport_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, }); // Before anything comes back, the client is writing to the identifier it // made up and derived the Initial keys from. try testing.expectEqualSlices(u8, &destination_connection_id, client.peerId()); var buffer: [2048]u8 = undefined; const hello = (try client.send(&buffer, 0)).?.bytes; try server.receive(hello, 0, 1); const reply = (try server.send(&buffer, 2)).?.bytes; try client.receive(reply, 0, 3); // And now to the one the server picked for itself. try testing.expectEqualSlices(u8, &server_connection_id, client.peerId()); // Which §7.3 then makes the server prove it really chose, inside the // encrypted handshake rather than in a header anyone could write. try testing.expectEqualSlices( u8, &server_connection_id, client.peer.?.initial_source_connection_id.?, ); try testing.expectEqualSlices( u8, &destination_connection_id, client.peer.?.original_destination_connection_id.?, ); } test "RFC 9000 7.3: a connection ID that was not the one used ends the connection" { // "Including connection ID values in transport parameters and verifying // them ensures that an attacker cannot influence the choice of connection // ID for a successful connection by injecting packets carrying // attacker-chosen connection IDs during the handshake." // // The server here claims inside the handshake to have used a Source // Connection ID it did not use. Nothing about the packets is wrong -- // they decrypt, they parse, the TLS handshake is valid -- and the client // must still refuse, because that mismatch is the signature of something // having rewritten a header in flight. const lying_server_parameters = comptime encoded: { var buffer: [64]u8 = undefined; const written = quic.parameters.write(&.{ .initial_source_connection_id = &[_]u8{ 0xde, 0xad }, .original_destination_connection_id = &destination_connection_id, }, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl = std.Random.DefaultPrng.init(0x9007); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_transport_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &lying_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, }); var buffer: [2048]u8 = undefined; const hello = (try client.send(&buffer, 0)).?.bytes; try server.receive(hello, 0, 1); const reply = (try server.send(&buffer, 2)).?.bytes; try testing.expectError(error.TransportParameterError, client.receive(reply, 0, 3)); try testing.expect(!client.isEstablished()); } test "RFC 9000 7.3: transport parameters that omit the connection ID are refused" { // "An endpoint MUST treat the absence of the initial_source_connection_id // transport parameter from either endpoint... as a connection error of // type TRANSPORT_PARAMETER_ERROR." Absence is not a lesser failure than a // mismatch: an endpoint that accepted it would be back to trusting the // headers. const silent_client_parameters = comptime encoded: { var buffer: [64]u8 = undefined; const written = quic.parameters.write(&.{ .initial_max_data = 1000, }, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl = std.Random.DefaultPrng.init(0x9008); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &silent_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_transport_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, }); var buffer: [2048]u8 = undefined; const hello = (try client.send(&buffer, 0)).?.bytes; try testing.expectError(error.TransportParameterError, server.receive(hello, 0, 1)); } /// Transport parameters that permit streams, for both ends of a test /// connection. §4.6: a server that forgets `initial_max_streams_bidi` accepts /// a connection on which no request can be made, and §4.1's limits start at /// zero, so a connection that is going to carry anything has to say so here. const stream_limits: quic.parameters.Parameters = .{ .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_streams_bidi = 4, // §18.2 defaults both unidirectional limits to zero, which is a connection // on which no unidirectional stream can be opened at all. These fixtures // allow them because §2.1's two identifier spaces and §4.6's two limits // are only testable where both exist. .initial_max_stream_data_uni = 2048, .initial_max_streams_uni = 3, }; /// The same limits, plus RFC 9221's parameter, for the datagram tests. Kept /// separate because §3 makes the parameter's absence meaningful -- a fixture /// that always sent it could not test what happens when it is not sent. const datagram_limits: quic.parameters.Parameters = limits: { var p = stream_limits; p.max_datagram_frame_size = 1200; break :limits p; }; const streaming_client_parameters = encoded: { var buffer: [128]u8 = undefined; var p = stream_limits; p.initial_source_connection_id = &client_connection_id; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const datagram_client_parameters = encoded: { var buffer: [128]u8 = undefined; var p = datagram_limits; p.initial_source_connection_id = &client_connection_id; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const datagram_server_parameters = encoded: { var buffer: [128]u8 = undefined; var p = datagram_limits; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; /// A server that names a preferred address, with the identifier §5.1.1 /// numbers 1 and the reset token that goes with it. /// The same length as `server_connection_id`, and not by coincidence: a short /// header carries no connection ID length, so an endpoint has to be able to /// find the field in its own packets — which means every identifier it issues /// is the same size, the preferred address's included. const preferred_connection_id = [_]u8{ 0xc1, 0xd0 }; const preferred_reset_token: [16]u8 = @splat(0x7e); /// What the server passes to `Connection.init`, which must say the same thing /// as what it passes to TLS -- see the note on `Options.local`. const preferred_limits: quic.parameters.Parameters = limits: { var p = stream_limits; p.preferred_address = .{ .ipv4 = .{ 192, 0, 2, 1 }, .ipv4_port = 8853, .connection_id = &preferred_connection_id, .stateless_reset_token = preferred_reset_token, }; break :limits p; }; const preferred_server_parameters = encoded: { var buffer: [256]u8 = undefined; var p = preferred_limits; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; const streaming_server_parameters = encoded: { var buffer: [128]u8 = undefined; var p = stream_limits; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; /// Two connections that have finished a handshake and may carry streams. const Pair = struct { client: *quic.Connection, server: *quic.Connection, now: u64 = 0, fn handshake(p: *Pair) !void { var buffer: [2048]u8 = undefined; var steps: usize = 0; while (steps < 16) : (steps += 1) { if (p.client.isEstablished() and p.server.isEstablished()) break; var moved = false; if (try p.client.send(&buffer, p.now)) |datagram| { const wire = datagram.bytes; p.now += std.time.ns_per_ms; try p.server.receive(wire, datagram.path, p.now); moved = true; } if (try p.server.send(&buffer, p.now)) |datagram| { const wire = datagram.bytes; p.now += std.time.ns_per_ms; try p.client.receive(wire, datagram.path, p.now); moved = true; } if (!moved) break; } try testing.expect(p.client.isEstablished()); try testing.expect(p.server.isEstablished()); } /// A client and a server that have finished a handshake, ready to carry /// streams. /// /// The two connections and their TLS live in the returned struct because /// a `Connection` borrows its own buffers -- see `Connection.init` -- so /// neither of them may be moved after being initialised. /// The default sizes, which is what every fixture but one wants. const Connected = ConnectedSized(.{}); /// A fixture whose buffers are a size of the test's choosing, for the /// tests where the relationship between a buffer and what the peer has /// granted is the thing under test rather than scenery. fn ConnectedSized(comptime sizes: quic.Connection.Sizes) type { return struct { client_tls: quic.tls_handshake.Client, server_tls: quic.tls_handshake.Server, client: quic.Connection, server: quic.Connection, client_memory: quic.Connection.Storage(sizes) = .{}, server_memory: quic.Connection.Storage(sizes) = .{}, /// A field and not a local of `startWith`, because `random()` hands /// out a pointer to it and both connections keep that pointer for as /// long as they live. As a local it dangled the moment `startWith` /// returned, and went on working only because nothing had reused the /// stack underneath it yet -- until a change of frame size somewhere /// else turned it into a bus error in the middle of a handshake. rng_impl: std.Random.DefaultPrng = undefined, pair: Pair = undefined, fn start(self: *@This(), seed: u64) !*Pair { return self.startWith(seed, stream_limits, &streaming_client_parameters, &streaming_server_parameters); } fn startWith( self: *@This(), seed: u64, local: quic.parameters.Parameters, client_encoded: []const u8, server_encoded: []const u8, ) !*Pair { self.rng_impl = std.Random.DefaultPrng.init(seed); const rng = self.rng_impl.random(); self.client_tls = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = client_encoded, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); self.server_tls = .init(.{ .auth = null, .transport_parameters = server_encoded, .alpn_protocols = &.{"doq"}, .rng = rng, }); self.client.init(.{ .role = .client, .memory = self.client_memory.memory(), .handshake = self.client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = local, // §5.1.1 and §8.2 both need it: without randomness there are // no further identifiers to issue and no challenge to send, // so a fixture without one cannot migrate at all. .rng = rng, }); self.server.init(.{ .role = .server, .memory = self.server_memory.memory(), .handshake = self.server_tls.handshake(), .local_id = &server_connection_id, .local = local, .rng = rng, }); self.pair = .{ .client = &self.client, .server = &self.server }; try self.pair.handshake(); return &self.pair; } }; } /// Moves datagrams until neither end has anything more to say. fn settle(p: *Pair) !void { var buffer: [2048]u8 = undefined; var steps: usize = 0; while (steps < 64) : (steps += 1) { var moved = false; if (try p.client.send(&buffer, p.now)) |datagram| { const wire = datagram.bytes; p.now += std.time.ns_per_ms; try p.server.receive(wire, datagram.path, p.now); moved = true; } if (try p.server.send(&buffer, p.now)) |datagram| { const wire = datagram.bytes; p.now += std.time.ns_per_ms; try p.client.receive(wire, datagram.path, p.now); moved = true; } if (!moved) return; } return error.NeverSettled; } }; test "a request and a response, on a stream" { // The shape of DNS over QUIC (RFC 9250): a client opens a bidirectional // stream, sends a query and ends its half, the server answers on the same // stream and ends its own. Nothing above the connection knows about // packets, encryption levels or acknowledgements. var rng_impl = std.Random.DefaultPrng.init(0x9010); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); // §2.1: the first stream a client opens bidirectionally is identifier // zero, and the peer's limit is what permits it at all. const id = try client.openBidirectional(); try testing.expectEqual(@as(u64, 0), id.value); try testing.expectEqual(quic.stream.Kind.client_bidirectional, id.kind()); try client.write(id, "who is example.com?"); try client.finishStream(id); try pair.settle(); // The server was told about a stream it did not open, and read what came // on it. const accepted = server.accept().?; try testing.expectEqual(id.value, accepted.value); try testing.expectEqualStrings("who is example.com?", server.readable(accepted)); server.consume(accepted, server.readable(accepted).len); try testing.expect(server.streamFinished(accepted)); // And answers on the same stream. try server.write(accepted, "192.0.2.1"); try server.finishStream(accepted); try pair.settle(); try testing.expectEqualStrings("192.0.2.1", client.readable(id)); client.consume(id, client.readable(id).len); try testing.expect(client.streamFinished(id)); } test "RFC 9000 4.1: a sender stops at the credit it was given" { // The limits here are deliberately small, so that a request larger than // one window has to wait for a MAX_STREAM_DATA before the rest of it can // go. Without flow control working in both directions this either stalls // forever or oversends. const tight: quic.parameters.Parameters = .{ .initial_max_data = 256, .initial_max_stream_data_bidi_local = 128, .initial_max_stream_data_bidi_remote = 128, .initial_max_streams_bidi = 2, }; const tight_client = comptime encoded: { var buffer: [128]u8 = undefined; var p = tight; p.initial_source_connection_id = &client_connection_id; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const tight_server = comptime encoded: { var buffer: [128]u8 = undefined; var p = tight; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl = std.Random.DefaultPrng.init(0x9011); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &tight_client, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &tight_server, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = tight, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = tight, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); var payload: [400]u8 = undefined; for (&payload, 0..) |*b, i| b.* = @truncate(i); const id = try client.openBidirectional(); try client.write(id, &payload); try client.finishStream(id); try pair.settle(); // Only the first window arrived: the peer granted 128 octets on this // stream and the sender stopped there rather than being refused. const accepted = server.accept().?; try testing.expectEqual(@as(usize, 128), server.readable(accepted).len); try testing.expect(!server.streamFinished(accepted)); // Reading is what releases credit, and the MAX_STREAM_DATA that follows // is what lets the rest of it move. §4.2: a receiver must not wait to be // told it is blocking the sender. var read: usize = 0; var rounds: usize = 0; while (read < payload.len and rounds < 20) : (rounds += 1) { const got = server.readable(accepted); read += got.len; server.consume(accepted, got.len); try pair.settle(); } try testing.expectEqual(payload.len, read); try testing.expect(server.streamFinished(accepted)); } test "RFC 9000 19.8: the FIN travels on the frame carrying the last octet" { // What every other implementation sends, and what this one now sends: one // STREAM frame with the data and the FIN bit, rather than the data and then // an empty frame behind it carrying only the bit. Both are legal -- §19.8 // allows a zero-length frame with FIN at the final offset -- and the // difference is not academic: Quad9's DNS-over-QUIC and DNS-over-HTTP/3 // servers answer a request whose FIN arrives with it and silently ignore // one whose FIN arrives behind it, which cost an afternoon to find from the // client's side because the packets are acknowledged either way. // // The guarantee is the packet builder's and the timing is // `quic_io.Session.writeStreamFinished`'s: a FIN set before the connection // is flushed leaves with the octets already in the send buffer. var rng_impl = std.Random.DefaultPrng.init(0x9011); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); const id = try client.openBidirectional(); // The query, and the end of it, before anything is sent: this is the order // `writeStreamFinished` keeps and the order the old `writeStream` plus // `finishStream` could not. try client.write(id, "\x00\x05query"); try client.finishStream(id); var buffer: [2048]u8 = undefined; const datagram = (try client.send(&buffer, pair.now)) orelse return error.TestExpectedDatagram; pair.now += std.time.ns_per_ms; try server.receive(datagram.bytes, datagram.path, pair.now); // One datagram, and the server has the whole message *and* knows there is // no more of it -- which is what a DoQ server waits for before it answers. // `streamReceived` is the question, not `streamFinished`: the second is // about the application having read the octets and the first is about // their having arrived, and what the FIN carries is the second fact. try testing.expectEqualStrings("\x00\x05query", server.readable(id)); try testing.expect(server.streamReceived(id)); } test "the other order needs two packets, which is what it used to send" { // The same exchange with the flush in between, kept as a test because it // is what the bug looked like: after the first datagram the peer has every // octet and does not know the stream has ended, and a server that answers // only a finished stream has nothing to answer yet. Legal, and lonely. var rng_impl = std.Random.DefaultPrng.init(0x9012); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); const id = try client.openBidirectional(); try client.write(id, "\x00\x05query"); var buffer: [2048]u8 = undefined; const first = (try client.send(&buffer, pair.now)) orelse return error.TestExpectedDatagram; pair.now += std.time.ns_per_ms; try server.receive(first.bytes, first.path, pair.now); try testing.expectEqualStrings("\x00\x05query", server.readable(id)); try testing.expect(!server.streamReceived(id)); // And then a second datagram whose only purpose is the bit. try client.finishStream(id); const second = (try client.send(&buffer, pair.now)) orelse return error.TestExpectedDatagram; pair.now += std.time.ns_per_ms; try server.receive(second.bytes, second.path, pair.now); try testing.expect(server.streamReceived(id)); } test "RFC 9000 4.6: a peer cannot open more streams than it was allowed" { // "An endpoint that receives a frame with a stream ID exceeding the limit // it has sent MUST treat this as a connection error of type // STREAM_LIMIT_ERROR." The limit is what bounds the memory a connection // commits, so this is the rule that stops a peer deciding it. const one_stream: quic.parameters.Parameters = .{ .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 512, .initial_max_stream_data_bidi_remote = 512, .initial_max_streams_bidi = 1, }; const one_stream_client = comptime encoded: { var buffer: [128]u8 = undefined; var p = one_stream; p.initial_source_connection_id = &client_connection_id; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl = std.Random.DefaultPrng.init(0x9012); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &one_stream_client, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = one_stream, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); // The server obeys the limit it was given: one stream, and no more. try testing.expectEqual(@as(u64, 1), server.peer_stream_limit[0]); _ = try server.openBidirectional(); try testing.expectError(error.StreamLimitError, server.openBidirectional()); // A peer that does not obey it is what the receiving check is for. This // one is made to forget, which is the cheapest way to write down "the // other end is misbehaving" -- and the client must end the connection // rather than open a second stream it never agreed to hold. server.peer_stream_limit[0] = 10; const second = try server.openBidirectional(); try testing.expectEqual(@as(u64, 5), second.value); try server.write(second, "one stream too many"); var buffer: [2048]u8 = undefined; const wire = (try server.send(&buffer, pair.now)).?.bytes; try testing.expectError(error.StreamLimitError, client.receive(wire, 0, pair.now + 1)); } test "a lost STREAM frame is sent again" { // §13.3: QUIC retransmits the frames a lost packet carried, not the // packet. So the octets go back into the stream that produced them and // leave again in a frame with a new packet number — which is what keeps // the acknowledgement for them unambiguous, and the reason loss recovery // had to exist before streams could. var rng_impl = std.Random.DefaultPrng.init(0x9013); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); const id = try client.openBidirectional(); try client.write(id, "a question that has to arrive"); try client.finishStream(id); var buffer: [2048]u8 = undefined; // The datagram carrying it goes into the void. const dropped = (try client.send(&buffer, pair.now)).?.bytes; try testing.expect(dropped.len > 0); pair.now += std.time.ns_per_ms; // Nothing arrived, so nothing can acknowledge it and nothing later can // declare it lost: the probe timeout is the only thing that finds out. try testing.expectEqual(@as(usize, 0), server.readable(.{ .value = 0 }).len); // More than one timer may have to fire. The lost datagram carried the // stream, and a connection that has just finished a handshake also has // acknowledgements outstanding in another space — so the first probe is // not necessarily the one that brings the request back. A caller drives // timers in a loop for exactly this reason. var accepted: ?quic.stream.Id = null; var rounds: usize = 0; while (accepted == null and rounds < 8) : (rounds += 1) { const at = client.timeout() orelse break; pair.now = @max(pair.now, at); client.onTimeout(pair.now); server.onTimeout(pair.now); try pair.settle(); accepted = server.accept(); } try testing.expect(accepted != null); const id_back = accepted.?; try testing.expectEqualStrings("a question that has to arrive", server.readable(id_back)); // And the end of the stream came back with it: §4.5 has the final size // travel on the frame that carries the last octet, so a lost frame takes // the end of the stream with it. server.consume(id_back, server.readable(id_back).len); try testing.expect(server.streamFinished(id_back)); } test "RFC 9000 10.2: a protocol violation reaches the peer" { // "Violations of the protocol lead to an immediate close." Before this, // an endpoint that caught a peer breaking the rules returned an error to // its caller and said nothing, leaving the peer to time out wondering. var rng_impl = std.Random.DefaultPrng.init(0x9020); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); // The server oversteps the flow control it was granted, by being made to // forget it -- the cheapest way to write down "the other end is // misbehaving" without hand-building a packet. The client granted 2048 // octets on this stream and 4096 on the connection; the server is about // to send 3500. const id = try server.openBidirectional(); server.send_credit.limit = 1 << 20; for (&server.streams) |*entry| { if (entry.open) entry.send.credit.limit = 1 << 20; } var payload: [3500]u8 = undefined; for (&payload, 0..) |*b, i| b.* = @truncate(i); try server.write(id, &payload); var buffer: [2048]u8 = undefined; var failed = false; var rounds: usize = 0; while (rounds < 8 and !failed) : (rounds += 1) { const out = (try server.send(&buffer, pair.now)) orelse break; pair.now += std.time.ns_per_ms; client.receive(out.bytes, out.path, pair.now) catch |e| { try testing.expectEqual(error.FlowControlError, e); failed = true; }; } try testing.expect(failed); // §10.2: the client is now closing, and the next thing it sends says so. try testing.expectEqual(quic.close.State.closing, client.closeState().?); const notice = (try client.send(&buffer, pair.now + 2)).?.bytes; // §10.2.2: "After receiving a CONNECTION_CLOSE frame, endpoints enter the // draining state", and a draining endpoint sends nothing at all -- which // is what stops the two of them exchanging closes forever. try server.receive(notice, 0, pair.now + 3); try testing.expectEqual(quic.close.State.draining, server.closeState().?); try testing.expectEqual(@as(?quic.Connection.Datagram, null), try server.send(&buffer, pair.now + 4)); // And the server was told why, in §20.1's vocabulary rather than this // library's. try testing.expectEqual(quic.close.Code.flow_control_error, server.closing.code); } test "RFC 9000 10.2.1: a closing endpoint repeats itself, less and less often" { // "An endpoint in the closing state sends a packet containing a // CONNECTION_CLOSE frame in response to any incoming packet that it // attributes to the connection", and "SHOULD limit the rate at which it // generates packets in the closing state" -- because otherwise a peer // that ignores the close turns the connection into a packet amplifier. var rng_impl = std.Random.DefaultPrng.init(0x9021); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); var buffer: [2048]u8 = undefined; var other: [2048]u8 = undefined; client.close(.no_error, "done here", pair.now); // The first goes at once: the peer has not heard yet. const first = (try client.send(&buffer, pair.now)).?.bytes; try testing.expect(first.len > 0); // And nothing follows it unprompted. try testing.expectEqual(@as(?quic.Connection.Datagram, null), try client.send(&buffer, pair.now)); // The server, which has not seen it, keeps talking. Every packet is // answered at first, then every second, then every fourth. var answers: usize = 0; var packets: usize = 0; while (packets < 16) : (packets += 1) { const id = server.openBidirectional() catch break; server.write(id, "still here") catch break; const chatter = (try server.send(&other, pair.now)) orelse break; var copy: [2048]u8 = undefined; @memcpy(copy[0..chatter.bytes.len], chatter.bytes); try client.receive(copy[0..chatter.bytes.len], chatter.path, pair.now); if (try client.send(&buffer, pair.now)) |_| answers += 1; } // Answered some of them and not all of them, which is the whole of the // rule: silence would leave a peer whose close was lost stuck forever, // and answering every packet would be the amplifier. try testing.expect(answers > 0); try testing.expect(answers < packets); } test "RFC 9000 10.1: a connection nobody speaks on times out silently" { // "The connection is silently closed and its state is discarded when it // remains idle for longer than the minimum of the max_idle_timeout value // advertised by both endpoints." Silently: no CONNECTION_CLOSE, because // the peer is doing the same arithmetic and reaching the same conclusion. const with_timeout: quic.parameters.Parameters = .{ .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_streams_bidi = 4, .max_idle_timeout = 30_000, }; const timeout_client = comptime encoded: { var buffer: [128]u8 = undefined; var p = with_timeout; p.initial_source_connection_id = &client_connection_id; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const timeout_server = comptime encoded: { var buffer: [128]u8 = undefined; var p = with_timeout; // The shorter of the two is what counts, so the server asks for less. p.max_idle_timeout = 5_000; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; // The server's own view of its parameters, which must match what it put // in the handshake -- the coupling `Options.local` documents. var server_side = with_timeout; server_side.max_idle_timeout = 5_000; var rng_impl = std.Random.DefaultPrng.init(0x9022); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &timeout_client, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &timeout_server, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = with_timeout, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = server_side, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); try pair.settle(); // The effective timeout is the smaller of the two, five seconds, not the // thirty this end asked for. const at = client.timeout().?; try testing.expect(at <= pair.now + 5 * std.time.ns_per_s); try testing.expect(at > pair.now + 4 * std.time.ns_per_s); // Nothing happens for long enough. client.onTimeout(at); try testing.expectEqual(quic.close.State.closed, client.closeState().?); // And it said nothing on the way out. var buffer: [2048]u8 = undefined; try testing.expectEqual(@as(?quic.Connection.Datagram, null), try client.send(&buffer, at)); } /// A pair of connections that have finished a handshake, with stream limits. fn streamingPair( seed: u64, client_tls: *quic.tls_handshake.Client, server_tls: *quic.tls_handshake.Server, client: *quic.Connection, server: *quic.Connection, client_memory: quic.Connection.Memory, server_memory: quic.Connection.Memory, rng_impl: *std.Random.DefaultPrng, ) !Pair { rng_impl.* = .init(seed); const rng = rng_impl.random(); client_tls.* = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); server_tls.* = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); client.init(.{ .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, .memory = client_memory, }); server.init(.{ .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, .memory = server_memory, }); var pair: Pair = .{ .client = client, .server = server }; try pair.handshake(); return pair; } test "RFC 9001 6: both ends move to the next key phase" { // §6: "Initiating a key update results in both endpoints updating keys. // This differs from TLS where endpoints can update keys independently." // There is one Key Phase bit for the connection, so there is one phase to // be in -- a peer that saw an update has no choice but to follow. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9030, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); // Something has to have been acknowledged in this phase before an update // is permitted, which §6.1 requires so that both ends are known to have // the keys the update is derived from. const first = try client.openBidirectional(); try client.write(first, "before"); try client.finishStream(first); try pair.settle(); try testing.expect(!client.key_phase); try testing.expect(!server.key_phase); try testing.expect(client.updateKeys(pair.now)); try testing.expect(client.key_phase); // The server has not heard yet. try testing.expect(!server.key_phase); // The next thing the client sends is protected with the new keys and // carries the new bit; the server reads it, and §6.2 gives it no option // but to follow. const second = try client.openBidirectional(); try client.write(second, "after the update"); try client.finishStream(second); try pair.settle(); try testing.expect(server.key_phase); const accepted = server.accept().?; try testing.expectEqualStrings("before", server.readable(accepted)); server.consume(accepted, server.readable(accepted).len); const next_stream = server.accept().?; try testing.expectEqualStrings("after the update", server.readable(next_stream)); // And the connection still works in the other direction, with keys both // ends derived independently and never exchanged. try server.write(next_stream, "and back"); try server.finishStream(next_stream); try pair.settle(); try testing.expectEqualStrings("and back", client.readable(second)); } test "RFC 9001 6.1: a second update waits for the first to be confirmed" { // "An endpoint MUST NOT initiate a subsequent key update unless it has // received an acknowledgment for a packet that was sent protected with // keys from the current key phase. This ensures that keys are available // to both peers before another key update can be initiated." An endpoint // that ratcheted twice in a row would be encrypting with keys its peer // has not derived and cannot derive without the packet it never got. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9031, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); const id = try client.openBidirectional(); try client.write(id, "hello"); try client.finishStream(id); try pair.settle(); try testing.expect(client.updateKeys(pair.now)); // Nothing has been sent in the new phase, let alone acknowledged. try testing.expect(!client.updateKeys(pair.now)); // Send in the new phase and have it acknowledged, and the next update is // permitted. const second = try client.openBidirectional(); try client.write(second, "again"); try client.finishStream(second); try pair.settle(); try testing.expect(client.updateKeys(pair.now)); } test "RFC 9001 6.5: a packet from the old phase still arrives" { // "For receiving packets during a key update, packets protected with // older keys might arrive if they were delayed by the network. Retaining // old packet protection keys allows these packets to be successfully // processed." Discarding them would look like loss, and loss looks like // congestion -- so an endpoint that dropped stragglers would punish itself // for its own key update. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9032, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); const warmup = try client.openBidirectional(); try client.write(warmup, "x"); try client.finishStream(warmup); try pair.settle(); // The server sends something, and it is held up in the network. const id = try server.openBidirectional(); try server.write(id, "sent before the update"); try server.finishStream(id); var delayed: [2048]u8 = undefined; const wire = (try server.send(&delayed, pair.now)).?.bytes; const held = delayed[0..wire.len]; // Meanwhile the client updates its keys, twice over: the straggler was // protected with keys the client has already replaced. try testing.expect(client.updateKeys(pair.now)); try testing.expect(client.key_phase); // And it still reads. try client.receive(held, 0, pair.now + std.time.ns_per_ms); const accepted = client.accept().?; try testing.expectEqualStrings("sent before the update", client.readable(accepted)); } test "RFC 9001 6.6: the confidentiality limit forces an update rather than a leak" { // "Endpoints MUST initiate a key update before sending more protected // packets than the confidentiality limit for the selected AEAD permits." // The limit is 2^23 packets for AES-GCM, which no test is going to reach // honestly, so the counter is wound forward instead -- the interesting // part is what the send path does when it sees it, not the counting. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9033, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); const warmup = try client.openBidirectional(); try client.write(warmup, "x"); try client.finishStream(warmup); try pair.settle(); try testing.expect(!client.key_phase); client.packets_encrypted = 1 << 23; const id = try client.openBidirectional(); try client.write(id, "one more packet"); try client.finishStream(id); try pair.settle(); // It updated instead of encrypting past the limit, and the count started // again with the new keys. try testing.expect(client.key_phase); try testing.expect(client.packets_encrypted < 1 << 23); try testing.expect(server.key_phase); // And the data still arrived. _ = server.accept().?; const second = server.accept().?; try testing.expectEqualStrings("one more packet", server.readable(second)); } test "RFC 9001 6.6: a connection that cannot update is closed rather than continued" { // "If a key update is not possible or integrity limits are reached, the // endpoint MUST stop using the connection... It is RECOMMENDED that // endpoints immediately close the connection with a connection error of // type AEAD_LIMIT_REACHED before reaching a state where key updates are // not possible." Continuing past the limit is the one option the RFC does // not offer. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; const pair = try streamingPair(0x9034, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); // At the limit, with an update forbidden because nothing sent in this // phase has been acknowledged yet. client.packets_encrypted = 1 << 23; client.phase_first_sent = 1 << 40; const id = try client.openBidirectional(); try client.write(id, "this will not go"); try client.finishStream(id); var buffer: [2048]u8 = undefined; const wire = (try client.send(&buffer, pair.now)).?.bytes; try testing.expectEqual(quic.close.State.closing, client.closeState().?); try testing.expectEqual(quic.close.Code.aead_limit_reached, client.closing.code); // And the peer is told, in §20.1's vocabulary. try server.receive(wire, 0, pair.now + 1); try testing.expectEqual(quic.close.State.draining, server.closeState().?); try testing.expectEqual(quic.close.Code.aead_limit_reached, server.closing.code); } test "RFC 9001 4.1.2: a client learns its handshake is confirmed from a frame" { // "The TLS handshake is considered confirmed at the server when the // handshake completes. At the client, the handshake is considered // confirmed when a HANDSHAKE_DONE frame is received." // // The asymmetry is the whole of it. When a server's handshake completes // it holds the client's Finished, so both ends are done. When a client's // completes, its own Finished has only been queued — so a client that // treated completion as confirmation would discard the handshake keys it // still needs to send the one message the other end is waiting for. That // is not a hypothetical: it is what this did before §19.20's frame // existed here, and the handshake stalled on the server every time. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; rng_impl = .init(0x9040); const rng = rng_impl.random(); client_tls = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); server_tls = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); // Hand-driven, because the moment worth looking at is between two // datagrams. Three of them: the client's Initial, the server's flight, // and the client's Finished. var buffer: [2048]u8 = undefined; var now: u64 = 0; for (0..2) |step| { const from_client = (try client.send(&buffer, now)).?.bytes; now += std.time.ns_per_ms; try server.receive(from_client, 0, now); // Stop with the client's Finished delivered and the server's answer // to it still unsent: that answer is what carries the confirmation. if (step == 1) break; const from_server = (try server.send(&buffer, now)).?.bytes; now += std.time.ns_per_ms; try client.receive(from_server, 0, now); } // Both ends have finished the handshake, and only one of them knows that // both ends have finished it. try testing.expect(client.isEstablished()); try testing.expect(server.isEstablished()); try testing.expect(server.isConfirmed()); try testing.expect(!client.isConfirmed()); // A client that is not confirmed may not update its keys (§6), because a // peer that has not confirmed may not have the keys the update is // derived from. try testing.expect(!client.updateKeys(now)); // The frame that closes the gap. const confirmation = (try server.send(&buffer, now)).?.bytes; now += std.time.ns_per_ms; try client.receive(confirmation, 0, now); try testing.expect(client.isConfirmed()); } test "RFC 9001 4.9: keys are discarded as soon as they are not needed" { // §4.9.1: "a client MUST discard Initial keys when it first sends a // Handshake packet and a server MUST discard Initial keys when it first // successfully processes a Handshake packet. Endpoints MUST NOT send // Initial packets after this point." // // The reason is that Initial packets are not authenticated — their keys // come from a connection ID in the clear, so anyone who saw the first // datagram can forge one. Every moment those keys are kept is a moment a // spoofed packet can still disrupt the connection. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9041, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); try pair.settle(); // §4.9.2: "An endpoint MUST discard its Handshake keys when the TLS // handshake is confirmed." Both spaces are gone at both ends, and only // the application space is left. for ([_]*quic.Connection{ &client, &server }) |connection| { try testing.expect(connection.discarded[0]); try testing.expect(connection.discarded[1]); try testing.expect(!connection.discarded[2]); // "This results in abandoning loss recovery state for the Initial // encryption level and ignoring any outstanding Initial packets" — // and §B.9 of RFC 9002 takes them out of the congestion controller's // bytes in flight, since a packet whose keys are gone will never be // acknowledged. try testing.expectEqual(@as(usize, 0), connection.spaces[0].loss.inFlight()); try testing.expectEqual(@as(usize, 0), connection.spaces[1].loss.inFlight()); } try testing.expectEqual(@as(usize, 0), client.congestion.in_flight); // And a stream still works afterwards, which is the point of discarding // rather than of closing. const id = try client.openBidirectional(); try client.write(id, "after the keys are gone"); try client.finishStream(id); try pair.settle(); const accepted = server.accept().?; try testing.expectEqualStrings("after the keys are gone", server.readable(accepted)); } test "RFC 9000 19.20: a server told its own handshake is done is a protocol error" { // "A server MUST treat receipt of a HANDSHAKE_DONE frame as a connection // error of type PROTOCOL_VIOLATION." It is the server's word: §4.1.2 // gives the server no way to *learn* that its handshake is confirmed, // because it already knew. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9042, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); try pair.settle(); // A misbehaving client, made so by being handed the server's own flag. client.owes_handshake_done = true; var buffer: [2048]u8 = undefined; const wire = (try client.send(&buffer, pair.now)).?.bytes; try testing.expectError(error.ProtocolViolation, server.receive(wire, 0, pair.now + 1)); try testing.expectEqual(quic.close.Code.protocol_violation, server.closing.code); } test "RFC 9000 14: no datagram is larger than the path is known to carry" { // "Endpoints SHOULD NOT send UDP datagrams that exceed the maximum size // of the path... unless they have received acknowledgment... that the // path supports that size." 1200 octets is what §14.1 guarantees every // QUIC path supports, and finding out whether a path supports more is // §14.3's path MTU discovery — which is not implemented, so 1200 is the // ceiling and not merely the floor. // // This was found against aioquic, where a 1219-octet datagram was being // built simply because the caller had offered a 2048-octet buffer. What // fits in a caller's buffer is not the same question as what the path // will carry. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9043, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); // A generous buffer, and a stream large enough to fill several datagrams. var buffer: [4096]u8 = undefined; var payload: [1500]u8 = undefined; for (&payload, 0..) |*b, i| b.* = @truncate(i); const id = try server.openBidirectional(); try server.write(id, payload[0..1500]); try server.finishStream(id); var sent: usize = 0; while (try server.send(&buffer, pair.now)) |datagram| { // §14.2: "all QUIC packets that are not sent in a PMTU probe SHOULD // be sized to fit within the maximum datagram size" — which is 1200 // until §14.3's search says otherwise, and a probe is the one thing // allowed to exceed it. const limit = @max(quic.Connection.min_initial_datagram, server.pmtu.current); // The one exception is a probe, which exists precisely to be larger // than what the path is known to carry — §14.2 calls those out by // name, and everything else has to fit. const is_probe = datagram.bytes.len == server.pmtu.probing; try testing.expect(datagram.bytes.len <= limit or is_probe); sent += 1; pair.now += std.time.ns_per_ms; try client.receive(datagram.bytes, datagram.path, pair.now); if (sent > 8) break; } // More than one, or the test proved nothing about the second. try testing.expect(sent > 1); } test "RFC 9000 4.6: a connection outlives its stream limit" { // §4.2 of RFC 9250 puts every DNS query on its own stream, so a // connection that could not reclaim a closed stream would answer // `initial_max_streams_bidi` queries and then refuse. That is what this // did: nothing ever freed a slot and nothing ever sent MAX_STREAMS, and // the interoperability test could not see it because every query there // opened a fresh connection. // // §4.6 suggests the remedy in one sentence: "implementations might choose // to increase limits as streams are closed, to keep the number of streams // available to peers roughly consistent." var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9050, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); try pair.settle(); // Four streams is what the table holds and what the parameters // advertised, so twenty queries is five times around. const limit = stream_limits.initial_max_streams_bidi; try testing.expectEqual(@as(u64, 4), limit); var asked: usize = 0; while (asked < 20) : (asked += 1) { const id = client.openBidirectional() catch |err| { std.debug.print("query {d}: {t}\n", .{ asked, err }); return err; }; // §2.1: identifiers are never reused, so each one is four higher than // the last however many slots have been recycled underneath. try testing.expectEqual(@as(u64, asked * 4), id.value); var question: [32]u8 = undefined; const text = try std.fmt.bufPrint(&question, "query number {d}", .{asked}); try client.write(id, text); try client.finishStream(id); try pair.settle(); const accepted = server.accept().?; try testing.expectEqual(id.value, accepted.value); try testing.expectEqualStrings(text, server.readable(accepted)); server.consume(accepted, server.readable(accepted).len); try server.write(accepted, "answered"); try server.finishStream(accepted); try pair.settle(); try testing.expectEqualStrings("answered", client.readable(id)); client.consume(id, client.readable(id).len); try pair.settle(); // Both ends have given the slot back, so the next query has somewhere // to go. try testing.expect(client.streamFinished(id)); } // And the limits grew rather than the tables filling: §4.6's limit is // cumulative, so what the server advertises now is far above where it // started. try testing.expect(server.advertised_stream_limit[0] > limit); try testing.expect(client.peer_stream_limit[0] > limit); } test "RFC 9000 5.1.1: both ends fill the other's pool after the handshake" { // "An endpoint SHOULD ensure that its peer has a sufficient number of // available and unused connection IDs. Endpoints advertise the number of // active connection IDs they are willing to maintain using the // active_connection_id_limit transport parameter." // // Sufficient means that number: fewer leaves the peer unable to migrate, // since §9.5 forbids reusing an identifier on a new path, and more is a // connection error at its end. const with_ids = comptime limits: { var p = stream_limits; p.active_connection_id_limit = 4; break :limits p; }; const client_side = comptime encoded: { var buffer: [128]u8 = undefined; var p = with_ids; p.initial_source_connection_id = &client_connection_id; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const server_side = comptime encoded: { var buffer: [128]u8 = undefined; var p = with_ids; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl: std.Random.DefaultPrng = .init(0x9060); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_side, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_side, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = with_ids, .rng = rng, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = with_ids, .rng = rng, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); // The handshake gives each end one of the other's identifiers, which // §5.1.1 numbers zero. Nothing more can be issued before the handshake is // confirmed, because §12.4 permits NEW_CONNECTION_ID only in 0-RTT and // 1-RTT packets — so the client, which is not confirmed until the frame // arrives, still has exactly the one. try testing.expectEqual(@as(usize, 1), client.issued.active()); try pair.settle(); // And then both pools fill to the table's size, which is what an // endpoint can hold and no more than the peer agreed to maintain. try testing.expectEqual(quic.connection_id.capacity, client.issued.active()); try testing.expectEqual(quic.connection_id.capacity, server.issued.active()); try testing.expectEqual(quic.connection_id.capacity, client.received.active()); try testing.expectEqual(quic.connection_id.capacity, server.received.active()); // Every identifier either end issued is one it answers to: "when an // endpoint issues a connection ID, it MUST accept packets that carry this // connection ID for the duration of the connection". for (&server.issued.entries) |*entry| { if (!entry.in_use) continue; try testing.expect(server.issued.accepts(entry.id())); } // §9.5 needs one that is not in use, and now there is one. try testing.expect(client.received.spare(client.peerId()) != null); } test "RFC 9000 5.1.2: changing which identifier a peer is addressed by" { // "An endpoint can change the connection ID it uses for a peer to another // available one at any time during the connection... Sending a // RETIRE_CONNECTION_ID frame indicates that the connection ID will not be // used again and requests that the peer replace it." // // This is the operation §9.5 makes compulsory before migrating, and it // needs a spare — which is what the pool exists for. const with_ids = comptime limits: { var p = stream_limits; p.active_connection_id_limit = 4; break :limits p; }; const client_side = comptime encoded: { var buffer: [128]u8 = undefined; var p = with_ids; p.initial_source_connection_id = &client_connection_id; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const server_side = comptime encoded: { var buffer: [128]u8 = undefined; var p = with_ids; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl: std.Random.DefaultPrng = .init(0x9061); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_side, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_side, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = with_ids, .rng = rng, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = with_ids, .rng = rng, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); try pair.settle(); var before: [20]u8 = undefined; @memcpy(before[0..client.peerId().len], client.peerId()); const before_len = client.peerId().len; try testing.expect(client.rotatePeerId()); try testing.expect(!std.mem.eql(u8, before[0..before_len], client.peerId())); // The retirement travels, the server frees the slot, and §5.1.1 has it // supply a replacement — so the pool is full again rather than one // smaller. try pair.settle(); try testing.expectEqual(quic.connection_id.capacity, server.issued.active()); try testing.expectEqual(quic.connection_id.capacity, client.received.active()); // And the connection still works, addressed by its new name. const id = try client.openBidirectional(); try client.write(id, "under a new name"); try client.finishStream(id); try pair.settle(); const accepted = server.accept().?; try testing.expectEqualStrings("under a new name", server.readable(accepted)); } test "RFC 9000 19.16: a peer cannot retire the identifier it is addressing" { // "An endpoint MUST NOT send this frame if it has a Sequence Number // matching the connection ID in the Destination Connection ID field of // the packet in which the frame is contained." A peer that did would be // retiring the name it used to reach us, in the packet that used it. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9062, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); try pair.settle(); // A misbehaving client, made so by being told to retire sequence zero — // which is the only identifier it has and the one it is writing to. try client.received.retire(0); var buffer: [2048]u8 = undefined; const wire = (try client.send(&buffer, pair.now)).?.bytes; try testing.expectError(error.ProtocolViolation, server.receive(wire, 0, pair.now + 1)); try testing.expectEqual(quic.close.Code.protocol_violation, server.closing.code); } test "RFC 9000 5.1.1: a packet addressed to nothing this endpoint issued is dropped" { // "When an endpoint issues a connection ID, it MUST accept packets that // carry this connection ID" — and the converse is what keeps a server // from answering on behalf of a connection it does not have. The // identifier is the only thing a short header carries to attribute it by. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9063, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); try pair.settle(); const id = try client.openBidirectional(); try client.write(id, "a question"); try client.finishStream(id); var buffer: [2048]u8 = undefined; const wire = (try client.send(&buffer, pair.now)).?.bytes; // Rewrite the Destination Connection ID to something the server never // issued. The packet is still protected with the right keys, so what // rejects it is the identifier and not the cryptography. // // A short header is one octet of flags followed by the identifier, and // the length is known because the receiver chose it. try testing.expect(wire[0] & 0x80 == 0); wire[1] ^= 0xff; try server.receive(wire, 0, pair.now + 1); try testing.expectEqual(@as(usize, 0), server.readable(id).len); try testing.expectEqual(@as(?quic.close.State, null), server.closeState()); } test "RFC 9000 9.3: a peer that moves is followed, and made to prove it" { // "Receiving a packet from a new peer address containing a non-probing // frame indicates that the peer has migrated to that address. If the // recipient permits the migration, it MUST send subsequent packets to the // new peer address and MUST initiate path validation to verify the peer's // ownership of the address if validation is not already underway." // // Both halves, in that order. Following the peer is what makes migration // work; validating the address is what stops a forged source address // turning the connection into a weapon aimed at a third party. const with_ids = comptime limits: { var p = stream_limits; p.active_connection_id_limit = 4; break :limits p; }; const client_side = comptime encoded: { var buffer: [128]u8 = undefined; var p = with_ids; p.initial_source_connection_id = &client_connection_id; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const server_side = comptime encoded: { var buffer: [128]u8 = undefined; var p = with_ids; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl: std.Random.DefaultPrng = .init(0x9070); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_side, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_side, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = with_ids, .rng = rng, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = with_ids, .rng = rng, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); try pair.settle(); // §8.1: the handshake validated the path it happened on, so the server // will send anything there. try testing.expect(server.paths.find(0).?.validated); try testing.expectEqual(@as(quic.path.Id, 0), server.paths.active); // The client moves. Everything it sends now arrives from path 1, which // the server has never heard from — a NAT rebinding looks exactly like // this, and so does an attacker forging the address of a victim. var buffer: [2048]u8 = undefined; const id = try client.openBidirectional(); try client.write(id, "from somewhere else"); try client.finishStream(id); var now = pair.now; const moved = (try client.send(&buffer, now)).?; now += std.time.ns_per_ms; try server.receive(moved.bytes, 1, now); // The server followed: §9.3's "MUST send subsequent packets to the new // peer address". try testing.expectEqual(@as(quic.path.Id, 1), server.paths.active); // And it does not believe the address yet. try testing.expect(!server.paths.find(1).?.validated); // §21.1.1.1: until it does, it may send three times what arrived and no // more. The datagram that moved the connection is the whole allowance. try testing.expect(server.paths.sendable(1) <= moved.bytes.len * 3); // What the server sends now is a challenge, on the new path, containing // eight octets the client cannot have predicted. var probe: [2048]u8 = undefined; const from_server = (try server.send(&probe, now)).?; try testing.expectEqual(@as(quic.path.Id, 1), from_server.path); // The client answers it — §8.2.2's "MUST respond by echoing the data" — // and that is what validates the address. now += std.time.ns_per_ms; try client.receive(from_server.bytes, 0, now); const response = (try client.send(&buffer, now)).?; now += std.time.ns_per_ms; try server.receive(response.bytes, 1, now); try testing.expect(server.paths.find(1).?.validated); // §9.4: "on confirming a peer's ownership of its new address, an endpoint // MUST immediately reset the congestion controller and round-trip time // estimator for the new path to initial values" — the capacity of the new // path is not the capacity of the old one, and carrying the old estimate // over is how a sender floods a path it has never measured. try testing.expectEqual( quic.congestion.initialWindow(quic.congestion.min_datagram_size), server.congestion.window, ); try testing.expect(!server.rtt.sampled); // And the connection works from the new address: the request that moved // it is answered. const accepted = server.accept().?; try testing.expectEqualStrings("from somewhere else", server.readable(accepted)); server.consume(accepted, server.readable(accepted).len); try server.write(accepted, "and answered"); try server.finishStream(accepted); var steps: usize = 0; while (steps < 8) : (steps += 1) { const out = (try server.send(&probe, now)) orelse break; now += std.time.ns_per_ms; try client.receive(out.bytes, 0, now); const back = (try client.send(&buffer, now)) orelse continue; now += std.time.ns_per_ms; try server.receive(back.bytes, 1, now); } try testing.expectEqualStrings("and answered", client.readable(id)); } test "RFC 9000 9.3: a stale packet from an old address is not a migration" { // "An endpoint only changes the address to which it sends packets in // response to the highest-numbered non-probing packet. This ensures that // an endpoint does not send packets to an old peer address in the case // that it receives reordered packets." // // Which is also what stops an attacker replaying an old packet from an // address of its choosing to drag a connection somewhere it has left. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9071, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); try pair.settle(); var buffer: [2048]u8 = undefined; var now = pair.now; // Two datagrams, delivered out of order. The newer one arrives first from // a new address, so the connection moves; the older one arrives after, // from a third address, and must not move it back. const first = try client.openBidirectional(); try client.write(first, "one"); try client.finishStream(first); const older = (try client.send(&buffer, now)).?; var held: [2048]u8 = undefined; @memcpy(held[0..older.bytes.len], older.bytes); const held_len = older.bytes.len; const second = try client.openBidirectional(); try client.write(second, "two"); try client.finishStream(second); now += std.time.ns_per_ms; const newer = (try client.send(&buffer, now)).?; now += std.time.ns_per_ms; try server.receive(newer.bytes, 1, now); try testing.expectEqual(@as(quic.path.Id, 1), server.paths.active); // The straggler, from somewhere else again. The server has room to // track a third path, and reads the packet -- but its number is lower // than what path 1 has shown, so the connection stays where it is. now += std.time.ns_per_ms; try server.receive(held[0..held_len], 2, now); try testing.expectEqual(@as(quic.path.Id, 1), server.paths.active); } test "RFC 9000 8.1: a Retry makes the client start again with a token" { // Retry is how a server refuses to keep state for an address it has not // checked: it answers the Initial with a token and nothing else, and // commits nothing until the token comes back from the same address. // // The Retry packet here is built by hand, because the library does not // send them — a Retry precedes connection state, which is the whole // point of it, so it belongs to whatever owns the socket. What is being // tested is the client's side, against a packet assembled from the RFC's // own description rather than from this code's idea of one. const retry_source = [_]u8{ 0xa1, 0xa2, 0xa3, 0xa4 }; const server_with_retry = comptime encoded: { var buffer: [128]u8 = undefined; var p = stream_limits; p.initial_source_connection_id = &retry_source; // §7.3: after a Retry, the server echoes the connection ID from the // client's *first* Initial here, and names the Retry's own Source // Connection ID separately. p.original_destination_connection_id = &destination_connection_id; p.retry_source_connection_id = &retry_source; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl: std.Random.DefaultPrng = .init(0x9080); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var buffer: [2048]u8 = undefined; const first = (try client.send(&buffer, 0)).?; try testing.expectEqual(@as(usize, quic.Connection.min_initial_datagram), first.bytes.len); try testing.expectEqualSlices(u8, &destination_connection_id, client.peerId()); // The server's answer: a token, and a connection ID of its own choosing. var retry_buffer: [128]u8 = undefined; const retry = try quic.retry.write( &retry_buffer, &destination_connection_id, &client_connection_id, &retry_source, "an opaque token", ); try client.receive(retry, 0, 1); // §17.2.5.1: "the client MUST use the value from the Retry packet in the // Destination Connection ID field of subsequent packets", and §5.2 of RFC // 9001 derives the Initial keys from it — so a Retry costs a client its // whole first flight, not just a header field. try testing.expectEqualSlices(u8, &retry_source, client.peerId()); // §17.2.5.3: "The client MUST NOT reset the packet number for any packet // number space after processing a Retry packet." The first Initial was // number 0, so the second is not. try testing.expectEqual(@as(u64, 1), client.spaces[0].next_number); // And it starts again, carrying the token this time. const second = (try client.send(&buffer, 2)).?; const header = try quic.packet.parse(second.bytes, 0); try testing.expectEqual(quic.packet.Kind.initial, header.kind); try testing.expectEqualStrings("an opaque token", header.token); try testing.expectEqualSlices(u8, &retry_source, header.destination); // A second Retry is ignored: §17.2.5.2's "a client MUST accept and // process at most one Retry packet for each connection attempt". A peer // that could send two could walk a connection attempt in circles. const again = try quic.retry.write( &retry_buffer, &destination_connection_id, &client_connection_id, &.{ 0xb1, 0xb2 }, "another token", ); try client.receive(again, 0, 3); try testing.expectEqualSlices(u8, &retry_source, client.peerId()); // The handshake completes from there, and §7.3's checks are what make the // Retry itself trustworthy: the server names the connection ID it used // in the Retry, and the client compares it with what it saw. var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_with_retry, .alpn_protocols = &.{"doq"}, .rng = rng, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &retry_source, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server, .now = 4 }; try server.receive(second.bytes, 0, pair.now); try pair.handshake(); try testing.expect(client.isEstablished()); try testing.expectEqualSlices( u8, &retry_source, client.peer.?.retry_source_connection_id.?, ); } test "RFC 9001 5.8 and 9000 7.3: a Retry nobody could have written is refused" { // Two defences, at two layers. §5.8's integrity tag proves the sender saw // the client's Initial — an off-path attacker did not, and cannot compute // the tag over a connection ID it never observed. §7.3's transport // parameter proves it *afterwards*, inside the encrypted handshake, which // is what catches an on-path attacker who could compute the tag. var rng_impl: std.Random.DefaultPrng = .init(0x9081); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var buffer: [2048]u8 = undefined; _ = (try client.send(&buffer, 0)).?; // A Retry whose tag was computed over a connection ID the client never // chose, which is what an attacker who did not see the Initial is // reduced to. var retry_buffer: [128]u8 = undefined; const forged = try quic.retry.write( &retry_buffer, &.{ 0xde, 0xad, 0xbe, 0xef }, &client_connection_id, &.{ 0xc1, 0xc2 }, "a forged token", ); try client.receive(forged, 0, 1); // Ignored entirely: the client is still talking to the address it chose, // with no token and nothing reset. try testing.expectEqualSlices(u8, &destination_connection_id, client.peerId()); try testing.expectEqual(@as(usize, 0), client.token_len); try testing.expectEqual(@as(?usize, null), client.retry_source_len); } test "RFC 9000 7.3: a server that names a Retry it never sent is refused" { // "Presence of the retry_source_connection_id transport parameter when no // Retry packet was received" is a connection error. The parameter is a // claim about what happened on the wire, and a claim that contradicts // what this endpoint saw is somebody rewriting history. const lying = comptime encoded: { var buffer: [128]u8 = undefined; var p = stream_limits; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; p.retry_source_connection_id = &.{ 0x99, 0x99 }; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl: std.Random.DefaultPrng = .init(0x9082); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &lying, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var buffer: [2048]u8 = undefined; const hello = (try client.send(&buffer, 0)).?; try server.receive(hello.bytes, 0, 1); const reply = (try server.send(&buffer, 2)).?; try testing.expectError(error.TransportParameterError, client.receive(reply.bytes, 0, 3)); } test "RFC 9000 8.1.4: a Retry token too large to hold changes nothing" { // "There is no need for a single well-defined format for the token // because the server that generates the token also consumes it" — so a // client has to hold whatever it is handed, and one it cannot hold is a // Retry it cannot act on. // // Acting on half of it is what this used to do, and it is worse than // ignoring it: adopting the new connection ID and re-deriving the Initial // keys, then sending an Initial with no token, makes the server Retry // again and the client do the same thing forever. aioquic found it, // because its tokens are 256 octets where the ones in these tests are // fifteen. var rng_impl: std.Random.DefaultPrng = .init(0x9083); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var buffer: [2048]u8 = undefined; _ = (try client.send(&buffer, 0)).?; // A token larger than any this client can keep, and small enough to // arrive in a datagram — which is the only kind that matters, since §14 // means nothing larger reaches it. var huge: [600]u8 = @splat(0x7a); var retry_buffer: [1024]u8 = undefined; const retry = try quic.retry.write( &retry_buffer, &destination_connection_id, &client_connection_id, &.{ 0xd1, 0xd2 }, &huge, ); try client.receive(retry, 0, 1); // Nothing moved: the connection ID, the keys and the token are as they // were, so the client goes on with the attempt it had rather than a // broken version of a new one. try testing.expectEqualSlices(u8, &destination_connection_id, client.peerId()); try testing.expectEqual(@as(usize, 0), client.token_len); try testing.expect(!client.retry_seen); try testing.expectEqual(@as(?usize, null), client.retry_source_len); // And a Retry it *can* hold still works afterwards, which is the point of // not having spent the one-Retry budget on the one it refused. const ok = try quic.retry.write( &retry_buffer, &destination_connection_id, &client_connection_id, &.{ 0xd3, 0xd4 }, "a token that fits", ); try client.receive(ok, 0, 2); try testing.expect(client.retry_seen); try testing.expectEqualSlices(u8, &.{ 0xd3, 0xd4 }, client.peerId()); } test "RFC 9000 10.3: a stateless reset ends a connection the peer has forgotten" { // "A crash or outage might result in peers continuing to send data to an // endpoint that is unable to properly continue the connection." A // stateless reset is the one message an endpoint can send about a // connection it has entirely forgotten — no packet number, no encryption // and no frame, because an endpoint that lost its state has no keys and // no numbers. What it has is a static key and the connection ID off the // packet that just arrived. const server_reset_key: quic.stateless_reset.Key = @splat(0x5e); const server_token = quic.stateless_reset.token(server_reset_key, &server_connection_id); const server_side = comptime encoded: { // An HMAC at compile time costs more branches than the default // allows, and the point of computing it here is that the parameters // blob has to outlive the handshake that borrows it. @setEvalBranchQuota(20_000); var buffer: [128]u8 = undefined; var p = stream_limits; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; // §10.3: "servers can also issue a stateless_reset_token transport // parameter during the handshake that applies to the connection ID // that it selected during the handshake. Note that clients cannot use // the stateless_reset_token transport parameter because their // transport parameters do not have confidentiality protection." p.stateless_reset_token = quic.stateless_reset.token( @splat(0x5e), &server_connection_id, ); const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; var rng_impl: std.Random.DefaultPrng = .init(0x9090); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_side, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, .reset_key = server_reset_key, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); try pair.settle(); try testing.expectEqualSlices(u8, &server_token, &client.peer.?.stateless_reset_token.?); // The server forgets everything — a crash, a restart, a load balancer // sending the next datagram somewhere else. All it can do with the next // packet is read the connection ID off it and recompute the token. const recomputed = quic.stateless_reset.token(server_reset_key, &server_connection_id); var out: [64]u8 = undefined; const the_reset = try quic.stateless_reset.write(&out, rng, recomputed, 60); try client.receive(the_reset, 0, pair.now); // §10.3.1: "the endpoint MUST enter the draining period and not send any // further packets on this connection." Draining rather than closing, // because there is nobody left to tell. try testing.expectEqual(quic.close.State.draining, client.closeState().?); var buffer: [2048]u8 = undefined; try testing.expectEqual( @as(?quic.Connection.Datagram, null), try client.send(&buffer, pair.now + 1), ); } test "RFC 9000 10.3.1: a datagram ending in the wrong sixteen octets is not a reset" { // A stateless reset is recognised only by its trailing octets matching a // token the peer actually issued. Anything else is an unreadable packet, // which is a different thing: §5.2 has those dropped in silence, and // treating one as a teardown would let anyone end a connection by sending // rubbish. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9091, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); try pair.settle(); var rubbish: [64]u8 = undefined; var prng: std.Random.DefaultPrng = .init(3); prng.random().bytes(&rubbish); rubbish[0] = (rubbish[0] & 0x3f) | 0x40; try client.receive(&rubbish, 0, pair.now); try testing.expectEqual(@as(?quic.close.State, null), client.closeState()); // And the connection still works, which is the point of not believing it. const id = try client.openBidirectional(); try client.write(id, "still here"); try client.finishStream(id); try pair.settle(); const accepted = server.accept().?; try testing.expectEqualStrings("still here", server.readable(accepted)); } test "RFC 9000 10.3.1: a token that was never issued is never checked" { // "An endpoint MUST NOT check for any stateless reset tokens associated // with connection IDs it has not used or for connection IDs that have // been retired." // // The identifier the handshake used arrives without a token — a server // names one in the `stateless_reset_token` transport parameter instead, // and §10.3 says a client "cannot use" that parameter at all, because its // transport parameters have no confidentiality protection. So the entry // for that identifier holds no token, and holding a placeholder instead // would be a token checked against every arriving datagram that the peer // never issued. // // Which is not a theoretical tidiness argument. A zero placeholder means // any datagram ending in sixteen zero octets reads as a teardown, and // aioquic pads its Initial packets with zeros — so the first thing this // did against a real peer was reset itself on the client's own // ClientHello. var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; var pair = try streamingPair(0x9092, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); try pair.settle(); // Neither end has been given a token: `streamingPair` advertises none and // configures no reset key, so there is nothing legitimate to match. for (&server.received.entries) |*entry| { if (!entry.in_use) continue; try testing.expectEqual(@as(?[quic.stateless_reset.token_len]u8, null), entry.token); } // A datagram that is all zeros, which is the shape a padded packet takes // when an implementation pads the datagram rather than the payload. var zeros: [1200]u8 = @splat(0); zeros[0] = 0x40; try server.receive(&zeros, 0, pair.now); try testing.expectEqual(@as(?quic.close.State, null), server.closeState()); // And the connection is unharmed, which is the whole of the claim. const id = try client.openBidirectional(); try client.write(id, "unbothered"); try client.finishStream(id); try pair.settle(); const accepted = server.accept().?; try testing.expectEqualStrings("unbothered", server.readable(accepted)); } test "RFC 9000 14.3: the largest datagram a path carries is found by asking" { // There is no way to ask a path how large a datagram it will carry. ICMP // would tell an endpoint, and §14.2.1 spends its length explaining why // that cannot be trusted — forgeable, often filtered, and sometimes about // a different path. So the only reliable question is the empirical one: // send a datagram of the size in question and see whether it comes back // acknowledged. // // The network here drops anything above 1350 octets, which is what a // tunnel or a PPPoE link looks like from the inside. const carries = 1350; var rng_impl: std.Random.DefaultPrng = undefined; var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; const pair = try streamingPair(0x90a0, &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &rng_impl); // §14.3.1: nothing is probed until the handshake is confirmed, because // until then every datagram is carrying handshake data that a failed // probe would cost a retransmission. try testing.expectEqual(quic.mtu.base, client.pmtu.current); var buffer: [2048]u8 = undefined; var now = pair.now; var dropped: usize = 0; var steps: usize = 0; while (steps < 200) : (steps += 1) { var moved = false; if (try client.send(&buffer, now)) |datagram| { now += std.time.ns_per_ms; if (datagram.bytes.len <= carries) { try server.receive(datagram.bytes, datagram.path, now); } else { dropped += 1; } moved = true; } if (try server.send(&buffer, now)) |datagram| { now += std.time.ns_per_ms; if (datagram.bytes.len <= carries) { try client.receive(datagram.bytes, datagram.path, now); } else { dropped += 1; } moved = true; } if (!moved) { // §14.4 and RFC 8899 §5.1.1: a probe that goes unanswered is // retried before its size is written off, and the timers are what // notice it went unanswered. const at = client.timeout() orelse server.timeout() orelse break; now = @max(now, at); client.onTimeout(now); server.onTimeout(now); } if (client.pmtu.state == .complete and server.pmtu.state == .complete) break; } try testing.expectEqual(quic.mtu.State.complete, client.pmtu.state); // Found the path's size, to within the granularity the search stops at. try testing.expect(client.pmtu.current <= carries); try testing.expect(client.pmtu.current > carries - 16); try testing.expect(client.pmtu.current > quic.mtu.base); // And it had to be told no at least once to learn that. try testing.expect(dropped > 0); // §14.4: "loss of a QUIC packet that is carried in a PMTU probe... SHOULD // NOT trigger a congestion control reaction." Probes are meant to be // lost, and an endpoint that halved its window each time would be // punishing itself for asking — after a search that dropped several, the // window is where it started. try testing.expectEqual( quic.congestion.initialWindow(quic.congestion.min_datagram_size), client.congestion.window, ); // And now ordinary traffic uses what was learned: a stream large enough // to fill a datagram fills the *new* one. var payload: [4000]u8 = undefined; for (&payload, 0..) |*b, i| b.* = @truncate(i); const id = try client.openBidirectional(); try client.write(id, &payload); try client.finishStream(id); var largest: usize = 0; steps = 0; while (steps < 40) : (steps += 1) { const datagram = (try client.send(&buffer, now)) orelse break; largest = @max(largest, datagram.bytes.len); now += std.time.ns_per_ms; if (datagram.bytes.len <= carries) { try server.receive(datagram.bytes, datagram.path, now); } if (try server.send(&buffer, now)) |back| { now += std.time.ns_per_ms; try client.receive(back.bytes, back.path, now); } } try testing.expect(largest > quic.mtu.base); try testing.expect(largest <= carries); } test "RFC 8446 2.2: a QUIC connection resumes an earlier one" { // Resumption, carried by QUIC rather than by a record layer: the // NewSessionTicket is a CRYPTO frame at the application level, because // §4.1.1 of RFC 9001 says "post-handshake messages are sent using 1-RTT // keys" and QUIC has no other place to put one. // // What it buys is the flight that carries a certificate. What it costs is // that the ticket is a bearer credential: §4.2.11.2's binder is the only // thing standing between copying one off the wire and having the session. const ticket_key: quic.tls_handshake.TicketKey = @splat(0x9b); var session: quic.tls_handshake.Session = .{}; var certificate_bytes: usize = 0; var resumed_bytes: usize = 0; for (0..2) |round| { var rng_impl: std.Random.DefaultPrng = .init(0x90b0 + @as(u64, round)); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 1_700_000_000, .insecure_skip_verify = true, .session = &session, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, .ticket_key = ticket_key, .now_sec = 1_700_000_000, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; // Count what the server's first flight costs, which is where the // saving shows up. var buffer: [2048]u8 = undefined; const hello = (try client.send(&buffer, pair.now)).?; try server.receive(hello.bytes, hello.path, pair.now + 1); var flight: usize = 0; var probe: [2048]u8 = undefined; while (try server.send(&probe, pair.now + 2)) |datagram| { flight += datagram.bytes.len; try client.receive(datagram.bytes, datagram.path, pair.now + 3); } if (round == 0) certificate_bytes = flight else resumed_bytes = flight; pair.now += 4; try pair.handshake(); try pair.settle(); try testing.expect(client.isEstablished()); // The first connection ends with a ticket in hand; the second proves // it was worth keeping. try testing.expect(session.valid); if (round == 1) { try testing.expect(client_tls.inner.resumed); try testing.expect(server_tls.inner.resumed); } // And it still carries traffic, which is the only thing that makes // any of it worth doing. const id = try client.openBidirectional(); try client.write(id, "resumed or not"); try client.finishStream(id); try pair.settle(); const accepted = server.accept().?; try testing.expectEqualStrings("resumed or not", server.readable(accepted)); } // What resumption saves is the Certificate and CertificateVerify // messages, and this server has none to send — `auth = null`, which is // what every test here uses. So the second flight is not smaller; it is // very slightly *larger*, by the `pre_shared_key` extension the // ServerHello now carries. // // Asserting a saving here would be asserting something the fixture cannot // demonstrate. The saving is real against a server with a certificate // chain — the interoperability test has one — and what this test is for // is that both ends agree they resumed and the connection still works. try testing.expect(resumed_bytes > 0 and certificate_bytes > 0); } test "RFC 9001 4.6: a client sends application data in its first flight" { // 0-RTT. The client writes a request into the same datagram as its // ClientHello, and the server answers it before either end has finished // the handshake — which is the whole of what resumption was building // towards, and the reason §4.6 exists at all. // // What makes it possible is that the key protecting that data comes from // the pre-shared key alone: §7.1 of RFC 8446 derives the // client_early_traffic_secret from the Early Secret and a transcript of // the ClientHello, so it is computable by an endpoint that has heard // nothing and by one that has heard only that. const ticket_key: quic.tls_handshake.TicketKey = @splat(0x4e); var session: quic.tls_handshake.Session = .{}; // -- the first connection, which is ordinary and ends with a ticket ---- { var rng_impl: std.Random.DefaultPrng = .init(0x0bb0); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 1_700_000_000, .insecure_skip_verify = true, .session = &session, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, .ticket_key = ticket_key, .now_sec = 1_700_000_000, .early_data = true, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); try pair.settle(); try testing.expect(client.isEstablished()); // §4.6.1: the ticket carries the permission, and without it the // second connection below would have nothing to attempt. try testing.expect(session.valid); try testing.expect(session.early_data); } // -- the second, which spends it --------------------------------------- var rng_impl: std.Random.DefaultPrng = .init(0x0bb1); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 1_700_000_000, .insecure_skip_verify = true, .session = &session, .early_data = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, .ticket_key = ticket_key, .now_sec = 1_700_000_000, .early_data = true, }); // §7.4.1 of RFC 9000: the limits a 0-RTT sender acts on are the ones the // server set last time, because this time it has not spoken yet. var remembered_ids: quic.parameters.IdStorage = .{}; const remembered = try quic.parameters.parse( session.peerTransportParameters(), &remembered_ids, .server, ); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, .remembered = remembered, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); // The request is written before anything has been sent, which is the // only way it can travel in the first flight. const id = try client.openBidirectional(); try client.write(id, "who is example.com?"); try client.finishStream(id); var buffer: [2048]u8 = undefined; const first = (try client.send(&buffer, 0)).?; // §14.1: a datagram carrying a client's Initial is still padded to 1200 // octets, and here the padding has something to share the space with. try testing.expectEqual(@as(usize, 1200), first.bytes.len); var pair: Pair = .{ .client = &client, .server = &server }; try server.receive(first.bytes, first.path, 1); // The server has the request, and has not finished the handshake: it has // not seen the client's Finished and cannot have, because the client has // not been told what to put in it. try testing.expect(!server.isEstablished()); const accepted = server.accept().?; try testing.expectEqualStrings("who is example.com?", server.readable(accepted)); try testing.expect(server.streamReceived(accepted)); // And the handshake still finishes, on top of a connection that has // already carried traffic. pair.now = 2; try pair.handshake(); try pair.settle(); try testing.expect(client.isEstablished()); try testing.expect(client.earlyDataAccepted()); try testing.expect(server.earlyDataAccepted()); } test "RFC 9001 4.6.2: refused 0-RTT resets every stream" { // A server may resume the session and still decline the early data, and // then "all connection characteristics that the client assumed might be // incorrect. This includes the choice of application protocol, transport // parameters, and any application configuration. The client therefore // MUST reset the state of all streams, including application state bound // to those streams." // // So the request written before the handshake is not sent again behind // the application's back: the stream it was on is gone, the application // is told, and it decides what to send now that it knows what the server // actually agreed to. const ticket_key: quic.tls_handshake.TicketKey = @splat(0x7a); var session: quic.tls_handshake.Session = .{}; { var rng_impl: std.Random.DefaultPrng = .init(0x1cc1); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 1_700_000_000, .insecure_skip_verify = true, .session = &session, }); // This server issues tickets that permit early data, so that the // refusal below is a change of mind rather than a ticket that never // offered it -- which is the case §4.6.3 is about. var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, .ticket_key = ticket_key, .now_sec = 1_700_000_000, .early_data = true, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); try pair.settle(); try testing.expect(session.early_data); } var rng_impl: std.Random.DefaultPrng = .init(0x1cc2); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 1_700_000_000, .insecure_skip_verify = true, .session = &session, .early_data = true, }); // The same ticket key, so the session still resumes. Only the early data // is refused. var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, .ticket_key = ticket_key, .now_sec = 1_700_000_000, .early_data = false, }); var remembered_ids: quic.parameters.IdStorage = .{}; const remembered = try quic.parameters.parse( session.peerTransportParameters(), &remembered_ids, .server, ); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, .remembered = remembered, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = stream_limits, }); const id = try client.openBidirectional(); try client.write(id, "who is example.com?"); try client.finishStream(id); var buffer: [2048]u8 = undefined; const first = (try client.send(&buffer, 0)).?; try server.receive(first.bytes, first.path, 1); // The 0-RTT packet in that datagram was undecryptable and is gone. A // server with no key for a packet does not answer it and does not // complain about it -- §5.2 of RFC 9001: "an endpoint without the // necessary keys... MAY discard it". try testing.expect(server.accept() == null); var pair: Pair = .{ .client = &client, .server = &server }; pair.now = 2; try pair.handshake(); try pair.settle(); try testing.expect(client.isEstablished()); try testing.expect(!client.earlyDataAccepted()); try testing.expect(client.earlyDataRejected()); // Nothing arrived, and nothing of the stream is left to send it again. try testing.expect(server.accept() == null); try testing.expectError(error.StreamStateError, client.write(id, "again")); try testing.expectEqual(@as(u64, 0), client.send_credit.used); // And the refused packets have left the congestion controller's count. // Nothing will ever acknowledge them, so bytes still counted in flight // would be window this connection never gets back. try testing.expectEqual(@as(usize, 0), client.congestion.in_flight); // The server never saw stream 0, so the numbering starts again: a stream // the server would otherwise be told was opened and never used. const again = try client.openBidirectional(); try testing.expectEqual(id, again); try client.write(again, "who is example.com?"); try client.finishStream(again); try pair.settle(); const accepted = server.accept().?; try testing.expectEqualStrings("who is example.com?", server.readable(accepted)); try testing.expect(server.streamReceived(accepted)); } /// A client resuming a session against a server whose transport parameters /// may have changed since: the first connection is run to completion for its /// ticket, and the second is left before its first packet, its client /// remembering what the first server said (§7.4.1). const Resumption = struct { session: quic.tls_handshake.Session = .{}, remembered_ids: quic.parameters.IdStorage = .{}, first_params: [256]u8 = undefined, second_params: [256]u8 = undefined, rng_impl: std.Random.DefaultPrng, client_tls: quic.tls_handshake.Client = undefined, server_tls: quic.tls_handshake.Server = undefined, client_memory: quic.Connection.Storage(.{}) = .{}, server_memory: quic.Connection.Storage(.{}) = .{}, client: quic.Connection = undefined, server: quic.Connection = undefined, const ticket_key: quic.tls_handshake.TicketKey = @splat(0x7b); fn create(first: quic.parameters.Parameters, second: quic.parameters.Parameters, accept_early: bool) !*Resumption { const r = try testing.allocator.create(Resumption); errdefer testing.allocator.destroy(r); r.* = .{ .rng_impl = .init(0x7e57) }; const rng = r.rng_impl.random(); const first_encoded = try serverParameters(first, &r.first_params); const second_encoded = try serverParameters(second, &r.second_params); { var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 1_700_000_000, .insecure_skip_verify = true, .session = &r.session, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = first_encoded, .alpn_protocols = &.{"doq"}, .rng = rng, .ticket_key = ticket_key, .now_sec = 1_700_000_000, .early_data = true, }); r.client.init(.{ .memory = r.client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, }); r.server.init(.{ .memory = r.server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = first, }); var pair: Pair = .{ .client = &r.client, .server = &r.server }; try pair.handshake(); try pair.settle(); try testing.expect(r.session.early_data); } r.client_tls = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 1_700_000_000, .insecure_skip_verify = true, .session = &r.session, .early_data = true, }); r.server_tls = .init(.{ .auth = null, .transport_parameters = second_encoded, .alpn_protocols = &.{"doq"}, .rng = rng, .ticket_key = ticket_key, .now_sec = 1_700_000_000, .early_data = accept_early, }); const remembered = try quic.parameters.parse( r.session.peerTransportParameters(), &r.remembered_ids, .server, ); r.client_memory = .{}; r.server_memory = .{}; r.client.init(.{ .memory = r.client_memory.memory(), .role = .client, .handshake = r.client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, .remembered = remembered, }); r.server.init(.{ .memory = r.server_memory.memory(), .role = .server, .handshake = r.server_tls.handshake(), .local_id = &server_connection_id, .local = second, }); return r; } fn destroy(r: *Resumption) void { testing.allocator.destroy(r); } fn serverParameters(p: quic.parameters.Parameters, buffer: []u8) ![]const u8 { var q = p; q.initial_source_connection_id = &server_connection_id; q.original_destination_connection_id = &destination_connection_id; return quic.parameters.write(&q, buffer, .server); } /// A request sent as 0-RTT, then the handshake. fn run(r: *Resumption) !void { const id = try r.client.openBidirectional(); try r.client.write(id, "who is example.com?"); try r.client.finishStream(id); var pair: Pair = .{ .client = &r.client, .server = &r.server }; try pair.handshake(); try pair.settle(); try testing.expect(r.client.sent_early); } }; /// `stream_limits`, halved: a server that has become less generous. const lowered_limits: quic.parameters.Parameters = limits: { var p = stream_limits; p.initial_max_data = 2048; p.initial_max_stream_data_bidi_local = 1024; p.initial_max_stream_data_bidi_remote = 1024; p.initial_max_streams_bidi = 2; break :limits p; }; test "RFC 9000 7.4.1: a server that accepts 0-RTT may not lower its limits" { // "If 0-RTT data is accepted by the server, the server MUST NOT reduce // any limits or alter any values that might be violated by the client // with its 0-RTT data." const r = try Resumption.create(stream_limits, lowered_limits, true); defer r.destroy(); try testing.expectError(error.ProtocolViolation, r.run()); try testing.expectEqual(quic.close.Code.protocol_violation, r.client.closing.code); } test "RFC 9000 7.4.1: a server that refuses 0-RTT may lower its limits, and they apply" { // The rule is about 0-RTT the server accepted. One it refused was never // read, so nothing the client did under the remembered limits stands -- // and the server's new limits are the ones in force, not the larger of // the two. const r = try Resumption.create(stream_limits, lowered_limits, false); defer r.destroy(); try r.run(); try testing.expect(!r.client.earlyDataAccepted()); try testing.expectEqual(@as(?quic.close.State, null), r.client.closeState()); try testing.expectEqual(@as(u64, 2048), r.client.send_credit.limit); try testing.expectEqual(@as(u64, 2), r.client.peer_stream_limit[0]); // RFC 9001 §4.6.2: the stream opened under the remembered limits is gone // with them, so both of the server's two are this client's to use. try testing.expect(r.client.earlyDataRejected()); try testing.expect(r.server.accept() == null); _ = try r.client.openBidirectional(); _ = try r.client.openBidirectional(); try testing.expectError(error.StreamLimitError, r.client.openBidirectional()); } test "RFC 9000 7.4.1: the parameters a client may not remember are not used" { // "A client MUST NOT use remembered values for the following parameters: // ack_delay_exponent, max_ack_delay, initial_source_connection_id, // original_destination_connection_id, preferred_address, // retry_source_connection_id, and stateless_reset_token. The client // MUST use the server's new values in the handshake instead; if the // server does not provide new values, the default values are used." var first = stream_limits; first.stateless_reset_token = @splat(0x3c); first.max_ack_delay = 200; first.ack_delay_exponent = 10; const r = try Resumption.create(first, stream_limits, true); defer r.destroy(); const before = r.client.peer.?; try testing.expectEqual(@as(?[16]u8, null), before.stateless_reset_token); try testing.expectEqual(@as(u64, 25), before.max_ack_delay); try testing.expectEqual(@as(u64, 3), before.ack_delay_exponent); try testing.expectEqual(@as(?[]const u8, null), before.initial_source_connection_id); // What may be remembered still is. try testing.expectEqual(stream_limits.initial_max_data, before.initial_max_data); } /// Finds a connection's own record of a stream, so that a test can make an /// endpoint misbehave in one specific way. /// /// Used below to build a peer that sends a frame no correct implementation /// sends. The alternative is a hand-built packet, which needs keys the test /// does not hold; flipping the one field that a guard consults produces /// exactly the frame in question out of the real send path, and documents /// what that guard is for. fn streamEntry(c: *quic.Connection, id: quic.stream.Id) *@TypeOf(c.streams[0]) { for (&c.streams) |*entry| { if (entry.open and entry.id.value == id.value) return entry; } unreachable; } test "RFC 9000 3.1: a unidirectional stream has one half, at one end" { // §2.1 gives unidirectional streams their own identifier space and §4.6 // their own limit, so opening one costs nothing from the bidirectional // allowance and neither can starve the other. What makes them different // to use is §3.1: the stream "has a sending part only at the end that // opened it", so every operation on the half that does not exist needs an // answer. // // This is the shape an application protocol needs for a channel that is // not a request and a response -- HTTP/3's control stream and its two // QPACK streams are all of it, which is why this exists at all. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x5171); const client = &fixture.client; const server = &fixture.server; const before = client.next_stream_index[0]; const id = try client.openUnidirectional(); try testing.expectEqual(quic.stream.Directionality.unidirectional, id.directionality()); // Opening it did not spend the bidirectional allowance. try testing.expectEqual(before, client.next_stream_index[0]); try testing.expectEqual(@as(u64, 1), client.next_stream_index[1]); // §2.1: a client's first unidirectional stream is identifier 2, not 0 -- // the four types interleave in one number space two bits wide. try testing.expectEqual(@as(u64, 2), id.value); try client.write(id, "a channel, not a conversation"); try client.finishStream(id); try pair.settle(); const accepted = server.accept().?; try testing.expectEqual(id.value, accepted.value); try testing.expectEqualStrings("a channel, not a conversation", server.readable(accepted)); // §3.1: the receiving end cannot write back on it. There is no half to // write to, which is a different thing from a half that has closed. try testing.expectError(error.StreamStateError, server.write(accepted, "no")); try testing.expectError(error.StreamStateError, server.finishStream(accepted)); try testing.expectError(error.StreamStateError, server.resetStream(accepted, 0)); // And the sending end will never read anything on it. Reported as nothing // having arrived rather than as an error, because that is the honest // answer and a caller's loop is the same either way. try testing.expectEqualStrings("", client.readable(id)); // The other direction works, out of a separate space again: the server's // first unidirectional stream is 3. const back = try server.openUnidirectional(); try testing.expectEqual(@as(u64, 3), back.value); try server.write(back, "and back"); try server.finishStream(back); try pair.settle(); const heard = client.accept().?; try testing.expectEqual(back.value, heard.value); try testing.expectEqualStrings("and back", client.readable(heard)); } test "RFC 9000 4.6: the two stream limits are counted apart" { // "These limits apply to streams of each type" -- two limits, two // identifier spaces, and a MAX_STREAMS frame whose type bit says which of // them it raises. One counter for both would let a peer that opened many // unidirectional streams exhaust the allowance for bidirectional ones, // which is the thing two spaces exist to prevent. var fixture: Pair.Connected = undefined; _ = try fixture.start(0x5172); const client = &fixture.client; // The fixture grants four bidirectional and three unidirectional. try testing.expectEqual(@as(u64, 4), client.peer_stream_limit[0]); try testing.expectEqual(@as(u64, 3), client.peer_stream_limit[1]); // Spending the unidirectional allowance entirely leaves the other one // untouched. for (0..3) |_| _ = try client.openUnidirectional(); try testing.expectError(error.StreamLimitError, client.openUnidirectional()); _ = try client.openBidirectional(); // And raising the bidirectional limit does not raise this one. §19.11's // type bit is load-bearing rather than decoration. client.peer_stream_limit[0] = 99; try testing.expectError(error.StreamLimitError, client.openUnidirectional()); } test "RFC 9000 19.10: credit for a half the peer does not have is an error" { // Two of §19's rules exist only because a unidirectional stream has one // half: a MAX_STREAM_DATA "for a receive-only stream" (§19.10) and a // RESET_STREAM "for a send-only stream" (§19.4), each a connection error // of type STREAM_STATE_ERROR. They are easy to leave out, because a // correct peer never sends either and nothing in a working connection // ever notices they are missing. // // So the peer here is made incorrect, in one field: the guard that stops // this endpoint sending the frame is switched off, and the real send path // then produces exactly the frame in question. { var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x5173); const id = try fixture.client.openUnidirectional(); try fixture.client.write(id, "x"); try pair.settle(); // The client only sends on this stream, so it has no credit to // extend. Pretending otherwise makes it offer some. const entry = streamEntry(&fixture.client, id); entry.has_recv = true; entry.recv.credit.limit = 0; try testing.expectError(error.StreamStateError, pair.settle()); } // And the mirror: the server only receives on such a stream, so a // RESET_STREAM from it names a sending half it does not have. { var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x5174); const id = try fixture.client.openUnidirectional(); try fixture.client.write(id, "x"); try pair.settle(); const accepted = fixture.server.accept().?; streamEntry(&fixture.server, accepted).has_send = true; try fixture.server.resetStream(accepted, 7); try testing.expectError(error.StreamStateError, pair.settle()); } } test "RFC 9000 4.5: a stream reset while blocked on flow control keeps the connection" { // A reset declares the stream's final size, and the peer charges it // against the limit it granted. What was written and never sent -- held // back because the peer had not granted room for it -- is not part of the // stream, and counting it declared a stream longer than the peer allowed. // The peer then ended the whole connection, for one abandoned stream. // // Found by zig-http's HTTP/3 client cancelling an upload part way: the // body was being written faster than the server's window opened, so the // buffer was full of octets that had not left when the reset went. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x4505); const client = &fixture.client; const server = &fixture.server; const id = try client.openBidirectional(); // Everything the send buffer will take, which is more than the server's // stream window: the server reads none of it, so its window never slides. var chunk: [1024]u8 = undefined; @memset(&chunk, 'x'); while (true) client.write(id, &chunk) catch |err| switch (err) { error.NoRoom => break, else => |e| return e, }; try pair.settle(); // The case being tested, stated rather than assumed: written past what // was sent, and blocked on the peer's limit. const sender = streamEntry(client, id); try testing.expect(sender.send.data.len > sender.send.data.sent); try testing.expect(sender.send.blocked()); try client.resetStream(id, 0x10c); // Before the fix this was the server closing the connection. try pair.settle(); const accepted = server.accept().?; const receiver = streamEntry(server, accepted); try testing.expectEqual(quic.stream.Recv.State.reset_received, receiver.recv.state); try testing.expectEqual(@as(?u64, 0x10c), receiver.recv.reset_code); // The final size is what arrived, since everything sent did arrive. try testing.expectEqual(@as(?u64, sender.send.data.sent), receiver.recv.final_size); try testing.expectEqual(@as(?quic.close.State, null), server.closeState()); try testing.expectEqual(@as(?quic.close.State, null), client.closeState()); // And the connection carries the next stream. const next = try client.openBidirectional(); try client.write(next, "still here"); try pair.settle(); } test "RFC 9000 3.5: a STOP_SENDING is answered rather than merely obeyed" { // "An endpoint that receives a STOP_SENDING frame MUST send a // RESET_STREAM frame if the stream is in the 'Ready' or 'Send' state." // Obeying it is not enough: the peer asked this end to stop and has to be // told that it did, and told the final size, because §4.5 makes that // number part of the flow control accounting both ends keep. // // The failure this guards against is silent in every in-process test that // does not look for it. An endpoint that moved straight to its own // terminal state would stop sending, free the slot, and satisfy every // question about its own behaviour -- while the peer waited. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x57a1); const client = &fixture.client; const server = &fixture.server; const id = try client.openBidirectional(); try client.write(id, "a long answer nobody wants"); try pair.settle(); const accepted = server.accept().?; // The server has read enough and wants no more of it. try server.stopSending(accepted, 0x1234); try pair.settle(); // The client obeyed, and said so: its sending half is reset, carrying the // code the server chose rather than one of its own, and the server has // acknowledged the RESET_STREAM -- which is the observable difference // between answering a STOP_SENDING and ignoring one. const sender = streamEntry(client, id); try testing.expectEqual(quic.stream.Send.State.reset_received, sender.send.state); try testing.expectEqual(@as(?u64, 0x1234), sender.send.reset_code); try testing.expect(!sender.send.reset_pending); // And the server was told, which is the part that would be missing if // obeying were all that happened. It knows the code and the final size, // and §4.5 needs the second of those to keep its flow control accounting // straight. const receiver = streamEntry(server, accepted); try testing.expectEqual(quic.stream.Recv.State.reset_received, receiver.recv.state); try testing.expectEqual(@as(?u64, 0x1234), receiver.recv.reset_code); try testing.expectEqual(@as(?u64, "a long answer nobody wants".len), receiver.recv.final_size); // The stream is not closed, because the server never finished its own // sending half — §3.4 closes a stream when both directions are done, and // only one of them is. try testing.expect(server.streamOpen(accepted)); } test "RFC 9221 4: a datagram is carried, and is not a stream" { // The extension exists for applications that want QUIC's handshake, // congestion control and path validation without its retransmissions -- // real-time media, and the tunnelling of somebody else's unreliable // protocol. §5.2: "DATAGRAM frames... SHOULD NOT be retransmitted", // because an application that wanted them retransmitted would have used a // stream. var fixture: Pair.Connected = undefined; const pair = try fixture.startWith( 0x9221, datagram_limits, &datagram_client_parameters, &datagram_server_parameters, ); const client = &fixture.client; const server = &fixture.server; // §3: the extension is negotiated by the parameter being present at all, // so both ends know before anything is sent. try testing.expect(client.datagramsAllowed()); try testing.expect(server.datagramsAllowed()); try client.sendDatagram("unreliable, unordered, unrepeated"); try pair.settle(); try testing.expectEqualStrings("unreliable, unordered, unrepeated", server.readDatagram().?); server.takeDatagram(); try testing.expect(server.readDatagram() == null); // It cost no stream: §4 gives a DATAGRAM frame no identifier and no // offset, so there is nothing for the stream limits to count. try testing.expectEqual(@as(u64, 0), server.peer_streams_retired[0]); try testing.expect(server.streamAt(0) == null); // They keep their order, which §4 does promise between datagrams that // both arrive -- "DATAGRAM frames... are delivered in the order they were // sent" is not stated, but nothing reorders them here and an application // should not have to wonder. try client.sendDatagram("first"); try client.sendDatagram("second"); try pair.settle(); try testing.expectEqualStrings("first", server.readDatagram().?); server.takeDatagram(); try testing.expectEqualStrings("second", server.readDatagram().?); server.takeDatagram(); // And the other way, on the same connection, with streams alongside. try server.sendDatagram("and back"); const id = try server.openUnidirectional(); try server.write(id, "on a stream"); try server.finishStream(id); try pair.settle(); try testing.expectEqualStrings("and back", client.readDatagram().?); const accepted = client.accept().?; try testing.expectEqualStrings("on a stream", client.readable(accepted)); } test "RFC 9221 3: a peer that did not ask for datagrams is not sent any" { // "An endpoint that receives the parameter with a value of 0, or that does // not receive it at all, MUST NOT send DATAGRAM frames." The extension is // negotiated by the parameter, so a connection where one end implements // it and the other does not is an ordinary connection rather than a // failure -- which is the property that lets an extension be deployed at // all. var fixture: Pair.Connected = undefined; _ = try fixture.start(0x9222); // the fixture without the parameter try testing.expect(!fixture.client.datagramsAllowed()); try testing.expect(!fixture.server.datagramsAllowed()); try testing.expectError(error.StreamStateError, fixture.client.sendDatagram("no")); // And §3's other half, which is the one with teeth: receiving one anyway // is a connection error. The peer here is made to send a frame it should // not by giving it the belief that the far end asked. var other: Pair.Connected = undefined; const pair = try other.start(0x9223); other.client.peer.?.max_datagram_frame_size = 1200; try other.client.sendDatagram("uninvited"); try testing.expectError(error.ProtocolViolation, pair.settle()); } test "RFC 9221 3: the limit is on the frame, not on what it carries" { // "The max_datagram_frame_size transport parameter is an integer value // that indicates the maximum size of a DATAGRAM frame (including the // frame type, length, and payload) the endpoint is willing to receive." // // Measuring the payload instead is the obvious mistake and costs the // connection: a frame one or two octets over is one the peer closes on, // and the octets in question are the ones the sender added itself. var fixture: Pair.Connected = undefined; const pair = try fixture.startWith( 0x9224, datagram_limits, &datagram_client_parameters, &datagram_server_parameters, ); const client = &fixture.client; // 1200 is the whole frame, so the largest payload it admits is smaller // than that by the type octet and the length's two. var payload: [1200]u8 = @splat('x'); try testing.expectError(error.NoRoom, client.sendDatagram(&payload)); // And a frame that fits the parameter but not the path is refused too, // which is the gap §3 warns about: the parameter "is not a guarantee that // the path can carry" such a frame, and this one leaves no room for the // packet header and the AEAD tag around it. Refused rather than queued, // because there is no offset to split a datagram at (§5.1) and nothing // that will ever make it smaller -- queuing it would be queuing it // forever, and the application would never learn why. try testing.expectError(error.NoRoom, client.sendDatagram(payload[0 .. 1200 - 3])); // A payload that leaves room for the packet around it does arrive. try client.sendDatagram(payload[0..1000]); try pair.settle(); try testing.expectEqual(@as(usize, 1000), fixture.server.readDatagram().?.len); } test "RFC 9000 9.6: a client moves to the address the server preferred" { // §9.6: "servers MAY communicate a preferred address... at the end of the // handshake", and a client that takes the invitation has to do three // things in order — address the server by the identifier that came with // it, prove the new path, and only then trust it with traffic. // // The identifier is the part with no wire signal behind it. §5.1.1 fixes // its sequence number at 1 by specification rather than carrying it in // the parameter, so an implementation that did not enter it in its own // table would find the pool empty at the moment it needed a fresh name, // and would migrate wearing the one it arrived in — which is exactly what // §9.5's unlinkability is about. var rng_impl = std.Random.DefaultPrng.init(0x0906); const rng = rng_impl.random(); var client_tls: quic.tls_handshake.Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &streaming_client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &preferred_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); var client_memory: quic.Connection.Storage(.{}) = .{}; var client: quic.Connection = undefined; client.init(.{ .memory = client_memory.memory(), .role = .client, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, .rng = rng, }); var server_memory: quic.Connection.Storage(.{}) = .{}; var server: quic.Connection = undefined; server.init(.{ .memory = server_memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, // The same parameters it gave TLS. §5.1.1 reserves sequence 1 for // this identifier, so the connection has to know about it as well as // the handshake does. .local = preferred_limits, .rng = rng, }); var pair: Pair = .{ .client = &client, .server = &server }; try pair.handshake(); try pair.settle(); // The client was told where the server would rather be, and what to call // it once it gets there. const preferred = client.preferredAddress().?; try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, &preferred.ipv4); try testing.expectEqual(@as(u16, 8853), preferred.ipv4_port); try testing.expectEqualSlices(u8, &preferred_connection_id, preferred.connection_id); // A server has nothing to be told: it is the end that advertises this. try testing.expect(server.preferredAddress() == null); // §9: not before the handshake is confirmed, which a client learns from // HANDSHAKE_DONE rather than from its own progress. try testing.expect(client.confirmed); // The caller has opened a socket to 192.0.2.1:8853 and calls that path 1. // The library never learns the address, which is the point: what it does // with the number is §9's business and what the number *means* is not. const before = client.peerId(); var was: [20]u8 = undefined; @memcpy(was[0..before.len], before); try client.migrateToPreferredAddress(1, pair.now); // §9.6.3: the path is not trusted until it answers, so until then the // connection stays on the original address, under its original name. try testing.expect(!client.pathValidated(1)); try testing.expectEqualSlices(u8, was[0..before.len], client.peerId()); // Once the probe is answered the client moves. §9.5: a new path is worn // under a new name, and the name is the one §5.1.1 numbered 1 -- which // is only available because the parameter put it in the table. The // server, migrated to, validates in the other direction as §9.3 // requires, and the connection carries traffic on the new path. try pair.settle(); try testing.expect(client.pathValidated(1)); try testing.expectEqualSlices(u8, &preferred_connection_id, client.peerId()); const id = try client.openBidirectional(); try client.write(id, "on the preferred address"); try client.finishStream(id); try pair.settle(); const accepted = server.accept().?; try testing.expectEqualStrings("on the preferred address", server.readable(accepted)); } test "RFC 9000 4.1: a retransmission spends no connection credit" { // "The sum of the final sizes on all streams" is what connection flow // control counts -- offsets, not transmissions. So sending the same // octets twice costs once, and the second time costs nothing. // // Charging per transmission instead is a deadlock and not merely an // over-count, because the two halves compound: credit is spent on // retransmissions, and then retransmissions are refused for want of // credit that only the peer can grant, by receiving exactly the octets // that are not being sent. Through zig-http it looked like two // concurrent downloads hanging; underneath, a connection had spent // sixty-four megabytes of credit on a hundred and thirty kilobytes of // body. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x0401); const client = &fixture.client; const id = try client.openBidirectional(); const payload: [900]u8 = @splat('r'); try client.write(id, &payload); // Sent, and deliberately not delivered: nothing is acknowledged, so the // probe timeout is what happens next. var buffer: [2048]u8 = undefined; var now = pair.now; while (try client.send(&buffer, now)) |_| { now += std.time.ns_per_ms; } const after_first = client.send_credit.used; try testing.expect(after_first >= payload.len); // Several probe timeouts' worth of putting the same flight back on the // wire. Each doubles the backoff, so the clock has to move a long way to // get more than a handful. for (0..6) |_| { now += 2 * std.time.ns_per_s; client.onTimeout(now); while (try client.send(&buffer, now)) |_| { now += std.time.ns_per_ms; } } // Whatever went out, the connection has spent credit for the offsets it // reached and not for the packets it sent. try testing.expectEqual(after_first, client.send_credit.used); } test "the window a connection advertises is the memory it was given" { // What `Sizes` is for. A connection promises what its buffers hold and // the caller decides how much that is, so the same code serves a server // that wants sixteen streams of four kilobytes and one that wants a // megabyte of flight on a fast path -- and neither has to edit this // library to get it. // // The two numbers are checked against each other rather than against a // constant: advertising more than the buffer holds is the mistake that // took a connection down with INTERNAL_ERROR on the first large upload, // and `Connection.init` asserts it can keep what it promises. const big: quic.Connection.Sizes = .{ .send_window = 64 * 1024, .recv_window = 32 * 1024, .tracked = 128, }; // Sixty-four kilobytes of flight is fifty-odd of §14.1's smallest // datagrams, so a hundred and twenty-eight is comfortably above the floor // the connection insists on. try testing.expect(big.tracked >= big.trackedFloor()); var memory = try testing.allocator.create(quic.Connection.Storage(big)); defer testing.allocator.destroy(memory); var rng_impl = std.Random.DefaultPrng.init(0x5123); var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &streaming_server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng_impl.random(), }); const connection = try testing.allocator.create(quic.Connection); defer testing.allocator.destroy(connection); connection.init(.{ .role = .server, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .memory = memory.memory(), // Exactly what the receive buffers hold, which is the most that may // honestly be advertised. .local = .{ .initial_max_data = 128 * 1024, .initial_max_stream_data_bidi_local = 32 * 1024, .initial_max_stream_data_bidi_remote = 32 * 1024, .initial_max_stream_data_uni = 32 * 1024, .initial_max_streams_bidi = 4, .initial_max_streams_uni = 3, }, }); // The connection took the sizes from the memory rather than from a // constant: one stream's share of each buffer is what a stream gets. try testing.expectEqual(@as(usize, 64 * 1024), connection.send_window); try testing.expectEqual(@as(usize, 32 * 1024), connection.recv_window); try testing.expectEqual(@as(usize, 128), connection.spaces[2].loss.sent.len); // And every stream slot really has that much room, which is the only // thing any of it was for. The last slot as well as the first, because // the buffers are carved out of one slice and an arithmetic mistake there // would overlap two streams rather than run off the end -- which is data // corruption between streams and not a crash. const first = &connection.streams[0]; const last = &connection.streams[quic.Connection.max_streams - 1]; try testing.expectEqual(@as(usize, 64 * 1024), first.send.data.buffer.len); try testing.expectEqual(@as(usize, 64 * 1024), last.send.data.buffer.len); try testing.expectEqual(@as(usize, 32 * 1024), first.recv.data.buffer.len); try testing.expectEqual(@as(usize, 32 * 1024), last.recv.data.buffer.len); // Nose to tail and in order, with nothing shared. const span = @intFromPtr(last.send.data.buffer.ptr) - @intFromPtr(first.send.data.buffer.ptr); try testing.expectEqual((quic.Connection.max_streams - 1) * 64 * 1024, span); } test "RFC 9000 18.2: disable_active_migration does not forbid the preferred address" { // "A client that receives disable_active_migration MUST NOT use a new // local address when sending to the address that the server provided" -- // and then, in the same paragraph, "this transport parameter does not // prohibit connection migration after a client has acted on a // preferred_address transport parameter". // // Two rules that look contradictory and are not: the server forbade the // client from wandering, and separately invited it to one place. The // exemption has its own entry point rather than a flag, so it cannot be // taken by accident. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x0907); const client = &fixture.client; try testing.expect(client.confirmed); // This fixture's server forbids neither and offers nothing, so the // ordinary migration is allowed and the preferred one has no address to // go to. try client.migrateTo(1, pair.now); try testing.expectError(error.StreamStateError, client.migrateToPreferredAddress(2, pair.now)); // And with migration disabled, the ordinary one is refused. client.peer.?.disable_active_migration = true; try testing.expectError(error.ProtocolViolation, client.migrateTo(3, pair.now)); } test "RFC 9000 8.2.1: a datagram carrying a path challenge is expanded to 1200" { // "An endpoint MUST expand datagrams that contain a PATH_CHALLENGE frame // to at least 1200 bytes", and §8.2.2 says the same of PATH_RESPONSE. // // Two things rest on it. What is being proved is not that the peer is // reachable but that the path carries what §14 requires of it -- a path // validated by a sixty-octet datagram may still be unable to carry a real // one, and has been validated into uselessness. And validation would // often not terminate without it: the answering endpoint is held to three // times what arrived (§21.1.1.1), so a challenge that arrives small buys // an answer that may be too small to send, after which neither end has // anything left to do and the path is never validated at all. // // That second failure is what this found. It cannot happen until some // endpoint initiates a migration rather than reacting to one, which // nothing here did before §9.6 gave a client a reason to. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x0821); const client = &fixture.client; try client.migrateTo(1, pair.now); var buffer: [2048]u8 = undefined; const datagram = (try client.send(&buffer, pair.now)).?; try testing.expectEqual(@as(paths_id, 1), datagram.path); try testing.expectEqual(@as(usize, 1200), datagram.bytes.len); // And the answer is expanded too, which is §8.2.2 and the half that // matters for termination: the server is the end that is rate limited. try fixture.server.receive(datagram.bytes, datagram.path, pair.now + 1); const answer = (try fixture.server.send(&buffer, pair.now + 2)).?; try testing.expectEqual(@as(usize, 1200), answer.bytes.len); } const paths_id = @TypeOf(@as(quic.Connection.Datagram, undefined).path); test "RFC 9000 3: a stream carries both directions at once, with neither half ended" { // Which is what a tunnel is, and what a request-and-response is not. Every // other stream test here has one end finish its half before the other // answers -- §4.2 of RFC 9250 makes the FIN the end of a DNS query, and // an HTTP request is the same shape -- so nothing has ever checked that a // stream still works when neither half has closed. // // RFC 9114's extended CONNECT needs exactly that: after the response head // the stream is a tunnel, and both ends keep sending on it for as long as // they like. A transport that only delivered what followed a FIN would // pass every test in this file and carry no tunnel at all. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x0003); const client = &fixture.client; const server = &fixture.server; const id = try client.openBidirectional(); try client.write(id, "from the client"); // Deliberately no `finishStream`. try pair.settle(); const accepted = server.accept().?; try testing.expectEqualStrings("from the client", server.readable(accepted)); server.consume(accepted, "from the client".len); try testing.expect(!server.streamReceived(accepted)); // And back the other way, on the same stream, with both halves still // open. try server.write(accepted, "from the server"); try pair.settle(); try testing.expectEqualStrings("from the server", client.readable(id)); client.consume(id, "from the server".len); // And again, in both directions, because a tunnel is not one exchange. try client.write(id, "more"); try pair.settle(); try testing.expectEqualStrings("more", server.readable(accepted)); server.consume(accepted, "more".len); try server.write(accepted, "and more"); try pair.settle(); try testing.expectEqualStrings("and more", client.readable(id)); } test "a write refused for room says whether more buffer would have helped" { // The send buffer is smaller than what the peer has granted, so a stream // that fills it is a stream the buffer is holding back rather than the // path or the peer. // Only the *sending* buffer is small: `recv_window` stays where the // fixture's advertised limits need it, since §4.1 makes an advertised // window a promise and `init` asserts the buffers can keep it. var fixture: Pair.ConnectedSized(.{ .send_window = 1024, .recv_window = 2048, .tracked = 64, }) = undefined; const pair = try fixture.start(0x0501); const client = &fixture.client; const id = try client.openBidirectional(); const payload: [1024]u8 = @splat('b'); try client.write(id, &payload); try testing.expectEqual(@as(u64, 0), client.bufferBound()); // Sent and deliberately not delivered, so nothing is acknowledged and // `compact` frees nothing: the buffer stays full of octets that have all // already gone, which is the state the signal is about. var buffer: [2048]u8 = undefined; var now = pair.now; while (try client.send(&buffer, now)) |_| { now += std.time.ns_per_ms; } // The path would take more -- the congestion window is barely touched -- // and so would the peer, which granted twice this buffer. Nothing but a // larger buffer was missing. try testing.expectError(error.NoRoom, client.write(id, "x")); try testing.expectEqual(@as(u64, 1), client.bufferBound()); } test "a write refused for want of credit is not blamed on the buffer" { // The same refusal, with the buffer exactly as large as the peer's grant: // a bigger one would have bought nothing, because the octets to fill it // could not have been sent. Counting this would tell a caller to spend // memory on a stream that is waiting for a MAX_STREAM_DATA. var fixture: Pair.ConnectedSized(.{ .send_window = 2048, .recv_window = 2048, .tracked = 64, }) = undefined; const pair = try fixture.start(0x0502); const client = &fixture.client; const id = try client.openBidirectional(); const payload: [2048]u8 = @splat('c'); try client.write(id, &payload); var buffer: [2048]u8 = undefined; var now = pair.now; while (try client.send(&buffer, now)) |_| { now += std.time.ns_per_ms; } try testing.expectError(error.NoRoom, client.write(id, "x")); try testing.expectEqual(@as(u64, 0), client.bufferBound()); } test "a send window can grow under a stream that is already using it" { // Three states at once when the buffer changes, which is what makes this // worth a test: octets already acknowledged and dropped from the front, // so `base` is not zero; octets written and not yet sent, so there is // something to copy; and a stream that has to go on working afterwards. var fixture: Pair.ConnectedSized(.{ .send_window = 1024, .recv_window = 2048, .tracked = 64, }) = undefined; const pair = try fixture.start(0x0601); const client = &fixture.client; const server = &fixture.server; const id = try client.openBidirectional(); const first: [1024]u8 = @splat('a'); try client.write(id, &first); try pair.settle(); // Acknowledged and compacted away, so the window's base is now 1024 and // every offset it keeps is a stream offset rather than an index. var seen: usize = 0; seen += server.readable(id).len; server.consume(id, seen); try testing.expectEqual(@as(usize, 1024), seen); // Written and deliberately not sent, so the buffer has something in it // that the copy has to carry across. const second: [512]u8 = @splat('b'); try client.write(id, &second); try testing.expectError(error.NoRoom, client.write(id, &first)); var bigger: [quic.Connection.max_streams * 2048]u8 = undefined; client.growSend(&bigger); try testing.expectEqual(@as(usize, 2048), client.sendWindow()); // Room that did not exist a moment ago, at the offset the stream was // already at. const third: [512]u8 = @splat('c'); try client.write(id, &third); try pair.settle(); var tail: [2048]u8 = undefined; const arrived = server.readable(id); @memcpy(tail[0..arrived.len], arrived); try testing.expectEqual(@as(usize, 1024), arrived.len); try testing.expectEqualSlices(u8, &second, tail[0..512]); try testing.expectEqualSlices(u8, &third, tail[512..1024]); } /// A Version Negotiation packet as §17.2.1 lays one out, for a client that /// sent `destination` and `source`. fn versionNegotiation( out: []u8, destination: []const u8, source: []const u8, versions: []const u32, ) []u8 { // The swap, done by hand here rather than through `writeVersionNegotiation`, // so that a fault in that writer cannot hide behind a test that used it to // build its own input. var at: usize = 0; out[at] = 0xc0; at += 1; std.mem.writeInt(u32, out[at..][0..4], 0, .big); at += 4; out[at] = @intCast(source.len); at += 1; @memcpy(out[at..][0..source.len], source); at += source.len; out[at] = @intCast(destination.len); at += 1; @memcpy(out[at..][0..destination.len], destination); at += destination.len; for (versions) |v| { std.mem.writeInt(u32, out[at..][0..4], v, .big); at += 4; } return out[0..at]; } test "RFC 9000 6.2: a client abandons the attempt when no version is shared" { // "A client that supports only this version of QUIC MUST abandon the // current connection attempt if it receives a Version Negotiation // packet." Abandoning and not closing: the server has just said it cannot // read this version, so a CONNECTION_CLOSE would be written with keys it // has no way to open. var fixture: Pair.Connected = undefined; _ = try fixture.start(0x0701); var client: quic.Connection = undefined; var memory: quic.Connection.Storage(.{}) = .{}; var rng_impl = std.Random.DefaultPrng.init(0x0702); client.init(.{ .memory = memory.memory(), .role = .client, .handshake = fixture.client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, .rng = rng_impl.random(), }); var out: [128]u8 = undefined; const wire = versionNegotiation( &out, &destination_connection_id, &client_connection_id, &.{ 0x1a2a3a4a, 0x00000002 }, ); try client.receive(wire, 0, 0); try testing.expectEqual(@as(?quic.close.State, .draining), client.closeState()); } test "RFC 9000 6.2: a Version Negotiation packet listing our own version is discarded" { // "A client MUST discard a Version Negotiation packet that lists the QUIC // version selected by the client." A server that supported it would not // have sent this, so §21.12's downgrade is what the rule turns away. var fixture: Pair.Connected = undefined; _ = try fixture.start(0x0703); var client: quic.Connection = undefined; var memory: quic.Connection.Storage(.{}) = .{}; var rng_impl = std.Random.DefaultPrng.init(0x0704); client.init(.{ .memory = memory.memory(), .role = .client, .handshake = fixture.client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = stream_limits, .rng = rng_impl.random(), }); var out: [128]u8 = undefined; const wire = versionNegotiation( &out, &destination_connection_id, &client_connection_id, &.{ 0x00000002, 1 }, ); try client.receive(wire, 0, 0); try testing.expectEqual(@as(?quic.close.State, null), client.closeState()); } test "RFC 9000 6.2: a Version Negotiation packet after the handshake is ignored" { // "A client MUST discard any Version Negotiation packet if it has // received and successfully processed any other packet." By then the // server has answered in this version, and anything claiming it cannot is // an off-path attacker who guessed the connection was underway -- which // is the whole of what makes an unauthenticated packet safe to have. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x0705); const client = &fixture.client; try testing.expect(client.isEstablished()); var out: [128]u8 = undefined; const wire = versionNegotiation( &out, &destination_connection_id, &client_connection_id, &.{0x00000002}, ); try client.receive(wire, 0, pair.now); try testing.expectEqual(@as(?quic.close.State, null), client.closeState()); } test "RFC 9000 17.2.1: a server does not act on a Version Negotiation packet" { // "It is only sent by servers", so one arriving at a server is not // something a conforming peer sends -- and a server that abandoned a // connection over it would be taking instructions from anybody able to // forge four octets. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x0706); const server = &fixture.server; var out: [128]u8 = undefined; const wire = versionNegotiation( &out, &client_connection_id, &destination_connection_id, &.{0x00000002}, ); try server.receive(wire, 0, pair.now); try testing.expectEqual(@as(?quic.close.State, null), server.closeState()); } test "RFC 9000 13.4.1: ECN markings are reported back to the sender" { // "Even if an endpoint does not set an ECT field in packets it sends, the // endpoint MUST provide feedback about ECN markings it receives, if these // are accessible. Failing to report the ECN counts will cause the sender // to disable the use of ECN for this connection." var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x0801); const client = &fixture.client; const server = &fixture.server; const id = try client.openBidirectional(); try client.write(id, "marked"); // The client's datagrams reach the server carrying ECT(0), and one of // them is marked CE by a notional router on the way. var buffer: [2048]u8 = undefined; var now = pair.now; var delivered: usize = 0; while (try client.send(&buffer, now)) |datagram| { now += std.time.ns_per_ms; const codepoint: quic.ack.Codepoint = if (delivered == 0) .ce else .ect0; try server.receiveEcn(datagram.bytes, datagram.path, now, codepoint); delivered += 1; } try testing.expect(delivered > 0); // The server's next ACK carries the counts rather than leaving them out. // The ACK is inside an encrypted packet, so this reads it the way the // client will: by handing it back and asking what the client saw. const answer = (try server.send(&buffer, now)).?; try client.receive(answer.bytes, answer.path, now); const found = client.peerEcnCounts(); try testing.expect(found != null); try testing.expectEqual(@as(u64, 1), found.?.ce); try testing.expect(found.?.ect0 >= 1); } test "RFC 9000 13.4.1: an endpoint with no access to the ECN field reports nothing" { // "If an endpoint does not implement ECN support or does not have access // to received ECN fields, it does not report ECN counts for packets it // receives." Absent counts and zero counts are different claims: §13.4.2.1 // fails validation when counts "are not present", which is how a sender // learns to stop marking rather than concluding the path stripped them. var fixture: Pair.Connected = undefined; const pair = try fixture.start(0x0802); const client = &fixture.client; const server = &fixture.server; const id = try client.openBidirectional(); try client.write(id, "unmarked"); var buffer: [2048]u8 = undefined; var now = pair.now; while (try client.send(&buffer, now)) |datagram| { now += std.time.ns_per_ms; // `receive` rather than `receiveEcn`: a caller that cannot read the // IP header. try server.receive(datagram.bytes, datagram.path, now); } const answer = (try server.send(&buffer, now)).?; try client.receive(answer.bytes, answer.path, now); try testing.expectEqual(@as(?quic.frame.Ack.Ecn, null), client.peerEcnCounts()); } // -- RFC 9287 and RFC 9368 -------------------------------------------------- /// `stream_limits`, advertising RFC 9287's grease_quic_bit. const grease_limits: quic.parameters.Parameters = limits: { var p = stream_limits; p.grease_quic_bit = true; break :limits p; }; const grease_client_parameters = encoded: { var buffer: [128]u8 = undefined; var p = grease_limits; p.initial_source_connection_id = &client_connection_id; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const grease_server_parameters = encoded: { var buffer: [128]u8 = undefined; var p = grease_limits; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; /// How many datagrams each end sent after the handshake, and how many of /// them had the QUIC Bit clear -- index 0 the client's, 1 the server's. const BitCount = struct { sent: [2]usize = .{ 0, 0 }, cleared: [2]usize = .{ 0, 0 } }; /// The client writes a little on one stream, `rounds` times, and everything /// either end has to say is delivered, with the first octet of every datagram /// looked at on the way. fn exchangeCounting(p: *Pair, rounds: usize) !BitCount { var count: BitCount = .{}; var buffer: [2048]u8 = undefined; const id = try p.client.openBidirectional(); for (0..rounds) |_| { try p.client.write(id, "grease"); // Past the peer's max_ack_delay, so that acknowledgements flow back. p.now += 30 * std.time.ns_per_ms; var steps: usize = 0; while (steps < 8) : (steps += 1) { var moved = false; if (try p.client.send(&buffer, p.now)) |d| { count.sent[0] += 1; if (d.bytes[0] & 0x40 == 0) count.cleared[0] += 1; p.now += std.time.ns_per_ms; try p.server.receive(d.bytes, d.path, p.now); moved = true; } if (try p.server.send(&buffer, p.now)) |d| { count.sent[1] += 1; if (d.bytes[0] & 0x40 == 0) count.cleared[1] += 1; p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); moved = true; } if (!moved) break; } } // Everything the client wrote arrived, whatever its packets looked like. const accepted = p.server.accept().?; try testing.expectEqual(rounds * "grease".len, p.server.readable(accepted).len); return count; } test "RFC 9287 3.1: both ends grease the QUIC Bit, and each reads the other's" { // Each end advertised grease_quic_bit, so each "SHOULD set the QUIC Bit to // an unpredictable value" -- and each has promised to accept a zero. Some // of each end's packets go out with it clear and some with it set, and // none of them is lost for it. var fixture: Pair.Connected = undefined; const p = try fixture.startWith(0x9287, grease_limits, &grease_client_parameters, &grease_server_parameters); const count = try exchangeCounting(p, 40); for (0..2) |side| { try testing.expect(count.sent[side] > 8); try testing.expect(count.cleared[side] > 0); try testing.expect(count.cleared[side] < count.sent[side]); } // And each end counted, after authentication, what the other cleared. try testing.expect(p.server.greasedPackets() >= count.cleared[0]); try testing.expect(p.client.greasedPackets() >= count.cleared[1]); } test "RFC 9287 3.1: an end whose peer did not offer it never clears the QUIC Bit" { // "An endpoint MUST NOT set the QUIC Bit to 0 without knowing whether the // peer supports the extension." The same exchange as above between two // ends that said nothing about it. var fixture: Pair.Connected = undefined; const p = try fixture.start(0x9287); const count = try exchangeCounting(p, 40); try testing.expect(count.sent[0] > 8 and count.sent[1] > 0); try testing.expectEqual(BitCount{ .sent = count.sent }, count); try testing.expectEqual(0, p.server.greasedPackets()); try testing.expectEqual(0, p.client.greasedPackets()); } /// Encoded client parameters naming a Chosen Version the packets are not in. const other_version_client_parameters = encoded: { var buffer: [64]u8 = undefined; var p = stream_limits; p.initial_source_connection_id = &client_connection_id; p.version_information = .{ .chosen = 0x6b3343cf, .available = .{ 0x6b3343cf, 0, 0, 0, 0, 0, 0, 0 }, .available_len = 1 }; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const other_version_server_parameters = encoded: { var buffer: [64]u8 = undefined; var p = stream_limits; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; p.version_information = .{ .chosen = 0x6b3343cf, .available = .{ 0x6b3343cf, 0, 0, 0, 0, 0, 0, 0 }, .available_len = 1 }; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; const v1_client_parameters = encoded: { var buffer: [64]u8 = undefined; var p = stream_limits; p.initial_source_connection_id = &client_connection_id; p.version_information = .v1; const written = quic.parameters.write(&p, &buffer, .client) catch unreachable; break :encoded buffer[0..written.len].*; }; const v1_server_parameters = encoded: { var buffer: [64]u8 = undefined; var p = stream_limits; p.initial_source_connection_id = &server_connection_id; p.original_destination_connection_id = &destination_connection_id; p.version_information = .v1; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; }; /// Moves datagrams until one end refuses one, and returns what it refused /// it with and which end it was. fn exchangeUntilRefused(p: *Pair) !struct { err: anyerror, by_server: bool } { var buffer: [2048]u8 = undefined; var steps: usize = 0; while (steps < 16) : (steps += 1) { if (try p.client.send(&buffer, p.now)) |d| { p.now += std.time.ns_per_ms; p.server.receive(d.bytes, d.path, p.now) catch |err| return .{ .err = err, .by_server = true }; } if (try p.server.send(&buffer, p.now)) |d| { p.now += std.time.ns_per_ms; p.client.receive(d.bytes, d.path, p.now) catch |err| return .{ .err = err, .by_server = false }; } } return error.TestExpectedRefusal; } test "RFC 9368 4: both ends say version 1, and the handshake completes" { var fixture: Pair.Connected = undefined; const p = try fixture.startWith(0x9368, stream_limits, &v1_client_parameters, &v1_server_parameters); try testing.expectEqual(@as(u32, 1), p.client.peer.?.version_information.?.chosen); try testing.expectEqual(@as(u32, 1), p.server.peer.?.version_information.?.chosen); } /// A pair that has not finished a handshake, for the tests where it must not. fn unshakenPair( rng: std.Random, client_tls: *quic.tls_handshake.Client, server_tls: *quic.tls_handshake.Server, client: *quic.Connection, server: *quic.Connection, client_memory: quic.Connection.Memory, server_memory: quic.Connection.Memory, client_encoded: []const u8, server_encoded: []const u8, client_local: quic.parameters.Parameters, server_local: quic.parameters.Parameters, ) !Pair { client_tls.* = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = client_encoded, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); server_tls.* = .init(.{ .auth = null, .transport_parameters = server_encoded, .alpn_protocols = &.{"doq"}, .rng = rng, }); client.init(.{ .role = .client, .memory = client_memory, .handshake = client_tls.handshake(), .local_id = &client_connection_id, .destination_id = &destination_connection_id, .local = client_local, .rng = rng, }); server.init(.{ .role = .server, .memory = server_memory, .handshake = server_tls.handshake(), .local_id = &server_connection_id, .local = server_local, .rng = rng, }); return .{ .client = client, .server = server }; } test "RFC 9368 4: a server refuses a client whose Chosen Version is not the one in use" { // "The server MUST validate that the client's Chosen Version matches the // version in use for the connection. If the two differ, the server MUST // close the connection with a version negotiation error." The packets // are version 1; the client's Version Information says otherwise. var rng_impl = std.Random.DefaultPrng.init(0x9369); var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client: quic.Connection = undefined; var server: quic.Connection = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var server_memory: quic.Connection.Storage(.{}) = .{}; var p = try unshakenPair(rng_impl.random(), &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &other_version_client_parameters, &v1_server_parameters, stream_limits, stream_limits); const refused = try exchangeUntilRefused(&p); try testing.expect(refused.by_server); try testing.expectEqual(error.VersionNegotiationError, refused.err); } test "RFC 9368 4: a client refuses a server that chose a version it did not offer" { // "If a client receives Version Information where the server's Chosen // Version was not sent by the client as part of its Available Versions, // the client MUST close the connection with a version negotiation error." var rng_impl = std.Random.DefaultPrng.init(0x936a); var client_tls: quic.tls_handshake.Client = undefined; var server_tls: quic.tls_handshake.Server = undefined; var client: quic.Connection = undefined; var server: quic.Connection = undefined; var client_memory: quic.Connection.Storage(.{}) = .{}; var server_memory: quic.Connection.Storage(.{}) = .{}; var p = try unshakenPair(rng_impl.random(), &client_tls, &server_tls, &client, &server, client_memory.memory(), server_memory.memory(), &v1_client_parameters, &other_version_server_parameters, stream_limits, stream_limits); const refused = try exchangeUntilRefused(&p); try testing.expect(!refused.by_server); try testing.expectEqual(error.VersionNegotiationError, refused.err); } // -- draft-ietf-quic-address-discovery-01 ----------------------------------- /// Where each end's datagrams appear to come from, as the other end's caller /// would say. Documentation ranges, and different ones, so that a report of /// the wrong end's address cannot pass for the right one. const client_address: quic.frame.Address = .{ .ip = .{ .v4 = .{ 198, 51, 100, 7 } }, .port = 40001 }; const server_address: quic.frame.Address = .{ .ip = .{ .v6 = .{ 0x20, 0x01, 0x0d, 0xb8 } ++ @as([12]u8, @splat(0)) }, .port = 853 }; fn withRole(role: ?quic.parameters.AddressDiscovery) quic.parameters.Parameters { var p = stream_limits; p.address_discovery = role; return p; } fn encodedClient(comptime role: ?quic.parameters.AddressDiscovery) [64]u8 { var buffer: [64]u8 = @splat(0); var p = withRole(role); p.initial_source_connection_id = &client_connection_id; _ = quic.parameters.write(&p, &buffer, .client) catch unreachable; return buffer; } /// A fixture pair in the given roles, each end told the other's address, /// shaken hands and settled. `server_says` is the role the server /// *advertises*, which the refusal test sets apart from the one it acts on. const Observing = struct { client_tls: quic.tls_handshake.Client = undefined, server_tls: quic.tls_handshake.Server = undefined, client: quic.Connection = undefined, server: quic.Connection = undefined, client_memory: quic.Connection.Storage(.{}) = .{}, server_memory: quic.Connection.Storage(.{}) = .{}, rng_impl: std.Random.DefaultPrng = undefined, client_params: [128]u8 = undefined, server_params: [128]u8 = undefined, pair: Pair = undefined, fn start( o: *Observing, seed: u64, client_role: ?quic.parameters.AddressDiscovery, server_role: ?quic.parameters.AddressDiscovery, server_says: ?quic.parameters.AddressDiscovery, ) !*Pair { o.rng_impl = .init(seed); var c = withRole(client_role); c.initial_source_connection_id = &client_connection_id; const client_encoded = try quic.parameters.write(&c, &o.client_params, .client); var sv = withRole(server_says); sv.initial_source_connection_id = &server_connection_id; sv.original_destination_connection_id = &destination_connection_id; const server_encoded = try quic.parameters.write(&sv, &o.server_params, .server); o.pair = try unshakenPair( o.rng_impl.random(), &o.client_tls, &o.server_tls, &o.client, &o.server, o.client_memory.memory(), o.server_memory.memory(), client_encoded, server_encoded, withRole(client_role), withRole(server_role), ); try o.client.setPeerAddress(0, server_address); try o.server.setPeerAddress(0, client_address); return &o.pair; } }; test "draft-ietf-quic-address-discovery-01 5: each end reports the other's address" { // Both ends in role 2, so each owes the other a report on the path the // handshake used, "as early as possible". What each end reads back is the // address the *other* end's caller saw it at. var o: Observing = .{}; const p = try o.start(0xad01, .both, .both, .both); try p.handshake(); try p.settle(); try testing.expect(p.client.observedAddress().?.eql(client_address)); try testing.expect(p.server.observedAddress().?.eql(server_address)); } test "draft-ietf-quic-address-discovery-01 3: reports flow only to an end that asked" { // A client that only receives and a server that only provides: the client // learns its address and the server learns nothing, because it asked for // nothing -- and neither end objects. var o: Observing = .{}; const p = try o.start(0xad02, .receive, .provide, .provide); try p.handshake(); try p.settle(); try testing.expect(p.client.observedAddress().?.eql(client_address)); try testing.expectEqual(@as(?quic.frame.Address, null), p.server.observedAddress()); // And a client that offers to provide but does not want reports gets // none, from a server that would happily send them. var o2: Observing = .{}; const p2 = try o2.start(0xad03, .provide, .both, .both); try p2.handshake(); try p2.settle(); try testing.expectEqual(@as(?quic.frame.Address, null), p2.client.observedAddress()); try testing.expect(p2.server.observedAddress().?.eql(server_address)); } test "draft-ietf-quic-address-discovery-01 4.1: a report nobody agreed to is a protocol violation" { // The server advertises that it only receives, and sends reports anyway. // "An endpoint MUST NOT send an OBSERVED_ADDRESS frame to a node that did // not request the receipt" -- and the client, which asked for reports // from a server that said it would not give them, is receiving one it // was never offered. var o: Observing = .{}; const p = try o.start(0xad04, .both, .both, .receive); const refused = try exchangeUntilRefused(p); try testing.expect(!refused.by_server); try testing.expectEqual(error.ProtocolViolation, refused.err); } test "draft-ietf-quic-address-discovery-01 5: a changed address is reported again" { // §5: "the sender SHOULD send an OBSERVED_ADDRESS frame when it detects a // change in the remote address on an existing path" -- a NAT rebinding, // as the caller sees it. var o: Observing = .{}; const p = try o.start(0xad05, .both, .both, .both); try p.handshake(); try p.settle(); const rebound: quic.frame.Address = .{ .ip = .{ .v4 = .{ 198, 51, 100, 9 } }, .port = 50000 }; try p.server.setPeerAddress(0, rebound); try p.settle(); try testing.expect(p.client.observedAddress().?.eql(rebound)); } test "draft-ietf-quic-address-discovery-01 4.1: a reordered report does not undo a newer one" { // Two reports, delivered newest first. "A peer SHOULD ignore an incoming // OBSERVED_ADDRESS frame if it previously received another // OBSERVED_ADDRESS frame for the same path with a Sequence Number equal to // or higher." var o: Observing = .{}; const p = try o.start(0xad06, .both, .both, .both); try p.handshake(); try p.settle(); const older: quic.frame.Address = .{ .ip = .{ .v4 = .{ 198, 51, 100, 10 } }, .port = 1 }; const newer: quic.frame.Address = .{ .ip = .{ .v4 = .{ 198, 51, 100, 11 } }, .port = 2 }; var first_buf: [2048]u8 = undefined; var second_buf: [2048]u8 = undefined; try p.server.setPeerAddress(0, older); const first = (try p.server.send(&first_buf, p.now)).?; try p.server.setPeerAddress(0, newer); const second = (try p.server.send(&second_buf, p.now)).?; p.now += std.time.ns_per_ms; try p.client.receive(second.bytes, second.path, p.now); try p.client.receive(first.bytes, first.path, p.now); try testing.expect(p.client.observedAddress().?.eql(newer)); } test "draft-ietf-quic-address-discovery-01 4.1: a lost report is sent again" { // "OBSERVED_ADDRESS frames are ack-eliciting, and SHOULD be retransmitted // if lost." The datagram carrying it is dropped, nothing later can // acknowledge it, and the probe timeout is what finds out. var o: Observing = .{}; const p = try o.start(0xad07, .both, .both, .both); try p.handshake(); try p.settle(); const moved: quic.frame.Address = .{ .ip = .{ .v4 = .{ 198, 51, 100, 12 } }, .port = 3 }; var buffer: [2048]u8 = undefined; try p.server.setPeerAddress(0, moved); _ = (try p.server.send(&buffer, p.now)).?; // dropped try testing.expect(!p.client.observedAddress().?.eql(moved)); var rounds: usize = 0; while (!p.client.observedAddress().?.eql(moved) and rounds < 8) : (rounds += 1) { const at = p.server.timeout() orelse break; p.now = @max(p.now, at); p.client.onTimeout(p.now); p.server.onTimeout(p.now); try p.settle(); } try testing.expect(p.client.observedAddress().?.eql(moved)); } // -- draft-ietf-quic-multipath-21, with one path ---------------------------- /// Seals `f` into a 1-RTT packet from `from`, under its own keys and to its /// own peer's connection ID, and hands it to `to`. How a test makes one end /// say something its sender would never choose to. fn inject(p: *Pair, from: *quic.Connection, to: *quic.Connection, f: quic.frame.Frame) !void { var buffer: [256]u8 = undefined; const space = &from.spaces[2]; var b = try packet.Builder.initShort(&buffer, from.peerId(), space.next_number, 4, from.key_phase); try b.add(f); // Enough for §5.4.2's header protection sample behind the number. try b.padTo(64); const wire = try b.finish(&space.write.?); space.next_number += 1; p.now += std.time.ns_per_ms; try to.receive(wire, 0, p.now); } /// `stream_limits`, advertising multipath with only path 0 allowed for now. const multipath_limits: quic.parameters.Parameters = limits: { var p = stream_limits; p.initial_max_path_id = 0; break :limits p; }; const Multipath = struct { o: Observing = .{}, /// A pair where the client's multipath parameter is `client` and the /// server's is `server`, handshake done. fn start(m: *Multipath, seed: u64, client: ?u64, server: ?u64) !*Pair { m.o.rng_impl = .init(seed); var cp = stream_limits; cp.initial_max_path_id = client; var c = cp; c.initial_source_connection_id = &client_connection_id; const client_encoded = try quic.parameters.write(&c, &m.o.client_params, .client); var sp = stream_limits; sp.initial_max_path_id = server; var sv = sp; sv.initial_source_connection_id = &server_connection_id; sv.original_destination_connection_id = &destination_connection_id; const server_encoded = try quic.parameters.write(&sv, &m.o.server_params, .server); m.o.pair = try unshakenPair( m.o.rng_impl.random(), &m.o.client_tls, &m.o.server_tls, &m.o.client, &m.o.server, m.o.client_memory.memory(), m.o.server_memory.memory(), client_encoded, server_encoded, cp, sp, ); try m.o.pair.handshake(); try m.o.pair.settle(); return &m.o.pair; } }; test "draft-ietf-quic-multipath-21 2: negotiated with one path, a connection carries on as before" { // Both ends advertise initial_max_path_id = 0: "the peer aims to enable // the multipath extension without allowing extra paths immediately". // Path 0's nonce is RFC 9001's, and ACK still acknowledges path 0, so // nothing about the connection's traffic has to change. var m: Multipath = .{}; const p = try m.start(0x3e00, 0, 0); try testing.expect(p.client.multipathNegotiated() and p.server.multipathNegotiated()); const count = try exchangeCounting(p, 20); try testing.expect(count.sent[0] > 8); } test "draft-ietf-quic-multipath-21 2: advertised by one end only, it is not in use" { // "If either of the endpoints does not advertise the initial_max_path_id // transport parameter, then both endpoints MUST NOT use any frame or // mechanism defined in this document" -- so a PATH_ACK from the one that // did is a frame the other never agreed to. var m: Multipath = .{}; const p = try m.start(0x3e01, 0, null); try testing.expect(!p.client.multipathNegotiated() and !p.server.multipathNegotiated()); try testing.expectError(error.ProtocolViolation, inject(p, p.client, p.server, .{ .max_path_id = 1 })); } test "draft-ietf-quic-multipath-21 4: path frames for path 0 are their RFC 9000 counterparts" { var m: Multipath = .{}; const p = try m.start(0x3e02, 0, 0); // PATH_NEW_CONNECTION_ID for path 0 is a NEW_CONNECTION_ID, under the // same rules: this one retires everything before it, which is what keeps // the client inside the two active identifiers it allows, and the client // holds it afterwards. const token: [16]u8 = @splat(0x44); try inject(p, p.server, p.client, .{ .path_new_connection_id = .{ .path = 0, .id = .{ .sequence = 7, .retire_prior_to = 7, .id = &.{ 0xd0, 0x07 }, .token = &token, } } }); try testing.expect(holds(&p.client.received, 7)); // MAX_PATH_ID may only raise the limit it was given. try inject(p, p.server, p.client, .{ .max_path_id = 3 }); try testing.expectEqual(@as(u64, 3), p.client.peer_max_path_id); try inject(p, p.server, p.client, .{ .max_path_id = 1 }); // reordered, ignored try testing.expectEqual(@as(u64, 3), p.client.peer_max_path_id); } fn holds(r: *const quic.connection_id.Received, sequence: u64) bool { for (r.entries) |e| { if (e.in_use and e.sequence == sequence) return true; } return false; } test "draft-ietf-quic-multipath-21 4: a path past the limit is a protocol violation" { // This end allowed path 0 and nothing more, so a frame naming path 1 is // "a path ID that is greater than the announced Maximum Paths value". var m: Multipath = .{}; const p = try m.start(0x3e03, 0, 0); try testing.expectError(error.ProtocolViolation, inject(p, p.server, p.client, .{ .path_status = .{ .path = 1, .sequence = 0, .status = .backup }, })); } test "draft-ietf-quic-multipath-21 3.4: abandoning the only path closes the connection" { // "If a PATH_ABANDON frame is received for the only open path of a QUIC // connection, the receiving peer SHOULD send a CONNECTION_CLOSE frame and // enter the closing state." var m: Multipath = .{}; const p = try m.start(0x3e04, 0, 0); try inject(p, p.server, p.client, .{ .path_abandon = .{ .path = 0, .error_code = 0 } }); try testing.expectEqual(quic.close.State.closing, p.client.closeState().?); } test "draft-ietf-quic-multipath-21 4: an ACK for a path in PATH_ACK form is an ACK" { // The server acknowledges everything the client sent, as PATH_ACK for // path 0 instead of ACK -- which the client has to accept, since §2.3 // has endpoints that negotiated multipath "SHOULD use PATH_ACK frames // instead of ACK frames". Acknowledged, the client stops retransmitting. var m: Multipath = .{}; const p = try m.start(0x3e05, 0, 0); const id = try p.client.openBidirectional(); try p.client.write(id, "acknowledge me"); var buffer: [2048]u8 = undefined; const sent = (try p.client.send(&buffer, p.now)).?; p.now += std.time.ns_per_ms; try p.server.receive(sent.bytes, sent.path, p.now); const largest = p.client.spaces[2].next_number - 1; try inject(p, p.server, p.client, .{ .path_ack = .{ .path = 0, .ack = .{ .largest = largest, .delay = 0, .range_count = 0, .first_range = largest, .encoded_ranges = &.{}, .ecn = null, } } }); try testing.expectEqual(@as(?u64, largest), p.client.spaces[2].loss.largest_acked); } // -- draft-ietf-quic-multipath-21, with a second path ----------------------- /// A pair with room for two paths, both ends allowing path ID 1, handshake /// done and settled -- which is when each has issued the other an identifier /// for path 1. const TwoPaths = struct { client_tls: quic.tls_handshake.Client = undefined, server_tls: quic.tls_handshake.Server = undefined, client: quic.Connection = undefined, server: quic.Connection = undefined, client_memory: quic.Connection.Storage(.{ .paths = 2 }) = .{}, server_memory: quic.Connection.Storage(.{ .paths = 2 }) = .{}, rng_impl: std.Random.DefaultPrng = undefined, client_params: [128]u8 = undefined, server_params: [128]u8 = undefined, pair: Pair = undefined, /// The server's initial_max_path_id; the client's is always 1. server_max_path_id: u64 = 1, /// n0's NAT traversal parameter at each end, or null for none. client_nat: ?u8 = null, server_nat: ?u8 = null, fn start(t: *TwoPaths, seed: u64) !*Pair { const p = try t.shake(seed); try p.settle(); return p; } fn shake(t: *TwoPaths, seed: u64) !*Pair { const p = try t.build(seed); try p.handshake(); return p; } /// The pair, before anything has been exchanged. fn build(t: *TwoPaths, seed: u64) !*Pair { t.rng_impl = .init(seed); var local = stream_limits; local.initial_max_path_id = 1; local.n0_nat_traversal = t.client_nat; var c = local; c.initial_source_connection_id = &client_connection_id; const client_encoded = try quic.parameters.write(&c, &t.client_params, .client); var server_local = local; server_local.initial_max_path_id = t.server_max_path_id; server_local.n0_nat_traversal = t.server_nat; var sv = server_local; sv.initial_source_connection_id = &server_connection_id; sv.original_destination_connection_id = &destination_connection_id; const server_encoded = try quic.parameters.write(&sv, &t.server_params, .server); t.pair = try unshakenPair( t.rng_impl.random(), &t.client_tls, &t.server_tls, &t.client, &t.server, t.client_memory.memory(), t.server_memory.memory(), client_encoded, server_encoded, local, server_local, ); return &t.pair; } }; test "draft-ietf-quic-multipath-21 3.1: a client opens a second path and data goes over it" { var t: TwoPaths = .{}; const p = try t.start(0x3e10); try testing.expect(p.client.multipathNegotiated()); // Route 1 is the caller's name for a second 4-tuple -- a second // interface, say. The path ID is the protocol's, and the lowest one both // ends have issued an identifier for. const id = try p.client.openPath(1, p.now); try testing.expectEqual(@as(u32, 1), id); // The client's PATH_CHALLENGE goes out on route 1, on path 1's packet // number space and identifier. The server, which has never seen the // identifier used, takes it as the path opening, answers, and challenges // back; the client answers that. Both routes are now validated. try p.settle(); try testing.expect(p.client.paths.find(1).?.validated); try testing.expect(p.server.paths.find(1).?.validated); // Path 0 is still the path the connection is on: a new path ID is not a // migration (§3.1.2). try testing.expectEqual(@as(quic.path.Id, 0), p.client.paths.active); try testing.expectEqual(@as(quic.path.Id, 0), p.server.paths.active); // New data on path 1. It has to arrive, acknowledged as path 1's. try p.client.useSendPath(1); const stream_id = try p.client.openBidirectional(); try p.client.write(stream_id, "over the second path"); try p.client.finishStream(stream_id); var buffer: [2048]u8 = undefined; var on_route_1: usize = 0; var steps: usize = 0; while (steps < 32) : (steps += 1) { var moved = false; if (try p.client.send(&buffer, p.now)) |d| { if (d.path == 1) on_route_1 += 1; p.now += std.time.ns_per_ms; try p.server.receive(d.bytes, d.path, p.now); moved = true; } if (try p.server.send(&buffer, p.now)) |d| { p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); moved = true; } if (!moved) break; } try testing.expect(on_route_1 > 0); const accepted = p.server.accept().?; try testing.expectEqualStrings("over the second path", p.server.readable(accepted)); // Path 1 numbered its own packets from zero, and the server acknowledged // them in path 1's space: nothing of the client's is left in flight there. const path1 = &p.client.extra[0]; try testing.expect(path1.space.next_number > 0); try testing.expectEqual(@as(usize, 0), path1.space.loss.inFlight()); } /// Opens path 1 over route 1 and settles until both ends have validated it. fn openSecondPath(p: *Pair) !void { _ = try p.client.openPath(1, p.now); try p.settle(); try testing.expect(p.client.paths.find(1).?.validated and p.server.paths.find(1).?.validated); } test "draft-ietf-quic-multipath-21 3.4: abandoning a path, and the answer" { // "When an endpoint receives a PATH_ABANDON frame, it MUST send a // corresponding PATH_ABANDON frame, if it has not already done so." After // it neither end sends on the path, and the connection carries on over // path 0 -- abandoning a path is not abandoning the connection. var t: TwoPaths = .{}; const p = try t.start(0x3e11); try openSecondPath(p); try p.client.useSendPath(1); try p.client.abandonPath(1); try p.settle(); try testing.expect(p.client.extra[0].state == .abandoned and p.client.extra[0].sent_abandon); try testing.expect(p.server.extra[0].state == .abandoned and p.server.extra[0].sent_abandon); try testing.expectEqual(@as(?quic.close.State, null), p.client.closeState()); // And the client's new data goes on path 0 again. const before = p.client.extra[0].space.next_number; const stream_id = try p.client.openBidirectional(); try p.client.write(stream_id, "back on path zero"); try p.client.finishStream(stream_id); try p.settle(); try testing.expectEqual(before, p.client.extra[0].space.next_number); try testing.expectEqualStrings("back on path zero", p.server.readable(p.server.accept().?)); } test "draft-ietf-quic-multipath-21 5.7: a packet lost on path 1 is found by path 1's timer" { // "An implementation should follow the mechanism specified in // [QUIC-RECOVERY] for detecting packet loss on each individual path" -- // so the data is retransmitted when path 1's probe timeout fires, which // is computed from path 1's own RTT. var t: TwoPaths = .{}; const p = try t.start(0x3e12); try openSecondPath(p); try p.client.useSendPath(1); const stream_id = try p.client.openBidirectional(); try p.client.write(stream_id, "lost once on path one"); try p.client.finishStream(stream_id); var buffer: [2048]u8 = undefined; const dropped = (try p.client.send(&buffer, p.now)).?; try testing.expectEqual(@as(quic.path.Id, 1), dropped.path); try testing.expect(p.client.extra[0].space.loss.inFlight() > 0); var accepted: ?quic.stream.Id = null; var rounds: usize = 0; while (accepted == null and rounds < 8) : (rounds += 1) { const at = p.client.timeout() orelse break; p.now = @max(p.now, at); p.client.onTimeout(p.now); p.server.onTimeout(p.now); try p.settle(); accepted = p.server.accept(); } try testing.expectEqualStrings("lost once on path one", p.server.readable(accepted.?)); } test "draft-ietf-quic-multipath-21 4.4: a lost path identifier is sent again, the same one" { // The server issues its identifier for path 1 in its first 1-RTT packet, // which travels with its handshake flight -- and that datagram is // dropped. The probe timeout brings the flight back, and with it the // *same* identifier under the same sequence number, not a second one: a // peer that already held the first would otherwise hold two it had never // been told were distinct. var t: TwoPaths = .{}; const p = try t.build(0x3e13); var buffer: [2048]u8 = undefined; var dropped = false; var rounds: usize = 0; while (rounds < 64 and !(p.client.extra[0].received.current() != null and p.client.isEstablished())) : (rounds += 1) { var moved = false; if (try p.client.send(&buffer, p.now)) |d| { p.now += std.time.ns_per_ms; try p.server.receive(d.bytes, d.path, p.now); moved = true; } if (try p.server.send(&buffer, p.now)) |d| { // The datagram after which the server has issued its path-1 // identifier is the one that carried it. if (!dropped and p.server.extra[0].issued.next_sequence == 1) { dropped = true; } else { p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); } moved = true; } if (!moved) { const at = @min(p.client.timeout() orelse std.math.maxInt(u64), p.server.timeout() orelse std.math.maxInt(u64)); if (at == std.math.maxInt(u64)) break; p.now = @max(p.now, at); p.client.onTimeout(p.now); p.server.onTimeout(p.now); } } try testing.expect(dropped); try testing.expect(p.client.isEstablished()); try testing.expect(holds(&p.client.extra[0].received, 0)); try testing.expectEqual(@as(u64, 1), p.server.extra[0].issued.next_sequence); } test "draft-ietf-quic-multipath-21 3.4: path 0 abandoned while path 1 carries on" { // No path is above the others. With path 1 open, abandoning path 0 is // answered in kind and the connection goes on over path 1 -- the one // case in which "the only open path" is not path 0. var t: TwoPaths = .{}; const p = try t.start(0x3e14); try openSecondPath(p); try p.client.abandonPath(0); try p.settle(); try testing.expect(p.client.path0_sent_abandon and p.server.path0_abandoned and p.server.path0_sent_abandon); try testing.expectEqual(@as(?quic.close.State, null), p.client.closeState()); try testing.expectEqual(@as(?quic.close.State, null), p.server.closeState()); const stream_id = try p.client.openBidirectional(); try p.client.write(stream_id, "path one only now"); try p.client.finishStream(stream_id); const zero_before = p.client.spaces[2].next_number; try p.settle(); try testing.expectEqualStrings("path one only now", p.server.readable(p.server.accept().?)); // Nothing more went out on path 0. try testing.expectEqual(zero_before, p.client.spaces[2].next_number); } test "draft-ietf-quic-multipath-21 4.7: PATH_CIDS_BLOCKED may not name an identifier not yet due" { var t: TwoPaths = .{}; const p = try t.start(0x3e15); // The server has issued sequence 0 for path 1 and nothing past it, so a // client saying it is waiting for sequence 5 is talking about identifiers // that could not exist yet. try testing.expectError(error.ProtocolViolation, inject(p, p.client, p.server, .{ .path_cids_blocked = .{ .path = 1, .next_sequence = 5 }, })); } test "draft-ietf-quic-multipath-21: a stateless reset for path 1's identifier ends the connection" { // The token that came with the server's path-1 identifier is one the // client has used, so a reset carrying it is the server saying it has // lost the connection -- §10.3.1's check has to include it. var t: TwoPaths = .{}; const p = try t.start(0x3e16); try openSecondPath(p); var token: [16]u8 = undefined; for (p.client.extra[0].received.entries) |e| { if (e.in_use) token = e.token.?; } var buffer: [64]u8 = undefined; var rng = std.Random.DefaultPrng.init(1); const reset = try quic.stateless_reset.write(&buffer, rng.random(), token, 1200); try p.client.receive(@constCast(reset), 1, p.now + 1); try testing.expectEqual(quic.close.State.draining, p.client.closeState().?); } /// Moves both ends of `p` to when their abandoned paths' state is let go of, /// and lets it go. fn releaseAbandoned(p: *Pair) void { var latest: u64 = p.now; for ([_]*quic.Connection{ p.client, p.server }) |c| { for (c.extra) |e| if (e.discard_at) |at| { latest = @max(latest, at); }; } p.now = latest; p.client.onTimeout(p.now); p.server.onTimeout(p.now); } /// Sends one stream's worth of `text` from the client and returns how many /// packets went out on multipath path `id` while it did. fn sendCounting(p: *Pair, text: []const u8, id: u32) !u64 { const before = if (id == 0) p.client.spaces[2].next_number else p.client.extra[0].space.next_number; const stream_id = try p.client.openBidirectional(); try p.client.write(stream_id, text); try p.client.finishStream(stream_id); try p.settle(); try testing.expectEqualStrings(text, p.server.readable(p.server.accept().?)); const after = if (id == 0) p.client.spaces[2].next_number else p.client.extra[0].space.next_number; return after - before; } test "draft-ietf-quic-multipath-21 3.4: data in flight on an abandoned path goes again on another" { // §3.4.3: "the packets sent over the path and not yet acknowledged MUST // be considered lost" -- here at once, since nothing more is sent on the // path to find out. The datagram carrying the stream is dropped, path 1 // is abandoned before any timer fires, and the data arrives over path 0. var t: TwoPaths = .{}; const p = try t.start(0x3e17); try openSecondPath(p); try p.client.useSendPath(1); const stream_id = try p.client.openBidirectional(); try p.client.write(stream_id, "abandoned in flight"); try p.client.finishStream(stream_id); var buffer: [2048]u8 = undefined; const dropped = (try p.client.send(&buffer, p.now)).?; try testing.expectEqual(@as(quic.path.Id, 1), dropped.path); try p.client.abandonPath(1); try testing.expectEqual(@as(usize, 0), p.client.extra[0].space.loss.inFlight()); try p.settle(); try testing.expectEqualStrings("abandoned in flight", p.server.readable(p.server.accept().?)); } test "draft-ietf-quic-multipath-21 3.4, 4.6: a path let go of makes room for a new path ID" { // Path 1 is abandoned by both ends, its state kept for 3 PTO and then let // go of. "The path ID MUST NOT be reused", so the slot comes back as path // 2, each end raises its limit with MAX_PATH_ID, identifiers for path 2 // follow, and the client opens it -- with path 2 in every nonce. var t: TwoPaths = .{}; const p = try t.start(0x3e18); try openSecondPath(p); try p.client.abandonPath(1); try p.settle(); try testing.expect(p.client.extra[0].discard_at != null and p.server.extra[0].discard_at != null); // Too soon: not yet. p.client.onTimeout(p.now); try testing.expectEqual(@as(u32, 1), p.client.extra[0].id); releaseAbandoned(p); try testing.expectEqual(@as(u32, 2), p.client.extra[0].id); try testing.expectEqual(@as(u32, 2), p.server.extra[0].id); try p.settle(); try testing.expectEqual(@as(u64, 2), p.client.peer_max_path_id); try testing.expectEqual(@as(u64, 2), p.server.peer_max_path_id); try testing.expect(p.client.extra[0].received.current() != null); try testing.expectEqual(@as(u32, 2), try p.client.openPath(2, p.now)); try p.settle(); try testing.expect(p.client.paths.find(2).?.validated and p.server.paths.find(2).?.validated); try p.client.useSendPath(2); try testing.expect(try sendCounting(p, "over path two", 2) > 0); } test "draft-ietf-quic-multipath-21 3.3: data leaves a path the peer marks backup, and comes back" { // PATH_STATUS_BACKUP asks "that no traffic should be sent on that path if // another path is available and usable". The client chose path 1; while // the server says backup, path 0 carries the data instead. var t: TwoPaths = .{}; const p = try t.start(0x3e19); try openSecondPath(p); try p.client.useSendPath(1); try p.server.setPathStatus(1, .backup); try p.settle(); try testing.expectEqual(quic.frame.PathStatus.Status.backup, p.client.peerPathStatus(1).?); try testing.expectEqual(@as(u64, 0), try sendCounting(p, "not on the backup path", 1)); try p.server.setPathStatus(1, .available); try p.settle(); try testing.expectEqual(quic.frame.PathStatus.Status.available, p.client.peerPathStatus(1).?); try testing.expect(try sendCounting(p, "on path one again", 1) > 0); } test "draft-ietf-quic-multipath-21 3.3: every path marked backup is no guidance at all" { var t: TwoPaths = .{}; const p = try t.start(0x3e1a); try openSecondPath(p); try p.client.useSendPath(1); try p.server.setPathStatus(0, .backup); try p.server.setPathStatus(1, .backup); try p.settle(); try testing.expect(try sendCounting(p, "the choice stands", 1) > 0); } test "draft-ietf-quic-multipath-21 4.3: an older path status does not undo a newer one" { var t: TwoPaths = .{}; const p = try t.start(0x3e1b); try inject(p, p.server, p.client, .{ .path_status = .{ .path = 0, .sequence = 5, .status = .backup } }); try inject(p, p.server, p.client, .{ .path_status = .{ .path = 0, .sequence = 3, .status = .available } }); try testing.expectEqual(quic.frame.PathStatus.Status.backup, p.client.peerPathStatus(0).?); try inject(p, p.server, p.client, .{ .path_status = .{ .path = 0, .sequence = 6, .status = .available } }); try testing.expectEqual(quic.frame.PathStatus.Status.available, p.client.peerPathStatus(0).?); } test "draft-ietf-quic-multipath-21 4.3: a lost path status is sent again" { var t: TwoPaths = .{}; const p = try t.start(0x3e1c); try p.server.setPathStatus(0, .backup); var buffer: [2048]u8 = undefined; _ = (try p.server.send(&buffer, p.now)).?; // dropped try testing.expectEqual(@as(?quic.frame.PathStatus.Status, null), p.client.peerPathStatus(0)); var rounds: usize = 0; while (p.client.peerPathStatus(0) == null and rounds < 8) : (rounds += 1) { const at = p.server.timeout() orelse break; p.now = @max(p.now, at); p.server.onTimeout(p.now); try p.settle(); } try testing.expectEqual(quic.frame.PathStatus.Status.backup, p.client.peerPathStatus(0).?); } test "draft-ietf-quic-multipath-21 4.7: PATHS_BLOCKED when the peer's limit is in the way" { // The client allows path 1 and has room for it; the server allows none // past path 0. Opening one fails, and the client says why, once. var t: TwoPaths = .{ .server_max_path_id = 0 }; const p = try t.start(0x3e1d); try testing.expectError(error.NoPathAvailable, p.client.openPath(1, p.now)); try p.settle(); try testing.expectEqual(@as(?u64, 0), p.client.paths_blocked_sent); try testing.expectError(error.NoPathAvailable, p.client.openPath(1, p.now)); try testing.expectEqual(@as(?u64, null), p.client.paths_blocked_owed); try testing.expectEqual(@as(?quic.close.State, null), p.server.closeState()); } test "draft-ietf-quic-multipath-21 4.7: PATH_CIDS_BLOCKED when the peer has issued no identifier" { // Path 1 is allowed at both ends, but the client holds nothing from the // server to address it with -- as if the offer were still in flight. var t: TwoPaths = .{}; const p = try t.start(0x3e1e); p.client.extra[0].received = .{}; try testing.expectError(error.NoPathAvailable, p.client.openPath(1, p.now)); try p.settle(); // Next Sequence Number 0: the client has heard of no identifier for path // 1, and the server, which has issued sequence 0, finds that in order. try testing.expectEqual(@as(?u64, 0), p.client.extra[0].cids_blocked_sent); try testing.expectEqual(@as(?quic.close.State, null), p.server.closeState()); } /// Runs `p` until both ends' PMTU searches on paths 0 and 1 are finished, /// dropping every datagram larger than its route carries. fn searchBothPaths(p: *Pair, carries: [2]usize) !void { var buffer: [2048]u8 = undefined; var steps: usize = 0; const ends = [_]*quic.Connection{ p.client, p.server }; while (steps < 400) : (steps += 1) { var moved = false; for (ends, 0..) |from, i| { const to = ends[1 - i]; if (try from.send(&buffer, p.now)) |d| { p.now += std.time.ns_per_ms; if (d.bytes.len <= carries[d.path]) try to.receive(d.bytes, d.path, p.now); moved = true; } } var done = true; for (ends) |c| { if (c.pmtu.state != .complete or c.extra[0].pmtu.state != .complete) done = false; } if (done) return; if (!moved) { const at = @min(p.client.timeout() orelse std.math.maxInt(u64), p.server.timeout() orelse std.math.maxInt(u64)); if (at == std.math.maxInt(u64)) return; p.now = @max(p.now, at); p.client.onTimeout(p.now); p.server.onTimeout(p.now); } } } test "draft-ietf-quic-multipath-21 5.8: each path finds its own PMTU, and is sized by it" { // Route 0 carries anything the search will try; route 1 no more than // 1300 octets. Sized by path 0's answer, path 1 would lose every full // packet -- so each path searches for itself, and data on path 1 goes in // datagrams path 1 carries. var t: TwoPaths = .{}; const p = try t.start(0x3e1f); const narrow = 1300; // Opened under the same conditions, so that path 1's search -- which // begins once the path is validated -- meets route 1's limit. _ = try p.client.openPath(1, p.now); try searchBothPaths(p, .{ quic.mtu.ceiling, narrow }); try testing.expect(p.client.paths.find(1).?.validated and p.server.paths.find(1).?.validated); for ([_]*quic.Connection{ p.client, p.server }) |c| { try testing.expectEqual(quic.mtu.State.complete, c.pmtu.state); try testing.expectEqual(quic.mtu.State.complete, c.extra[0].pmtu.state); try testing.expect(c.pmtu.current > narrow); try testing.expect(c.extra[0].pmtu.current <= narrow); try testing.expect(c.extra[0].pmtu.current > narrow - 16); } try p.client.useSendPath(1); const stream_id = try p.client.openBidirectional(); const text: [2000]u8 = @splat('m'); try p.client.write(stream_id, &text); try p.client.finishStream(stream_id); var buffer: [2048]u8 = undefined; var on_path_1: usize = 0; var steps: usize = 0; while (steps < 64) : (steps += 1) { var moved = false; if (try p.client.send(&buffer, p.now)) |d| { if (d.path == 1) { try testing.expect(d.bytes.len <= narrow); on_path_1 += 1; } p.now += std.time.ns_per_ms; try p.server.receive(d.bytes, d.path, p.now); moved = true; } if (try p.server.send(&buffer, p.now)) |d| { p.now += std.time.ns_per_ms; try p.client.receive(d.bytes, d.path, p.now); moved = true; } if (!moved) break; } // Two full-sized packets' worth, each sized for route 1 rather than // for path 0's 1445. try testing.expect(on_path_1 >= 2); try testing.expectEqualSlices(u8, &text, p.server.readable(p.server.accept().?)); } test "draft-ietf-quic-multipath-21 5.5: the lowest-RTT scheduler takes the faster path" { // Nothing chosen with useSendPath: the scheduler decides, and path 0 is // made the slow one. var t: TwoPaths = .{}; const p = try t.start(0x3e20); try openSecondPath(p); p.client.setScheduler(.lowest_rtt); p.client.rtt.smoothed = 200 * std.time.ns_per_ms; try testing.expect(try sendCounting(p, "the quick way", 1) > 0); // And the other way round. var u: TwoPaths = .{}; const q = try u.start(0x3e21); try openSecondPath(q); q.client.setScheduler(.lowest_rtt); q.client.extra[0].rtt.smoothed = 200 * std.time.ns_per_ms; try testing.expectEqual(@as(u64, 0), try sendCounting(q, "path zero is quicker", 1)); } test "draft-ietf-quic-multipath-21 5.5: a full window sends the overflow to the next path" { // Path 1 is the faster, but its congestion window holds one packet. The // first packet of the stream goes on path 1 and fills it; the rest goes // on path 0, which has room -- "among those paths with an open congestion // window" -- and the stream arrives whole. var t: TwoPaths = .{}; const p = try t.start(0x3e22); try openSecondPath(p); p.client.setScheduler(.lowest_rtt); p.client.rtt.smoothed = 200 * std.time.ns_per_ms; p.client.extra[0].congestion.window = 1300; const stream_id = try p.client.openBidirectional(); const text: [2000]u8 = @splat('o'); try p.client.write(stream_id, &text); try p.client.finishStream(stream_id); var buffer: [2048]u8 = undefined; var held: [4][2048]u8 = undefined; var lens: [4]usize = undefined; var routes: [4]quic.path.Id = undefined; var count: usize = 0; while (count < held.len) : (count += 1) { const d = (try p.client.send(&buffer, p.now)) orelse break; @memcpy(held[count][0..d.bytes.len], d.bytes); lens[count] = d.bytes.len; routes[count] = d.path; } try testing.expect(count >= 2); try testing.expectEqual(@as(quic.path.Id, 1), routes[0]); try testing.expectEqual(@as(quic.path.Id, 0), routes[1]); for (0..count) |i| { p.now += std.time.ns_per_ms; try p.server.receive(held[i][0..lens[i]], routes[i], p.now); } try p.settle(); try testing.expectEqualSlices(u8, &text, p.server.readable(p.server.accept().?)); } test "draft-ietf-quic-multipath-21 3.3: the scheduler keeps off a backup path while another has room" { var t: TwoPaths = .{}; const p = try t.start(0x3e23); try openSecondPath(p); p.client.setScheduler(.lowest_rtt); // Path 1 is faster, but the server asked that it be kept for backup. p.client.rtt.smoothed = 200 * std.time.ns_per_ms; try p.server.setPathStatus(1, .backup); try p.settle(); try testing.expectEqual(@as(u64, 0), try sendCounting(p, "not on backup", 1)); } /// How much path 0's congestion window grows while `text` is sent over it /// in congestion avoidance, with path 1 open beside it, under `scheduler`. fn growthOnPath0(t: *TwoPaths, seed: u64, scheduler: quic.Connection.Scheduler, text: []const u8) !usize { const p = try t.start(seed); try openSecondPath(p); p.client.setScheduler(scheduler); // Path 0 the faster, so that the lowest-RTT scheduler keeps the stream // there too, and both paths past slow start. p.client.extra[0].rtt.smoothed = 200 * std.time.ns_per_ms; p.client.congestion.ssthresh = 1; p.client.extra[0].congestion.ssthresh = 1; const before = p.client.congestion.window; try testing.expectEqual(@as(u64, 0), try sendCounting(p, text, 1)); return p.client.congestion.window - before; } test "draft-ietf-quic-multipath-21 5.3: paths shared by the scheduler grow as linked increases say" { // RFC 6356's coupling applies when the lowest-RTT scheduler is spreading // data, and not when one chosen path carries it all: the same exchange // grows path 0's window less under the first than under the second. const text: [2000]u8 = @splat('c'); var a: TwoPaths = .{}; const alone = try growthOnPath0(&a, 0x3e24, .chosen, &text); var b: TwoPaths = .{}; const linked = try growthOnPath0(&b, 0x3e24, .lowest_rtt, &text); try testing.expect(alone > 0); try testing.expect(linked < alone); } test "draft-ietf-quic-multipath-21: CRYPTO goes on another path once path 0 is gone, and comes back when lost" { // With path 0 abandoned, a post-handshake message -- a NewSessionTicket, // say -- has no path but path 1 to go on. What it carried goes back into // the application level's CRYPTO stream when the packet is lost, not into // path 1's space, which has no stream to send it from. The octets here // are stand-ins and never reach the client's TLS. var t: TwoPaths = .{}; const p = try t.start(0x3e25); try openSecondPath(p); try p.client.abandonPath(0); try p.settle(); try testing.expect(p.server.path0_abandoned); try p.server.spaces[2].crypto.write("a stand-in for a ticket"); var buffer: [2048]u8 = undefined; const carried = (try p.server.send(&buffer, p.now)).?; try testing.expectEqual(@as(quic.path.Id, 1), carried.path); try testing.expect(!p.server.spaces[2].crypto.pending()); const sent = p.server.extra[0].space.loss.unacked(); try testing.expect(sent.len > 0 and sent[sent.len - 1].crypto_len > 0); // Dropped. The probe timeout on path 1 gives it up, and the octets are // owed again from the stream they came from. const at = p.server.timeout().?; p.now = @max(p.now, at); p.server.onTimeout(p.now); try testing.expect(p.server.spaces[2].crypto.pending()); } // -- n0's NAT traversal ------------------------------------------------------- fn addr4(a: u8, b: u8, c: u8, d: u8, port: u16) quic.frame.Address { return .{ .ip = .{ .v4 = .{ a, b, c, d } }, .port = port }; } /// A network for NAT traversal tests: each end has an address on two /// networks, 10.0.0.0/24 and 10.0.1.0/24, a datagram leaves from whichever /// of its sender's addresses is on its destination's network, and each end /// numbers the addresses it hears from as `Session` does -- route 0 for the /// handshake's, the next free one for anything new -- telling the /// connection where each came from before handing it over. const NatNet = struct { p: *Pair, routes: [2][quic.path.capacity]?quic.frame.Address = .{ @splat(null), @splat(null) }, /// The server's NAT, when set: it drops what arrives from an address /// the server has not yet sent anything to. server_nat: bool = false, server_sent_to: [8]?quic.frame.Address = @splat(null), delivered: usize = 0, const client_addresses = [2]quic.frame.Address{ addr4(10, 0, 0, 1, 1000), addr4(10, 0, 1, 1, 1000) }; const server_addresses = [2]quic.frame.Address{ addr4(10, 0, 0, 2, 443), addr4(10, 0, 1, 2, 443) }; fn init(p: *Pair) NatNet { var n: NatNet = .{ .p = p }; n.routes[0][0] = server_addresses[0]; n.routes[1][0] = client_addresses[0]; p.client.setPeerAddress(0, server_addresses[0]) catch unreachable; p.server.setPeerAddress(0, client_addresses[0]) catch unreachable; return n; } fn end(n: *NatNet, side: usize) *quic.Connection { return if (side == 0) n.p.client else n.p.server; } /// Carries one datagram from `side`, or drops it at the server's NAT. fn deliver(n: *NatNet, side: usize, d: quic.Connection.Datagram) !void { const to = d.to orelse n.routes[side][d.path].?; const net = to.ip.v4[2]; const from = (if (side == 0) client_addresses else server_addresses)[net]; if (side == 1) { for (&n.server_sent_to) |*slot| { if (slot.*) |seen| if (seen.eql(to)) break; if (slot.* == null) { slot.* = to; break; } } } else if (n.server_nat) { const opened = for (n.server_sent_to) |slot| { if (slot) |seen| if (seen.eql(from)) break true; } else false; if (!opened) return; } const other = 1 - side; const route: quic.path.Id = for (n.routes[other], 0..) |slot, i| { if (slot) |seen| if (seen.eql(from)) break @intCast(i); } else for (&n.routes[other], 0..) |*slot, i| { if (slot.* == null) { slot.* = from; break @intCast(i); } } else return error.TooManyRoutes; const receiver = n.end(other); n.p.now += std.time.ns_per_ms; try receiver.setPeerAddress(route, from); try receiver.receive(d.bytes, route, n.p.now); n.delivered += 1; } /// Exchanges datagrams, running timers when both ends are quiet, until /// `done` holds or `limit` passes. fn run(n: *NatNet, limit: usize, context: anytype, comptime done: fn (@TypeOf(context)) bool) !void { var buffer: [2048]u8 = undefined; var steps: usize = 0; while (steps < limit and !done(context)) : (steps += 1) { var moved = false; for (0..2) |side| { if (try n.end(side).send(&buffer, n.p.now)) |d| { try n.deliver(side, d); moved = true; } } if (!moved) { const at = @min(n.p.client.timeout() orelse std.math.maxInt(u64), n.p.server.timeout() orelse std.math.maxInt(u64)); if (at == std.math.maxInt(u64)) return; n.p.now = @max(n.p.now, at); n.p.client.onTimeout(n.p.now); n.p.server.onTimeout(n.p.now); } } } fn settle(n: *NatNet) !void { try n.run(200, n, never); } fn never(_: *NatNet) bool { return false; } /// The client's open path past path 0 whose route is `address`, if any. fn pathTo(n: *NatNet, address: quic.frame.Address) ?*const @TypeOf(n.p.client.extra[0]) { for (&n.p.client.extra) |*extra| { if (extra.state != .open) continue; const seen = n.routes[0][extra.route] orelse continue; if (seen.eql(address)) return extra; } return null; } }; fn natPair(t: *TwoPaths, seed: u64) !*Pair { t.client_nat = 8; t.server_nat = 8; const p = try t.start(seed); try testing.expect(p.client.natNegotiated() and p.server.natNegotiated()); return p; } test "n0 NAT traversal: negotiated only when both ends ask, with multipath" { var a: TwoPaths = .{ .client_nat = 8 }; const p = try a.start(0x3f01); try testing.expect(!p.client.natNegotiated() and !p.server.natNegotiated()); try testing.expectError(error.NotNegotiated, p.client.addNatAddress(addr4(10, 0, 1, 1, 1))); var b: TwoPaths = .{}; const q = try natPair(&b, 0x3f02); _ = q; } test "n0 NAT traversal: a frame nobody negotiated, or sent the wrong way, is a protocol violation" { var a: TwoPaths = .{}; const p = try a.start(0x3f03); try testing.expectError(error.ProtocolViolation, inject(p, p.server, p.client, .{ .add_address = .{ .sequence = 0, .address = addr4(10, 0, 1, 2, 443) }, })); var b: TwoPaths = .{}; const q = try natPair(&b, 0x3f04); // ADD_ADDRESS is the server's to send, and REACH_OUT the client's. try testing.expectError(error.ProtocolViolation, inject(q, q.client, q.server, .{ .add_address = .{ .sequence = 0, .address = addr4(10, 0, 1, 1, 1000) }, })); var c: TwoPaths = .{}; const r = try natPair(&c, 0x3f05); try testing.expectError(error.ProtocolViolation, inject(r, r.server, r.client, .{ .reach_out = .{ .sequence = 1, .address = addr4(10, 0, 1, 2, 443) }, })); } test "n0 NAT traversal: more REACH_OUT addresses in a round than the server allows is refused" { var t: TwoPaths = .{ .client_nat = 8, .server_nat = 2 }; const p = try t.start(0x3f06); for (0..2) |i| try inject(p, p.client, p.server, .{ .reach_out = .{ .sequence = 1, .address = addr4(10, 0, 1, @intCast(i + 1), 1000) }, }); try testing.expectError(error.ProtocolViolation, inject(p, p.client, p.server, .{ .reach_out = .{ .sequence = 1, .address = addr4(10, 0, 1, 3, 1000) }, })); } test "n0 NAT traversal: the server's candidates reach the client, and withdrawn ones leave" { var t: TwoPaths = .{}; const p = try natPair(&t, 0x3f07); var n: NatNet = .init(p); try p.server.addNatAddress(NatNet.server_addresses[1]); try p.server.addNatAddress(addr4(192, 0, 2, 1, 443)); try n.settle(); try testing.expectEqual(@as(usize, 2), p.client.natRemoteCount()); try p.server.removeNatAddress(addr4(192, 0, 2, 1, 443)); try n.settle(); try testing.expectEqual(@as(usize, 1), p.client.natRemoteCount()); } fn clientHasNatPath(n: *NatNet) bool { const extra = n.pathTo(NatNet.server_addresses[1]) orelse return false; const seen = n.p.client.paths.find(extra.route) orelse return false; return seen.validated; } test "n0 NAT traversal: a round finds a hole, and the client opens a path through it" { // The server advertises its address on the second network, the client // offers its own there and starts a round. Its probe to the server's // candidate is answered; it opens path 1 over that route, marked backup, // and validates it the ordinary multipath way. Data can then go over it. var t: TwoPaths = .{}; const p = try natPair(&t, 0x3f08); var n: NatNet = .init(p); try p.server.addNatAddress(NatNet.server_addresses[1]); try p.client.addNatAddress(NatNet.client_addresses[1]); try n.settle(); try testing.expectEqual(@as(usize, 1), p.client.natRemoteCount()); try p.client.startNatRound(p.now); try n.run(400, &n, clientHasNatPath); try testing.expect(clientHasNatPath(&n)); const extra = n.pathTo(NatNet.server_addresses[1]).?; try testing.expectEqual(quic.frame.PathStatus.Status.backup, extra.status.local.?); // The server heard the client's candidate, and probed it too. try testing.expectEqual(@as(usize, 1), p.server.natRemoteCount()); try p.client.useSendPath(extra.id); const stream_id = try p.client.openBidirectional(); try p.client.write(stream_id, "through the hole"); try p.client.finishStream(stream_id); try n.settle(); try testing.expectEqualStrings("through the hole", p.server.readable(p.server.accept().?)); } test "n0 NAT traversal: behind a NAT, the server's probe opens the hole the client's answer comes back by" { // The server's NAT drops the client's probes, since the server has never // sent to the client's candidate address. The server's own probe to it // opens the way; the client answers with a PATH_RESPONSE and a challenge // of its own, and the server's answer to that is the client's proof. var t: TwoPaths = .{}; const p = try natPair(&t, 0x3f09); var n: NatNet = .init(p); try p.server.addNatAddress(NatNet.server_addresses[1]); try p.client.addNatAddress(NatNet.client_addresses[1]); try n.settle(); n.server_nat = true; // The handshake's route has been sent to, so it stays open. n.server_sent_to[0] = NatNet.client_addresses[0]; try p.client.startNatRound(p.now); try n.run(400, &n, clientHasNatPath); try testing.expect(clientHasNatPath(&n)); } test "n0 NAT traversal: with nothing to probe, the client learns of the hole from its own challenge" { // The server advertises no candidates, so the client's round probes // nothing and only the server punches -- at the client's candidate, from // the server's address on that network. The client's answer carries a // PATH_CHALLENGE of its own, and the server's answer to *that* is the // only way the client can learn a path is there: without it, nothing. var t: TwoPaths = .{}; const p = try natPair(&t, 0x3f0a); var n: NatNet = .init(p); try p.client.addNatAddress(NatNet.client_addresses[1]); try testing.expectEqual(@as(usize, 0), p.client.natRemoteCount()); try p.client.startNatRound(p.now); try n.run(400, &n, clientHasNatPath); try testing.expect(clientHasNatPath(&n)); } // -- draft-ietf-quic-ack-frequency-14 ------------------------------------------ /// A pair whose ends advertise min_ack_delay as given, handshake done. const AckFrequencyPair = struct { o: Observing = .{}, fn start(a: *AckFrequencyPair, seed: u64, client_min: ?u64, server_min: ?u64) !*Pair { a.o.rng_impl = .init(seed); var cp = stream_limits; cp.min_ack_delay = client_min; var c = cp; c.initial_source_connection_id = &client_connection_id; const client_encoded = try quic.parameters.write(&c, &a.o.client_params, .client); var sp = stream_limits; sp.min_ack_delay = server_min; var sv = sp; sv.initial_source_connection_id = &server_connection_id; sv.original_destination_connection_id = &destination_connection_id; const server_encoded = try quic.parameters.write(&sv, &a.o.server_params, .server); a.o.pair = try unshakenPair( a.o.rng_impl.random(), &a.o.client_tls, &a.o.server_tls, &a.o.client, &a.o.server, a.o.client_memory.memory(), a.o.server_memory.memory(), client_encoded, server_encoded, cp, sp, ); try a.o.pair.handshake(); try a.o.pair.settle(); return &a.o.pair; } }; /// Sends `count` PINGs from the server to the client, one packet each, and /// counts the datagrams the client has to send back after each -- which, /// with nothing else to say, are its ACKs. fn acksForPings(p: *Pair, count: usize) !usize { var acks: usize = 0; var buffer: [2048]u8 = undefined; for (0..count) |_| { try inject(p, p.server, p.client, .ping); while (try p.client.send(&buffer, p.now)) |_| acks += 1; } return acks; } test "draft-ietf-quic-ack-frequency-14 6: an Ack-Eliciting Threshold of 9 is one ACK in ten" { var a: AckFrequencyPair = .{}; const p = try a.start(0xaf01, 1000, 1000); // Before any ACK_FREQUENCY, every ack-eliciting packet is acknowledged, // as this library always has. try testing.expectEqual(@as(usize, 20), try acksForPings(p, 20)); // The server asks for one in ten, with the delay out of the way. try p.server.requestAckFrequency(9, 10 * std.time.ns_per_s, 0); try p.settle(); try testing.expectEqual(@as(u64, 9), p.client.ack_frequency.?.threshold); try testing.expectEqual(@as(usize, 2), try acksForPings(p, 20)); } test "draft-ietf-quic-ack-frequency-14 6: an ACK held back goes out when its delay runs out" { var a: AckFrequencyPair = .{}; const p = try a.start(0xaf02, 1000, 1000); try p.server.requestAckFrequency(100, 40 * std.time.ns_per_ms, 0); try p.settle(); try testing.expectEqual(@as(usize, 0), try acksForPings(p, 1)); const due = p.client.timeout().?; try testing.expect(due > p.now and due <= p.now + 40 * std.time.ns_per_ms); p.now = due; p.client.onTimeout(p.now); var buffer: [2048]u8 = undefined; try testing.expect((try p.client.send(&buffer, p.now)) != null); } test "draft-ietf-quic-ack-frequency-14 5: IMMEDIATE_ACK is acknowledged at once" { var a: AckFrequencyPair = .{}; const p = try a.start(0xaf03, 1000, 1000); try p.server.requestAckFrequency(100, 10 * std.time.ns_per_s, 0); try p.settle(); try testing.expectEqual(@as(usize, 0), try acksForPings(p, 3)); try inject(p, p.server, p.client, .immediate_ack); var buffer: [2048]u8 = undefined; try testing.expect((try p.client.send(&buffer, p.now)) != null); } test "draft-ietf-quic-ack-frequency-14 3: the frames are only for an end that said it takes them" { var a: AckFrequencyPair = .{}; const p = try a.start(0xaf04, null, 1000); // The server takes them; the client did not say so. try testing.expectError(error.NotSupported, p.server.requestAckFrequency(1, 25 * std.time.ns_per_ms, 1)); try testing.expectError(error.NotSupported, p.server.requestImmediateAck()); try p.client.requestAckFrequency(1, 25 * std.time.ns_per_ms, 1); try testing.expectError(error.ProtocolViolation, inject(p, p.server, p.client, .immediate_ack)); } test "draft-ietf-quic-ack-frequency-14 4: a delay below min_ack_delay is refused, and a stale frame ignored" { var a: AckFrequencyPair = .{}; const p = try a.start(0xaf05, 5000, 5000); // Asking is refused locally... try testing.expectError(error.InvalidDelay, p.server.requestAckFrequency(1, 4 * std.time.ns_per_ms, 1)); try testing.expectError(error.InvalidDelay, p.server.requestAckFrequency(1, (1 << 14) * std.time.ns_per_ms, 1)); // ...and receiving is a violation. try inject(p, p.server, p.client, .{ .ack_frequency = .{ .sequence = 5, .ack_eliciting_threshold = 7, .requested_max_ack_delay = 5000, .reordering_threshold = 1 } }); try inject(p, p.server, p.client, .{ .ack_frequency = .{ .sequence = 4, .ack_eliciting_threshold = 2, .requested_max_ack_delay = 9000, .reordering_threshold = 1 } }); try testing.expectEqual(@as(u64, 7), p.client.ack_frequency.?.threshold); try testing.expectError(error.ProtocolViolation, inject(p, p.server, p.client, .{ .ack_frequency = .{ .sequence = 6, .ack_eliciting_threshold = 1, .requested_max_ack_delay = 4999, .reordering_threshold = 1 }, })); } test "draft-ietf-quic-ack-frequency-14 7: the requested delay counts once acknowledged, and the larger until then" { var a: AckFrequencyPair = .{}; const p = try a.start(0xaf06, 1000, 1000); // 100 ms, above the default 25 ms: in flight, the PTO already allows it. try p.server.requestAckFrequency(1, 100 * std.time.ns_per_ms, 1); var buffer: [2048]u8 = undefined; const d = (try p.server.send(&buffer, p.now)).?; try testing.expect(p.server.ack_frequency_in_flight != null); try testing.expectEqual(@as(?u64, null), p.server.peer_max_ack_delay_us); p.now += std.time.ns_per_ms; const received_at = p.now; try p.client.receive(d.bytes, d.path, p.now); // The client now acknowledges every other packet or after 100 ms, and // this was one packet: its ACK waits out the delay the frame asked for. try p.settle(); try testing.expectEqual(@as(?u64, null), p.server.peer_max_ack_delay_us); const due = p.client.timeout().?; try testing.expectEqual(received_at + 100 * std.time.ns_per_ms, due); p.now = due; p.client.onTimeout(p.now); try p.settle(); try testing.expectEqual(@as(?u64, 100_000), p.server.peer_max_ack_delay_us); try testing.expect(p.server.ack_frequency_in_flight == null); } test "draft-ietf-quic-ack-frequency-14 4: a lost ACK_FREQUENCY is sent again" { var a: AckFrequencyPair = .{}; const p = try a.start(0xaf07, 1000, 1000); try p.server.requestAckFrequency(4, 30 * std.time.ns_per_ms, 1); var buffer: [2048]u8 = undefined; _ = (try p.server.send(&buffer, p.now)).?; // dropped var rounds: usize = 0; while (p.client.ack_frequency == null and rounds < 8) : (rounds += 1) { const at = p.server.timeout() orelse break; p.now = @max(p.now, at); p.server.onTimeout(p.now); try p.settle(); } try testing.expectEqual(@as(u64, 4), p.client.ack_frequency.?.threshold); // The second went out under a new sequence number. try testing.expectEqual(@as(u64, 2), p.server.ack_frequency_next); } test "RFC 9002 6.2: a waking that is not the probe timeout's does not fire it" { // A connection has other timers now -- an ACK held back, a NAT traversal // round, an abandoned path -- and being woken for one of them must not // put everything in flight back on the wire as if it were lost. var a: AckFrequencyPair = .{}; const p = try a.start(0xaf08, 1000, 1000); const stream_id = try p.client.openBidirectional(); try p.client.write(stream_id, "still in flight"); var buffer: [2048]u8 = undefined; _ = (try p.client.send(&buffer, p.now)).?; try testing.expect(p.client.spaces[2].loss.inFlight() > 0); p.client.onTimeout(p.now + 1); try testing.expectEqual(@as(u32, 0), p.client.pto_count); try testing.expect(!p.client.probe_pending); try testing.expect((try p.client.send(&buffer, p.now + 1)) == null); }