diff --git a/Cargo.lock b/Cargo.lock index 39803fdf..f97b7cfa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -449,9 +449,9 @@ checksum = "570b591f2c5947596f3e5b0fcf59a71068ece15aa710446ce7eb670c3620350c" [[package]] name = "brotli" -version = "9.1.3" +version = "9.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +checksum = "8aa80dae1bf2461007e6b64308edc7c59b1aca84e5b0fc59dc0a22606d897a86" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -460,9 +460,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "6.3.1" +version = "6.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f" +checksum = "968e28b51837a735d00f25c8d10cca6ab376cec4813a65bb8eab1bbce97502c2" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", diff --git a/Cargo.toml b/Cargo.toml index 95df4a8f..3cbc026f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -190,7 +190,8 @@ redis = { version = "1.7", default-features = false, features = ["tokio-comp", " async-compression = { version = "0.4", features = ["tokio", "brotli", "zstd", "gzip", "zlib"] } brotli = "9" # RFC 9842 dcb: Brotli against a raw LZ77 dictionary, output identical to the -# reference encoder (the brotli crate's custom-dictionary encoder wrote corrupt streams) +# reference encoder; brotli's decoder checks each stream (brotli-decompressor +# 6.4.2 and later read a dictionary copy that runs on into the window) mbrotli = { version = "0.5", default-features = false, features = ["std", "compression"] } zstd = "0.14" flate2 = "1.0" diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 2081347b..9dc68f70 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -411,9 +411,9 @@ checksum = "570b591f2c5947596f3e5b0fcf59a71068ece15aa710446ce7eb670c3620350c" [[package]] name = "brotli" -version = "9.1.3" +version = "9.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +checksum = "8aa80dae1bf2461007e6b64308edc7c59b1aca84e5b0fc59dc0a22606d897a86" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -422,9 +422,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "6.3.2" +version = "6.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e" +checksum = "968e28b51837a735d00f25c8d10cca6ab376cec4813a65bb8eab1bbce97502c2" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -2538,7 +2538,7 @@ dependencies = [ [[package]] name = "pqcrypta-proxy" -version = "0.29.0" +version = "0.31.0" dependencies = [ "anyhow", "arc-swap", diff --git a/fuzz/seeds/moq_control/publish-fill-empty-filter b/fuzz/seeds/moq_control/publish-fill-empty-filter new file mode 100644 index 00000000..fc36c56c Binary files /dev/null and b/fuzz/seeds/moq_control/publish-fill-empty-filter differ diff --git a/src/compression.rs b/src/compression.rs index 7431d921..d40c4761 100644 --- a/src/compression.rs +++ b/src/compression.rs @@ -914,9 +914,7 @@ pub fn encode_dcb(data: &[u8], dict: &StoredDictionary, quality: u32) -> std::io )); }; - // mbrotli, whose output is the reference encoder's: the brotli crate's - // encoder wrote streams with a custom dictionary at some qualities that - // no decoder (the reference one included) could read. The reference + // mbrotli, whose output is the reference encoder's. The reference // searches a dictionary only from quality 5 (below it the dictionary is // ignored), so a lower configured quality is raised to 5 for dcb. let quality = mbrotli::Quality::try_from(u8::try_from(quality.clamp(5, 11)).unwrap_or(11)) @@ -2096,9 +2094,7 @@ mod tests { ); } - /// Every quality, small to large dictionaries: the brotli crate's encoder - /// wrote streams no decoder could read at quality 2 always and at quality - /// 5 from about 70 KB of dictionary; each must now decode to the body + /// Every quality, small to large dictionaries: each must decode to the body #[test] fn dcb_round_trips_at_every_quality_and_dictionary_size() { let mut base = String::new(); @@ -2130,6 +2126,85 @@ mod tests { } } + /// A copy that starts in the dictionary and runs on into the stream's own + /// window: what the brotli crate's encoder writes at quality 2 against a + /// 64 KiB dictionary. Decoders before brotli-decompressor 6.4.2 refused + /// it as invalid (dropbox/rust-brotli-decompressor#104), which made + /// `decode_dcb` turn away valid streams. + #[test] + fn decode_dcb_reads_a_dictionary_copy_that_runs_into_the_window() { + use brotli::enc::encode::{ + BrotliEncoderOperation, BrotliEncoderParameter, BrotliEncoderStateStruct, + }; + use brotli::enc::StandardAlloc; + + // Word-like text from an xorshift: the body begins as the dictionary does + fn text(mut seed: u64, len: usize) -> Vec { + let words = [ + "fn ", + "let ", + "const ", + "return ", + "match ", + "impl ", + "pub ", + "struct ", + "async ", + "await ", + "self", + ".map(", + "?;\n", + " => ", + "{\n", + "}\n", + "value", + "quic", + "brotli", + "dictionary", + ]; + let mut out = Vec::with_capacity(len); + while out.len() < len { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let word = usize::try_from(seed % u64::try_from(words.len()).unwrap()).unwrap(); + out.extend_from_slice(words[word].as_bytes()); + } + out.truncate(len); + out + } + let dict = text(7, 64 << 10); + let mut body = text(7, 64 << 10); + body.extend_from_slice(&text(99, 25 << 10)); + + let mut encoder = BrotliEncoderStateStruct::new(StandardAlloc::default()); + encoder.set_parameter(BrotliEncoderParameter::BROTLI_PARAM_QUALITY, 2); + encoder.set_parameter(BrotliEncoderParameter::BROTLI_PARAM_LGWIN, DCB_LGWIN); + encoder.set_custom_dictionary(dict.len(), &dict); + let mut stream = vec![0u8; body.len() * 2 + 1024]; + let (mut avail_in, mut next_in, mut avail_out, mut next_out) = + (body.len(), 0usize, stream.len(), 0usize); + while !encoder.is_finished() { + assert!(encoder.compress_stream( + BrotliEncoderOperation::BROTLI_OPERATION_FINISH, + &mut avail_in, + &body, + &mut next_in, + &mut avail_out, + &mut stream, + &mut next_out, + &mut None, + &mut |_, _, _, _| (), + )); + } + stream.truncate(next_out); + + let mut encoded = DCB_MAGIC.to_vec(); + encoded.extend_from_slice(&Sha256::digest(&dict)); + encoded.extend_from_slice(&stream); + assert_eq!(decode_dcb(&encoded, &dict).unwrap(), body); + } + #[test] fn compression_request_combines_multiple_accept_encoding_headers() { let mut h = HeaderMap::new(); diff --git a/src/moq/message.rs b/src/moq/message.rs index 03baf2c1..9c2185eb 100644 --- a/src/moq/message.rs +++ b/src/moq/message.rs @@ -1542,6 +1542,16 @@ mod tests { } } + /// A PUBLISH whose FILL_PARAMETERS hold a Range Filter of Length 0, which + /// outside a REQUEST_UPDATE is no filter and is not encoded again: the + /// input ClusterFuzzLite found on 2026-12-04 + #[test] + fn control_check_takes_a_publish_with_an_empty_fill_filter() { + crate::moq::check::control(include_bytes!( + "../../fuzz/seeds/moq_control/publish-fill-empty-filter" + )); + } + #[test] fn the_pause_parameter_differs_by_draft() { let p = Params { diff --git a/src/moq/mod.rs b/src/moq/mod.rs index 3b4872c5..5391a924 100644 --- a/src/moq/mod.rs +++ b/src/moq/mod.rs @@ -88,18 +88,35 @@ pub mod check { || !p.removed_filters.is_empty() || p.fill.as_deref().is_some_and(unencodable) } - let skip = match &m { + // Every message that carries parameters: FILL_PARAMETERS "MAY + // appear in a SUBSCRIBE, SUBSCRIBE_TRACKS, PUBLISH, or + // REQUEST_UPDATE", and a Range Filter of Length 0 is a removal + // only in a REQUEST_UPDATE, no filter anywhere else, so it is + // never re-encoded + let params = match &m { Message::Subscribe(r) | Message::Fetch(r) | Message::TrackStatus(r) => { - unencodable(&r.params) + Some(&r.params) } - Message::SubscribeTracks(r) => unencodable(&r.params), - Message::RequestUpdate { params, .. } => unencodable(params), - // A Reason Phrase that was not UTF-8 is kept as text with - // replacement characters, which can outgrow its 1024 bytes - Message::PublishDone { reason, .. } => reason.contains('\u{FFFD}'), - Message::RequestError(e) => e.reason.contains('\u{FFFD}'), - _ => false, + Message::PublishNamespace(r) + | Message::SubscribeNamespace(r) + | Message::SubscribeTracks(r) => Some(&r.params), + Message::Publish(p) => Some(&p.params), + Message::SubscribeOk { params, .. } + | Message::FetchOk22 { params, .. } + | Message::Namespace { params, .. } + | Message::RequestUpdate { params, .. } + | Message::RequestOk { params, .. } + | Message::PublishStateNotify(params) => Some(params), + _ => None, }; + let skip = params.is_some_and(unencodable) + || match &m { + // A Reason Phrase that was not UTF-8 is kept as text with + // replacement characters, which can outgrow its 1024 bytes + Message::PublishDone { reason, .. } => reason.contains('\u{FFFD}'), + Message::RequestError(e) => e.reason.contains('\u{FFFD}'), + _ => false, + }; if skip { return; } diff --git a/vendor/noq/VENDORED.md b/vendor/noq/VENDORED.md index 83be2fa7..669c3571 100644 --- a/vendor/noq/VENDORED.md +++ b/vendor/noq/VENDORED.md @@ -33,7 +33,13 @@ when the proxy builds noq as a dependency. - A server that rejects a ClientHello spanning two Initial packets (a hybrid post-quantum key share makes most ClientHellos this size) says so with CONNECTION_CLOSE too, on the path the connection began on, within the - anti-amplification limit; upstream n0-computer/noq#892. + anti-amplification limit, and again for each Initial the client sends + again there while the Initial keys exist (the first close was lost); + upstream n0-computer/noq#892. +- A handshake is confirmed once both the Initial and the Handshake keys are + gone. A connection that closed in the Initial space never had Handshake + keys, so it no longer counts as confirmed, and does not take probing or + migrating packets; upstream n0-computer/noq#920. - RESET_STREAM_AT (draft-ietf-quic-reliable-stream-reset): the `reset_stream_at` transport parameter (on by default), the frame both ways, and `SendStream::reset_at`. This is a port of n0-computer/noq#843 onto this diff --git a/vendor/noq/noq-proto/src/connection/mod.rs b/vendor/noq/noq-proto/src/connection/mod.rs index 7145cb43..9a70934e 100644 --- a/vendor/noq/noq-proto/src/connection/mod.rs +++ b/vendor/noq/noq-proto/src/connection/mod.rs @@ -4675,11 +4675,20 @@ impl Connection { // schedule such a packet. We should also fix this some day. This makes us // vulnerable to an attacker faking a migration at the right time and then we'd // be unable to send the CONNECTION_CLOSE to the real remote. + // + // Before the path is validated, an Initial the client sends again on the path + // the connection began on, while the Initial keys exist, is answered too: the + // client sends it again because the first CONNECTION_CLOSE did not arrive (a + // ClientHello refused after its second datagram, n0-computer/noq#892). What + // goes out on an unvalidated path stays within the 3x anti-amplification limit + // (path_congestion_check). if self .paths .get(&path_id) .map(|p| { - p.data.validated && p.data.network_path.is_probably_same_path(&network_path) + p.data.network_path.is_probably_same_path(&network_path) + && (p.data.validated + || self.crypto_state.has_keys(EncryptionLevel::Initial)) }) .unwrap_or(false) { @@ -7591,9 +7600,13 @@ impl Connection { /// your TLS Finished message. /// /// Implementation-wise this is the point at which the handshake crypto keys are - /// discarded. So we can use this to know if the handshake is confirmed. + /// discarded. The Initial keys must be gone too: a connection that closed in the + /// Initial space never had Handshake keys to discard, and was never confirmed. A + /// confirmed connection stays confirmed once it closes or drains. fn is_handshake_confirmed(&self) -> bool { - !self.is_handshaking() && !self.crypto_state.has_keys(EncryptionLevel::Handshake) + !self.is_handshaking() + && !self.crypto_state.has_keys(EncryptionLevel::Initial) + && !self.crypto_state.has_keys(EncryptionLevel::Handshake) } } @@ -8203,4 +8216,435 @@ mod tests { assert!(t.contains(&PathId(3))); assert_eq!(t.max(), Some(PathId(3))); } + + #[cfg(all(feature = "rustls", any(feature = "aws-lc-rs", feature = "ring")))] + fn make_tls_configs( + server_alpns: Vec>, + client_alpns: Vec>, + ) -> (ServerConfig, crate::ClientConfig) { + use crate::crypto::rustls::{QuicClientConfig, QuicServerConfig}; + use alloc::{string::ToString, vec}; + + #[cfg(feature = "ring")] + let provider = Arc::new(crate::rustls::crypto::ring::default_provider()); + #[cfg(all(not(feature = "ring"), feature = "aws-lc-rs"))] + let provider = Arc::new(crate::rustls::crypto::aws_lc_rs::default_provider()); + + let key_pair = rcgen::KeyPair::generate().unwrap(); + let params = rcgen::CertificateParams::new(vec!["localhost".to_string()]).unwrap(); + let cert = params.self_signed(&key_pair).unwrap(); + let cert_der = cert.der().clone(); + let key_der = crate::rustls::pki_types::PrivateKeyDer::Pkcs8( + crate::rustls::pki_types::PrivatePkcs8KeyDer::from(key_pair.serialize_der()), + ); + + let mut server_crypto = + crate::rustls::ServerConfig::builder_with_provider(provider.clone()) + .with_protocol_versions(&[&crate::rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![cert_der.clone()], key_der) + .unwrap(); + server_crypto.alpn_protocols = server_alpns; + let mut server_config = + ServerConfig::with_crypto(Arc::new(QuicServerConfig::try_from(server_crypto).unwrap())); + server_config.migration = true; + + let mut roots = crate::rustls::RootCertStore::empty(); + roots.add(cert_der).unwrap(); + let mut client_crypto = crate::rustls::ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[&crate::rustls::version::TLS13]) + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + client_crypto.alpn_protocols = client_alpns; + let client_config = + crate::ClientConfig::new(Arc::new(QuicClientConfig::try_from(client_crypto).unwrap())); + + (server_config, client_config) + } + + #[cfg(all(feature = "rustls", any(feature = "aws-lc-rs", feature = "ring")))] + #[test] + fn closed_in_initial_space_is_not_handshake_confirmed() { + use crate::{DatagramEvent, Endpoint}; + use alloc::vec; + use core::net::{IpAddr, Ipv4Addr}; + + let mut client_alpns = vec![b"h3".to_vec()]; + for i in 0..8u8 { + let mut proto = format!("pad-alpn-{i:02}-").into_bytes(); + proto.resize(200, b'a'); + client_alpns.push(proto); + } + let (server_config, client_config) = + make_tls_configs(vec![b"other-proto".to_vec()], client_alpns); + let mut server_ep = Endpoint::new( + Arc::new(EndpointConfig::default()), + Some(Arc::new(server_config)), + false, + ); + let mut client_ep = Endpoint::new(Arc::new(EndpointConfig::default()), None, false); + + let now = Instant::now(); + let client_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 10002)); + let server_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 20002)); + let spoof_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 19998)); + + let (_client_ch, mut client_conn) = client_ep + .connect(now, client_config, server_addr, "localhost") + .unwrap(); + + let mut client_datagrams = Vec::new(); + let mut tx_buf = Vec::new(); + while let Some(t) = client_conn.poll_transmit(now, NonZeroUsize::MIN, &mut tx_buf) { + client_datagrams.push(BytesMut::from(&tx_buf[..t.size])); + tx_buf.clear(); + } + assert!(client_datagrams.len() >= 2); + + let mut response_buf = Vec::new(); + let Some(DatagramEvent::NewConnection(incoming)) = server_ep.handle( + now, + FourTuple::from_remote(client_addr), + None, + client_datagrams[0].clone(), + &mut response_buf, + ) else { + panic!("expected NewConnection for first Initial datagram"); + }; + for dgram in &client_datagrams[1..] { + assert!( + server_ep + .handle( + now, + FourTuple::from_remote(client_addr), + None, + dgram.clone(), + &mut response_buf, + ) + .is_none() + ); + } + + let (server_ch, mut server_conn) = server_ep + .accept(incoming, now, &mut response_buf, None) + .expect("accept should return closed connection after buffered datagram"); + + assert!(server_conn.is_closed()); + assert!( + !server_conn + .crypto_state + .has_keys(EncryptionLevel::Handshake) + ); + assert!( + !server_conn.is_handshake_confirmed(), + "connection closed during Initial space must not report handshake confirmed" + ); + assert!( + !server_conn.peer_may_probe(), + "connection closed during Initial space must not allow off-path probing" + ); + assert!(!server_conn.peer_may_migrate()); + + let mut close_buf = Vec::new(); + assert!( + server_conn + .poll_transmit(now, NonZeroUsize::MIN, &mut close_buf) + .is_some() + ); + + let pto = client_conn + .poll_timeout() + .expect("client PTO must be armed"); + client_conn.handle_timeout(pto); + let mut retransmit_buf1 = Vec::new(); + let rt1 = client_conn + .poll_transmit(pto, NonZeroUsize::MIN, &mut retransmit_buf1) + .expect("client should emit first PTO probe"); + let mut retransmit_buf2 = Vec::new(); + let rt2 = client_conn + .poll_transmit(pto, NonZeroUsize::MIN, &mut retransmit_buf2) + .expect("client should emit second PTO probe"); + + let recvd_before = server_conn.total_recvd(); + let rx_before = server_conn.stats().udp_rx; + let Some(DatagramEvent::ConnectionEvent(ch, ev)) = server_ep.handle( + pto, + FourTuple::from_remote(spoof_addr), + None, + BytesMut::from(&retransmit_buf1[..rt1.size]), + &mut response_buf, + ) else { + panic!("expected spoofed Initial to route to server connection"); + }; + assert_eq!(ch, server_ch); + server_conn.handle_event(ev); + + assert_eq!( + server_conn.total_recvd(), + recvd_before, + "packet from unrecognized remote must be discarded before incrementing total_recvd" + ); + assert_eq!( + server_conn.stats().udp_rx.datagrams, + rx_before.datagrams, + "packet from unrecognized remote must be discarded before udp_rx accounting" + ); + assert_eq!(server_conn.stats().udp_rx.bytes, rx_before.bytes); + let mut spoof_tx_buf = Vec::new(); + assert!( + server_conn + .poll_transmit(pto, NonZeroUsize::MIN, &mut spoof_tx_buf) + .is_none() + ); + + // Legitimate client retransmission on the original path still elicits CONNECTION_CLOSE. + let Some(DatagramEvent::ConnectionEvent(ch, ev)) = server_ep.handle( + pto, + FourTuple::from_remote(client_addr), + None, + BytesMut::from(&retransmit_buf2[..rt2.size]), + &mut response_buf, + ) else { + panic!("expected client Initial retransmission to route to server connection"); + }; + assert_eq!(ch, server_ch); + server_conn.handle_event(ev); + assert!(server_conn.total_recvd() > recvd_before); + let mut retry_close_buf = Vec::new(); + assert!( + server_conn + .poll_transmit(pto, NonZeroUsize::MIN, &mut retry_close_buf) + .is_some() + ); + + // Client closed in Initial space must also not treat the handshake as confirmed + // or allow local IP migration in early_discard_packet. + client_conn + .path_data_mut(PathId::ZERO) + .network_path + .local_ip = Some(IpAddr::V4(Ipv4Addr::LOCALHOST)); + client_conn.close(pto, 0u32.into(), Bytes::new()); + assert!(client_conn.is_closed()); + assert!( + !client_conn + .crypto_state + .has_keys(EncryptionLevel::Handshake) + ); + assert!(!client_conn.is_handshake_confirmed()); + assert!(!client_conn.local_ip_may_migrate()); + assert!(client_conn.early_discard_packet( + FourTuple::new(server_addr, Some(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)))), + PathId::ZERO, + )); + } + + #[cfg(all(feature = "rustls", any(feature = "aws-lc-rs", feature = "ring")))] + #[test] + fn handshake_confirmed_requires_established_without_handshake_keys() { + use crate::{DatagramEvent, Endpoint}; + use alloc::vec; + use core::net::Ipv4Addr; + + let (server_config, client_config) = + make_tls_configs(vec![b"h3".to_vec()], vec![b"h3".to_vec()]); + let mut server_ep = Endpoint::new( + Arc::new(EndpointConfig::default()), + Some(Arc::new(server_config)), + false, + ); + let mut client_ep = Endpoint::new(Arc::new(EndpointConfig::default()), None, false); + + let now = Instant::now(); + let client_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 10003)); + let server_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 20003)); + + let (client_ch, mut client_conn) = client_ep + .connect(now, client_config, server_addr, "localhost") + .unwrap(); + assert!(!client_conn.is_handshake_confirmed()); + + // Flight 1: Client Initial(s) -> Server. + let mut tx_buf = Vec::new(); + let mut response_buf = Vec::new(); + let mut incoming = None; + while let Some(t) = client_conn.poll_transmit(now, NonZeroUsize::MIN, &mut tx_buf) { + match server_ep.handle( + now, + FourTuple::from_remote(client_addr), + None, + BytesMut::from(&tx_buf[..t.size]), + &mut response_buf, + ) { + Some(DatagramEvent::NewConnection(inc)) => { + assert!(incoming.is_none()); + incoming = Some(inc); + } + None => { + assert!(incoming.is_some()); + } + _ => panic!("unexpected event for client Initial flight"), + } + tx_buf.clear(); + } + let incoming = incoming.expect("expected NewConnection for client Initial"); + let (server_ch, mut server_conn) = server_ep + .accept(incoming, now, &mut response_buf, None) + .expect("server accept should succeed"); + while let Some(ev) = server_conn.poll_endpoint_events() { + if let Some(cev) = server_ep.handle_event(server_ch, ev) { + server_conn.handle_event(cev); + } + } + assert!(server_conn.is_handshaking()); + assert!(!server_conn.is_handshake_confirmed()); + + // Flight 2: Server Initial + Handshake -> Client. + let t1 = now + Duration::from_millis(1); + while let Some(t) = server_conn.poll_transmit(t1, NonZeroUsize::MIN, &mut tx_buf) { + let Some(DatagramEvent::ConnectionEvent(ch, ev)) = client_ep.handle( + t1, + FourTuple::from_remote(server_addr), + None, + BytesMut::from(&tx_buf[..t.size]), + &mut response_buf, + ) else { + panic!("expected server flight to route to client"); + }; + assert_eq!(ch, client_ch); + client_conn.handle_event(ev); + tx_buf.clear(); + } + while let Some(ev) = client_conn.poll_endpoint_events() { + if let Some(cev) = client_ep.handle_event(client_ch, ev) { + client_conn.handle_event(cev); + } + } + assert!(client_conn.state.is_established()); + assert!( + client_conn + .crypto_state + .has_keys(EncryptionLevel::Handshake) + ); + assert!( + !client_conn.is_handshake_confirmed(), + "client handshake must not be confirmed before HANDSHAKE_DONE" + ); + + // Flight 3: Client Handshake Finished -> Server. + let t2 = t1 + Duration::from_millis(1); + while let Some(t) = client_conn.poll_transmit(t2, NonZeroUsize::MIN, &mut tx_buf) { + let Some(DatagramEvent::ConnectionEvent(ch, ev)) = server_ep.handle( + t2, + FourTuple::from_remote(client_addr), + None, + BytesMut::from(&tx_buf[..t.size]), + &mut response_buf, + ) else { + panic!("expected client Finished to route to server"); + }; + assert_eq!(ch, server_ch); + server_conn.handle_event(ev); + tx_buf.clear(); + } + assert!(server_conn.state.is_established()); + assert!(server_conn.is_handshake_confirmed()); + assert!(server_conn.peer_may_probe()); + assert!(server_conn.peer_may_migrate()); + + // Flight 4: Server HANDSHAKE_DONE -> Client. + let t3 = t2 + Duration::from_millis(1); + while let Some(t) = server_conn.poll_transmit(t3, NonZeroUsize::MIN, &mut tx_buf) { + let Some(DatagramEvent::ConnectionEvent(ch, ev)) = client_ep.handle( + t3, + FourTuple::from_remote(server_addr), + None, + BytesMut::from(&tx_buf[..t.size]), + &mut response_buf, + ) else { + panic!("expected server HANDSHAKE_DONE to route to client"); + }; + assert_eq!(ch, client_ch); + client_conn.handle_event(ev); + tx_buf.clear(); + } + assert!(client_conn.state.is_established()); + assert!(client_conn.is_handshake_confirmed()); + assert!(client_conn.local_ip_may_migrate()); + + // Closing after confirmation leaves the established state, not the confirmed one: + // the handshake still happened. + let t4 = t3 + Duration::from_millis(1); + server_conn.close(t4, 0u32.into(), Bytes::new()); + client_conn.close(t4, 0u32.into(), Bytes::new()); + assert!(!server_conn.state.is_established()); + assert!(server_conn.is_handshake_confirmed()); + assert!(client_conn.is_handshake_confirmed()); + } + + /// A server that closes while its first flight is still queued sends only CONNECTION_CLOSE + /// in the Initial space, unpadded (RFC 9000 section 14.1 pads ack-eliciting Initials): a + /// close sent again for a retransmitted ClientHello stays well within the + /// anti-amplification limit. + #[cfg(all(feature = "rustls", any(feature = "aws-lc-rs", feature = "ring")))] + #[test] + fn server_close_only_initial_is_not_padded() { + use crate::{DatagramEvent, Endpoint}; + use alloc::vec; + use core::net::Ipv4Addr; + + let (server_config, client_config) = + make_tls_configs(vec![b"h3".to_vec()], vec![b"h3".to_vec()]); + let mut server_ep = Endpoint::new( + Arc::new(EndpointConfig::default()), + Some(Arc::new(server_config)), + false, + ); + let mut client_ep = Endpoint::new(Arc::new(EndpointConfig::default()), None, false); + let now = Instant::now(); + let client_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 10004)); + let server_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 20004)); + + let (_, mut client_conn) = client_ep + .connect(now, client_config, server_addr, "localhost") + .unwrap(); + let mut buf = Vec::new(); + let mut response_buf = Vec::new(); + let mut incoming = None; + while let Some(t) = client_conn.poll_transmit(now, NonZeroUsize::MIN, &mut buf) { + match server_ep.handle( + now, + FourTuple::from_remote(client_addr), + None, + BytesMut::from(&buf[..t.size]), + &mut response_buf, + ) { + Some(DatagramEvent::NewConnection(i)) => incoming = Some(i), + None => assert!(incoming.is_some()), + _ => panic!("unexpected event for the client's first flight"), + } + buf.clear(); + } + let (_, mut server_conn) = server_ep + .accept( + incoming.expect("a new connection"), + now, + &mut response_buf, + None, + ) + .expect("the ClientHello is accepted"); + + // The ServerHello is queued, not sent: the server closes instead + server_conn.close(now, 0u32.into(), Bytes::new()); + let mut close_buf = Vec::new(); + let close = server_conn + .poll_transmit(now, NonZeroUsize::MIN, &mut close_buf) + .expect("CONNECTION_CLOSE"); + assert!( + close.size < 1200, + "close-only Initial of {} bytes", + close.size + ); + } }