diff --git a/Cargo.lock b/Cargo.lock index c581d9d0..40d0fa87 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -647,7 +647,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1102,7 +1102,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1529,9 +1529,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quinn" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", "cfg_aliases", @@ -1550,9 +1550,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.18" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", "getrandom 0.4.3", @@ -1572,16 +1572,16 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1756,7 +1756,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2015,7 +2015,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2383,7 +2383,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/compat/httpx/0.28.1/profile.toml b/compat/httpx/0.28.1/profile.toml index da57e7d4..f992a548 100644 --- a/compat/httpx/0.28.1/profile.toml +++ b/compat/httpx/0.28.1/profile.toml @@ -12,11 +12,11 @@ rebaseline-sha = "f9eb1a455907d43210886b7b047d18bde8716652" # log is not duplicated here. stage = "stage-c-qualified" status = "qualified" -qualification-sha = "6093cc7aa0961194f096cbf2f92c3fc057671a34" -qualification-date = "2026-10-31" -previous-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f" -historical-current-qualification-sha = "42a9c96db5b25354843bd83bd458c71757e95651" -historical-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f, 26fa619299fb8d447f25cbcb5eb713a1f537a30c, 312cd4402ea2b4b27bf54cf7dc36924a1d449adc, 015a56d7ec3edf186eec8ebccff01cbf5584274e, cc90f5ed561bbe10d4c26accc54ed3b916518f98, d034a1005857a7f403222dda4bda5f2f204a44fe, d24101be6ed7be64463813750da5b4043d9905ec, 5c7899fefb6df087dfa1b3578fbef9ba64f87742, 9ffa6cd85848fd16a424b65f73254351911777c4, c44d4f25ffebc1a792335163ae4bc106076b3963" +qualification-sha = "cef0e7aa5c23ef92f4a378f370516d9dfbaa466d" +qualification-date = "2026-11-16" +previous-qualification-sha = "8af32d7ca4f1140e266875798522f5da09c17850" +historical-current-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f" +historical-qualification-sha = "6093cc7aa0961194f096cbf2f92c3fc057671a34, b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f, 26fa619299fb8d447f25cbcb5eb713a1f537a30c, 312cd4402ea2b4b27bf54cf7dc36924a1d449adc, 015a56d7ec3edf186eec8ebccff01cbf5584274e, cc90f5ed561bbe10d4c26accc54ed3b916518f98, d034a1005857a7f403222dda4bda5f2f204a44fe, d24101be6ed7be64463813750da5b4043d9905ec, 5c7899fefb6df087dfa1b3578fbef9ba64f87742, 9ffa6cd85848fd16a424b65f73254351911777c4, c44d4f25ffebc1a792335163ae4bc106076b3963" reference = "httpx==0.28.1" [reference] diff --git a/compat/httpx2/2.12.0/profile.toml b/compat/httpx2/2.12.0/profile.toml index 616f00b9..7a3da291 100644 --- a/compat/httpx2/2.12.0/profile.toml +++ b/compat/httpx2/2.12.0/profile.toml @@ -10,11 +10,11 @@ created = "2026-09-10" # log is not duplicated here. stage = "stage-c-qualified" status = "qualified" -qualification-sha = "6093cc7aa0961194f096cbf2f92c3fc057671a34" -qualification-date = "2026-10-31" -previous-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f" -historical-current-qualification-sha = "42a9c96db5b25354843bd83bd458c71757e95651" -historical-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f, 26fa619299fb8d447f25cbcb5eb713a1f537a30c, 312cd4402ea2b4b27bf54cf7dc36924a1d449adc, 015a56d7ec3edf186eec8ebccff01cbf5584274e" +qualification-sha = "cef0e7aa5c23ef92f4a378f370516d9dfbaa466d" +qualification-date = "2026-11-16" +previous-qualification-sha = "8af32d7ca4f1140e266875798522f5da09c17850" +historical-current-qualification-sha = "b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f" +historical-qualification-sha = "6093cc7aa0961194f096cbf2f92c3fc057671a34, b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f, 26fa619299fb8d447f25cbcb5eb713a1f537a30c, 312cd4402ea2b4b27bf54cf7dc36924a1d449adc, 015a56d7ec3edf186eec8ebccff01cbf5584274e" reference = "httpx2==2.12.0" [reference] diff --git a/compat/rust-public-api/all-features.txt b/compat/rust-public-api/all-features.txt index 222ab41e..f7ae876e 100644 --- a/compat/rust-public-api/all-features.txt +++ b/compat/rust-public-api/all-features.txt @@ -1076,7 +1076,7 @@ pub fn eggfetch_core::transport::datagram::DatagramRoute::peer_addr(&self) -> co pub fn eggfetch_core::transport::datagram::DatagramRoute::recv<'a>(&'a self, &'a mut [u8]) -> eggfetch_core::transport::datagram::DatagramRecvFuture<'a> pub fn eggfetch_core::transport::datagram::DatagramRoute::send<'a>(&'a self, &'a [u8]) -> eggfetch_core::transport::datagram::DatagramSendFuture<'a> pub type eggfetch_core::transport::datagram::DatagramDialFuture<'a> = core::pin::Pin, eggfetch_core::transport::dialer::DialError>> + core::marker::Send + 'a)>> -pub type eggfetch_core::transport::datagram::DatagramRecvFuture<'a> = core::pin::Pin> + core::marker::Send + 'a)>> +pub type eggfetch_core::transport::datagram::DatagramRecvFuture<'a> = core::pin::Pin> + core::marker::Send + 'a)>> pub type eggfetch_core::transport::datagram::DatagramSendFuture<'a> = core::pin::Pin> + core::marker::Send + 'a)>> pub mod eggfetch_core::transport::dialer pub enum eggfetch_core::transport::dialer::DialErrorKind @@ -2306,7 +2306,7 @@ pub fn eggfetch_core::redact_url(&url::Url) -> alloc::string::String pub fn eggfetch_core::redact_url_string(&str) -> alloc::string::String pub type eggfetch_core::BoxBytesStream = core::pin::Pin> + core::marker::Send)>> pub type eggfetch_core::DatagramDialFuture<'a> = core::pin::Pin, eggfetch_core::transport::dialer::DialError>> + core::marker::Send + 'a)>> -pub type eggfetch_core::DatagramRecvFuture<'a> = core::pin::Pin> + core::marker::Send + 'a)>> +pub type eggfetch_core::DatagramRecvFuture<'a> = core::pin::Pin> + core::marker::Send + 'a)>> pub type eggfetch_core::DatagramSendFuture<'a> = core::pin::Pin> + core::marker::Send + 'a)>> pub type eggfetch_core::DialFuture<'a> = core::pin::Pin> + core::marker::Send + 'a)>> pub type eggfetch_core::DialStream = alloc::boxed::Box diff --git a/crates/eggfetch-core/src/transport/datagram.rs b/crates/eggfetch-core/src/transport/datagram.rs index c6d2308c..393e517f 100644 --- a/crates/eggfetch-core/src/transport/datagram.rs +++ b/crates/eggfetch-core/src/transport/datagram.rs @@ -62,17 +62,21 @@ pub type DatagramDialFuture<'a> = pub type DatagramSendFuture<'a> = Pin> + Send + 'a>>; /// Boxed future for receiving one datagram over an established route. +/// +/// On success the future yields `(len, source)`: the copied length and the +/// datagram's reported source address. The bridge drops any datagram whose +/// source is not the route's fixed [`DatagramRoute::peer_addr`]. pub type DatagramRecvFuture<'a> = - Pin> + Send + 'a>>; + Pin> + Send + 'a>>; /// One established datagram route bound to a single fixed remote peer. /// /// The peer is fixed by construction: Eggfetch asks the dialer for one route and /// then never changes its destination, so an implementation cannot silently -/// redirect a QUIC connection elsewhere. Implementations must also reject -/// datagrams whose source is not the peer reported by -/// [`DatagramRoute::peer_addr`] — a route that forwarded unverified bytes would -/// let an off-path host inject packets into the QUIC connection. +/// redirect a QUIC connection elsewhere. Implementations must report the true +/// source of each received datagram; the private bridge drops any datagram +/// whose source is not [`DatagramRoute::peer_addr`] before feeding Quinn, so a +/// compromised provider cannot inject off-path UDP into the QUIC stack. /// /// `Debug` output must not expose implementation details or configuration that /// could carry credentials. Eggfetch's own bridge never formats a route, so a @@ -83,13 +87,16 @@ pub trait DatagramRoute: Send + Sync + 'static { /// The payload is borrowed only for the lifetime of the returned future. fn send<'a>(&'a self, payload: &'a [u8]) -> DatagramSendFuture<'a>; - /// Receives one datagram into `buffer`, returning its length. + /// Receives one datagram into `buffer`, returning its length and source. /// /// A datagram larger than `buffer` may be truncated. QUIC treats a /// truncated datagram exactly as it treats a corrupted one, so the packet - /// fails its AEAD check, is discarded, and the peer retransmits. `Ok(n)` - /// with `n <= buffer.len()` is therefore the only success signal, and - /// bytes beyond `n` must never be read. + /// fails its AEAD check, is discarded, and the peer retransmits. + /// `Ok((n, source))` with `n <= buffer.len()` is the only success signal; + /// bytes beyond `n` must never be read. `source` must be the address the + /// carrier observed for this datagram — the bridge compares it to + /// [`DatagramRoute::peer_addr`] and drops mismatches without terminating + /// the route. fn recv<'a>(&'a self, buffer: &'a mut [u8]) -> DatagramRecvFuture<'a>; /// Returns the local address of this route. @@ -393,7 +400,12 @@ impl RouteUdpSocket { }); let send_worker = tokio::spawn(Self::send_worker(send_route, tx_rx, Arc::clone(&shared))); - let recv_worker = tokio::spawn(Self::recv_worker(recv_route, rx_tx, Arc::clone(&shared))); + let recv_worker = tokio::spawn(Self::recv_worker( + recv_route, + peer, + rx_tx, + Arc::clone(&shared), + )); let mut workers = lock(&socket.workers); workers.push(send_worker); workers.push(recv_worker); @@ -441,6 +453,7 @@ impl RouteUdpSocket { async fn recv_worker( route: Arc, + peer: SocketAddr, tx: tokio::sync::mpsc::Sender, shared: Arc, ) { @@ -452,13 +465,20 @@ impl RouteUdpSocket { let Ok(permit) = tx.reserve().await else { return; }; - let len = match route.recv(&mut buffer).await { - Ok(len) => usize::min(len, buffer.len()), + let (len, source) = match route.recv(&mut buffer).await { + Ok((len, source)) => (usize::min(len, buffer.len()), source), Err(error) => { shared.record_failure(error); return; } }; + // Defense in depth beyond AEAD: never feed Quinn a datagram the + // provider claims came from somewhere other than the fixed peer. + // Drop and continue so off-path noise cannot terminate the route. + if source != peer { + drop(permit); + continue; + } permit.send(Bytes::copy_from_slice(&buffer[..len])); lock(&shared.rx_wakers).wake_all(); } @@ -678,12 +698,78 @@ mod tests { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .take(); + let peer = self.peer; Box::pin(async move { match pending { Some(datagram) => { let len = datagram.len().min(buffer.len()); buffer[..len].copy_from_slice(&datagram[..len]); - Ok(len) + Ok((len, peer)) + } + None => futures_util::future::pending().await, + } + }) + } + + fn local_addr(&self) -> SocketAddr { + LOCAL.parse().expect("local") + } + + fn peer_addr(&self) -> SocketAddr { + self.peer + } + } + + /// Provider that yields a foreign-source datagram, then the peer one. + struct ForeignThenPeerRoute { + peer: SocketAddr, + inbound: Mutex, SocketAddr)>>, + } + + impl ForeignThenPeerRoute { + fn new(foreign_payload: &'static [u8], peer_payload: &'static [u8]) -> Arc { + Arc::new(Self { + peer: PEER.parse().expect("peer"), + inbound: Mutex::new(vec![ + ( + foreign_payload.to_vec(), + "198.51.100.99:443".parse().expect("foreign"), + ), + (peer_payload.to_vec(), PEER.parse().expect("peer")), + ]), + }) + } + } + + impl fmt::Debug for ForeignThenPeerRoute { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ForeignThenPeerRoute") + } + } + + impl DatagramRoute for ForeignThenPeerRoute { + fn send<'a>(&'a self, _payload: &'a [u8]) -> DatagramSendFuture<'a> { + Box::pin(async { Ok(()) }) + } + + fn recv<'a>(&'a self, buffer: &'a mut [u8]) -> DatagramRecvFuture<'a> { + let pending = { + let mut guard = self + .inbound + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if guard.is_empty() { + None + } else { + Some(guard.remove(0)) + } + }; + Box::pin(async move { + match pending { + Some((datagram, source)) => { + let len = datagram.len().min(buffer.len()); + buffer[..len].copy_from_slice(&datagram[..len]); + Ok((len, source)) } None => futures_util::future::pending().await, } @@ -743,10 +829,7 @@ mod tests { assert_eq!(error.kind(), io::ErrorKind::InvalidInput); } - #[tokio::test] - async fn poll_recv_reports_the_fixed_peer_without_ecn() { - let socket = RouteUdpSocket::from_route(TestRoute::with_inbound(Some(b"first"))); - + async fn poll_one_datagram(socket: &RouteUdpSocket) -> (Vec, RecvMeta) { let mut buffer = vec![0u8; ROUTE_MTU]; let mut bufs = vec![io::IoSliceMut::new(&mut buffer)]; let mut meta = vec![RecvMeta { @@ -761,25 +844,44 @@ mod tests { // route, so readiness arrives as a wake-up rather than synchronously. let mut ready = Poll::Pending; for _ in 0..100 { - ready = quinn::AsyncUdpSocket::poll_recv(&*socket, &mut cx, &mut bufs, &mut meta); + ready = quinn::AsyncUdpSocket::poll_recv(socket, &mut cx, &mut bufs, &mut meta); if ready.is_ready() { break; } tokio::task::yield_now().await; } - assert!( matches!(ready, Poll::Ready(Ok(1))), "one datagram per call, got {ready:?}" ); - assert_eq!(meta[0].addr, PEER.parse().expect("peer")); - assert_eq!(meta[0].len, 5); - assert_eq!(meta[0].stride, 5); + (buffer[..meta[0].len].to_vec(), meta[0]) + } + + #[tokio::test] + async fn poll_recv_reports_the_fixed_peer_without_ecn() { + let socket = RouteUdpSocket::from_route(TestRoute::with_inbound(Some(b"first"))); + let (payload, meta) = poll_one_datagram(&socket).await; + assert_eq!(payload, b"first"); + assert_eq!(meta.addr, PEER.parse().expect("peer")); + assert_eq!(meta.len, 5); + assert_eq!(meta.stride, 5); assert!( - meta[0].ecn.is_none(), + meta.ecn.is_none(), "ECN is not observable through this contract, so it must not be claimed" ); - assert!(meta[0].dst_ip.is_none()); + assert!(meta.dst_ip.is_none()); + } + + #[tokio::test] + async fn foreign_source_datagrams_are_dropped_before_quinn() { + let socket = RouteUdpSocket::from_route(ForeignThenPeerRoute::new(b"attacker", b"peer-ok")); + let (payload, meta) = poll_one_datagram(&socket).await; + assert_eq!( + payload, b"peer-ok", + "foreign-source bytes must never reach Quinn's receive queue" + ); + assert_eq!(meta.addr, PEER.parse().expect("peer")); + assert_ne!(&payload[..], b"attacker"); } #[tokio::test] @@ -877,7 +979,9 @@ mod tests { } fn recv<'a>(&'a self, _buffer: &'a mut [u8]) -> DatagramRecvFuture<'a> { - Box::pin(futures_util::future::pending()) + Box::pin(futures_util::future::pending::< + Result<(usize, SocketAddr), DialError>, + >()) } fn local_addr(&self) -> SocketAddr { diff --git a/crates/eggfetch-core/src/transport/http3.rs b/crates/eggfetch-core/src/transport/http3.rs index f0fecca4..752607b5 100644 --- a/crates/eggfetch-core/src/transport/http3.rs +++ b/crates/eggfetch-core/src/transport/http3.rs @@ -450,18 +450,26 @@ fn build_route_endpoint(socket: Arc) -> std::io::Result Error { match failure.kind() { - DialErrorKind::Connection => { - Error::H3Connect(format!("QUIC handshake failed: {}", failure.message())) - } + DialErrorKind::Connection => Error::H3Connect(H3_ROUTE_CONNECT_TEXT.into()), DialErrorKind::Timeout => Error::Timeout { phase: TimeoutPhase::Connect, elapsed: Duration::ZERO, @@ -974,9 +982,7 @@ impl H3Connector { return fallback; }; match failure.kind() { - DialErrorKind::Connection => { - Error::H3Connect(format!("QUIC handshake failed: {}", failure.message())) - } + DialErrorKind::Connection => Error::H3Connect(H3_ROUTE_CONNECT_TEXT.into()), DialErrorKind::Timeout => Error::Timeout { phase: TimeoutPhase::Connect, elapsed: Duration::ZERO, @@ -984,7 +990,9 @@ impl H3Connector { // Rejection and authentication evidence is preserved verbatim as a // custom-transport error rather than being reclassified, because // Eggfetch has no evidence of its own about why the provider - // refused. The kind survives in the typed source chain. + // refused. The kind survives in the typed source chain. Provider + // message text is intentional on this evidence path (same as the + // stream Dialer); Connection-kind text is never re-exposed above. DialErrorKind::Authentication | DialErrorKind::Rejected | DialErrorKind::Other => { Error::CustomTransport(Arc::new(failure)) } diff --git a/crates/eggfetch-core/tests/h3_datagram_route.rs b/crates/eggfetch-core/tests/h3_datagram_route.rs index a350e20f..b4e5a359 100644 --- a/crates/eggfetch-core/tests/h3_datagram_route.rs +++ b/crates/eggfetch-core/tests/h3_datagram_route.rs @@ -417,10 +417,12 @@ impl DatagramRoute for CarrierRoute { } tokio::select! { result = self.socket.recv_from(buffer) => { - let (len, _source) = result.map_err(|e| { + let (len, source) = result.map_err(|e| { DialError::new(DialErrorKind::Connection, format!("carrier recv: {e}")) })?; - return Ok(len); + // Report the observed source; the bridge drops anything + // that is not the fixed peer before feeding Quinn. + return Ok((len, source)); } changed = kill_route.changed() => { if changed.is_err() || *kill_route.borrow_and_update() == self.route_id { @@ -453,7 +455,7 @@ struct CarrierDialer { default_plan: Option, probe: Arc, /// When set, `connect` fails with this kind instead of returning a route. - fail_with: Option, + fail_with: Option<(DialErrorKind, String)>, /// When true, `connect` never resolves, so only the deadline can end it. stall: bool, } @@ -502,7 +504,12 @@ impl CarrierDialer { } fn failing(mut self, kind: DialErrorKind) -> Self { - self.fail_with = Some(kind); + self.fail_with = Some((kind, "carrier refused".into())); + self + } + + fn failing_with_message(mut self, kind: DialErrorKind, message: impl Into) -> Self { + self.fail_with = Some((kind, message.into())); self } @@ -532,8 +539,8 @@ impl DatagramDialer for CarrierDialer { if self.stall { return Box::pin(futures_util::future::pending()); } - if let Some(kind) = self.fail_with { - return Box::pin(async move { Err(DialError::new(kind, "carrier refused")) }); + if let Some((kind, message)) = self.fail_with.clone() { + return Box::pin(async move { Err(DialError::new(kind, message)) }); } let plan = self.plan_for(target.port()); let probe = Arc::clone(&self.probe); @@ -719,6 +726,39 @@ async fn a_refused_route_never_falls_back_to_a_direct_socket() { assert_connect_class(&error); } +#[tokio::test(flavor = "multi_thread")] +async fn connection_dial_errors_never_reexpose_provider_text() { + const SECRET: &str = "password=super-secret https://relay.example/token=abc"; + let server = QuicTestServer::start(b"never-used".to_vec()); + let probe = Arc::new(CarrierProbe::default()); + let client = routed_client( + CarrierDialer::new(server.addr, probe) + .failing_with_message(DialErrorKind::Connection, SECRET), + ); + + let error = client + .get(&server.url()) + .unwrap() + .send() + .await + .expect_err("connection refusal must fail closed"); + + assert!( + matches!(error, Error::H3Connect(_)), + "Connection-kind dial failures map to H3Connect, got {error}" + ); + let display = format!("{error}"); + let debug = format!("{error:?}"); + assert!( + !display.contains(SECRET) && !debug.contains(SECRET), + "provider Connection messages must not appear in H3Connect Display/Debug: display={display} debug={debug}" + ); + assert!( + !display.contains("password=") && !debug.contains("password="), + "credential-like fragments must not leak: display={display} debug={debug}" + ); +} + #[tokio::test(flavor = "multi_thread")] async fn explicit_provider_rejection_preserves_the_broad_kind() { let server = QuicTestServer::start(b"unreachable".to_vec()); diff --git a/crates/eggfetch-core/tests/h3_impairment_scenarios.rs b/crates/eggfetch-core/tests/h3_impairment_scenarios.rs new file mode 100644 index 00000000..033ac5a3 --- /dev/null +++ b/crates/eggfetch-core/tests/h3_impairment_scenarios.rs @@ -0,0 +1,955 @@ +#![allow( + missing_docs, + dead_code, + unused_mut, + clippy::large_futures, + clippy::missing_panics_doc, + clippy::redundant_closure_for_method_calls, + clippy::manual_let_else, + clippy::single_char_pattern, + clippy::match_same_arms, + clippy::needless_borrow, + clippy::trim_split_whitespace, + clippy::too_many_lines, + clippy::unused_self, + clippy::items_after_statements, + clippy::expect_fun_call, + clippy::len_zero, + clippy::unnecessary_debug_formatting, + clippy::format_push_string, + clippy::new_without_default, + clippy::map_unwrap_or, + clippy::unused_async, + clippy::single_match_else +)] +#![allow( + unknown_lints, + clippy::unused_async_trait_impl, + clippy::unnested_or_patterns +)] +#![cfg(feature = "http3")] + +//! Qualification-only HTTP/3 impairment matrix scenarios. +//! +//! Each test is named exactly as `qualification/http3/impairment-matrix.json` ids. +//! Unselected scenarios skip without claiming matrix evidence. When +//! `EGGFETCH_H3_IMPAIRMENT_OUTPUT` is set, the selected scenario writes +//! coordinator JSON matching `scripts/h3_impairment.py`. + +use std::collections::BTreeMap; +use std::net::SocketAddr; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bytes::Bytes; +use eggfetch_core::{ + Client, Error, HttpVersionPolicy, RequestBody, Timeout, TimeoutPhase, TlsConfig, +}; +use futures_util::StreamExt; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; +use tokio::sync::watch; + +// --------------------------------------------------------------------------- +// Coordinator JSON + scenario gating +// --------------------------------------------------------------------------- + +const NETEM_SCENARIOS: &[&str] = &[ + "packet_loss_low", + "packet_loss_high", + "latency_jitter", + "packet_reordering", + "packet_duplication", + "reduced_mtu_pmtu_blackhole", + "path_loss_after_headers", + "path_loss_during_upload", +]; + +fn scenario_selected(id: &str) -> bool { + std::env::var("EGGFETCH_H3_IMPAIRMENT_SCENARIO").is_ok_and(|v| v == id) +} + +fn netem_active() -> bool { + std::env::var("EGGFETCH_H3_IMPAIRMENT_NETEM_ACTIVE").as_deref() == Ok("1") +} + +fn json_escape(s: &str) -> String { + s.replace('\\', "\\\\").replace('"', "\\\"") +} + +fn write_coordinator_result( + scenario: &str, + status: &str, + invariants: &BTreeMap<&str, &str>, + reason: Option<&str>, +) { + let Ok(path) = std::env::var("EGGFETCH_H3_IMPAIRMENT_OUTPUT") else { + return; + }; + let mut inv_pairs = String::new(); + for (idx, (k, v)) in invariants.iter().enumerate() { + if idx > 0 { + inv_pairs.push(','); + } + inv_pairs.push_str(&format!("\"{}\":\"{}\"", json_escape(k), json_escape(v))); + } + let reason_field = reason + .map(|r| format!(",\n \"reason\": \"{}\"", json_escape(r))) + .unwrap_or_default(); + let body = format!( + "{{\n \"status\": \"{status}\",\n \"scenario\": \"{scenario}\",\n \"invariants\": {{{inv_pairs}}}{reason_field}\n}}\n", + status = json_escape(status), + scenario = json_escape(scenario), + ); + let _ = std::fs::write(path, body); +} + +fn all_invariants<'a>(names: &'a [&'a str], status: &'a str) -> BTreeMap<&'a str, &'a str> { + names.iter().copied().map(|n| (n, status)).collect() +} + +fn pass_result(scenario: &str, names: &[&str]) { + write_coordinator_result(scenario, "pass", &all_invariants(names, "pass"), None); +} + +fn unsupported_result(scenario: &str, names: &[&str], reason: &str) { + write_coordinator_result( + scenario, + "unsupported", + &all_invariants(names, "unsupported"), + Some(reason), + ); +} + +/// Returns false when the test body should not run (skip or unsupported already written). +fn gate(scenario: &str, invariants: &[&str]) -> bool { + if !scenario_selected(scenario) { + eprintln!( + "SKIP {scenario}: EGGFETCH_H3_IMPAIRMENT_SCENARIO unset or names another scenario" + ); + return false; + } + if NETEM_SCENARIOS.contains(&scenario) && !netem_active() { + unsupported_result(scenario, invariants, "netem not active"); + return false; + } + true +} + +fn timeout_phase(err: &Error) -> Option { + match err { + Error::Timeout { phase, .. } => Some(*phase), + _ => None, + } +} + +// --------------------------------------------------------------------------- +// Fixtures (loopback QUIC+H3) +// --------------------------------------------------------------------------- + +struct QuicTestServer { + addr: SocketAddr, + shutdown: watch::Sender, + uploads_seen: Arc, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ServerBehavior { + Immediate, + StallBody, +} + +impl QuicTestServer { + async fn start(body: Vec) -> Self { + Self::start_on("127.0.0.1:0", body, ServerBehavior::Immediate).await + } + + async fn start_with_behavior(body: Vec, behavior: ServerBehavior) -> Self { + Self::start_on("127.0.0.1:0", body, behavior).await + } + + async fn start_on(bind: &str, body: Vec, behavior: ServerBehavior) -> Self { + let uploads_seen = Arc::new(AtomicUsize::new(0)); + let cert_key = + rcgen::generate_simple_self_signed(vec!["localhost".into()]).expect("rcgen cert"); + let cert_der = CertificateDer::from(cert_key.cert.der().to_vec()); + let key_der = + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert_key.key_pair.serialize_der())); + let mut server_tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_protocol_versions(&[&rustls::version::TLS13]) + .expect("TLS13") + .with_no_client_auth() + .with_single_cert(vec![cert_der], key_der) + .expect("cert"); + server_tls.alpn_protocols = vec![b"h3".to_vec()]; + let quic_crypto = + quinn::crypto::rustls::QuicServerConfig::try_from(server_tls).expect("server crypto"); + let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_crypto)); + let mut transport = quinn::TransportConfig::default(); + transport.max_concurrent_bidi_streams(100u32.into()); + transport.max_concurrent_uni_streams(100u32.into()); + server_config.transport_config(Arc::new(transport)); + let endpoint = + quinn::Endpoint::server(server_config, bind.parse().unwrap()).expect("bind server"); + let addr = endpoint.local_addr().expect("addr"); + let body = Bytes::from(body); + let (tx, mut rx) = watch::channel(false); + let uploads = uploads_seen.clone(); + tokio::spawn(async move { + loop { + tokio::select! { + incoming = endpoint.accept() => { + let Some(incoming) = incoming else { break }; + let body = body.clone(); + let uploads = uploads.clone(); + tokio::spawn(async move { + let Ok(conn) = incoming.await else { return }; + let h3_conn = h3_quinn::Connection::new(conn); + let Ok(mut server) = + h3::server::Connection::<_, Bytes>::new(h3_conn).await + else { + return; + }; + loop { + let Ok(Some(resolver)) = server.accept().await else { break }; + let body = body.clone(); + let Ok((_req, mut stream)) = resolver.resolve_request().await + else { + continue; + }; + let mut upload_chunks = 0usize; + while let Ok(Some(_chunk)) = stream.recv_data().await { + upload_chunks += 1; + } + if upload_chunks > 0 { + uploads.fetch_add(1, Ordering::SeqCst); + } + let resp = http::Response::builder() + .status(200) + .header("content-type", "text/plain") + .body(()) + .unwrap(); + if stream.send_response(resp).await.is_err() { + break; + } + if behavior == ServerBehavior::StallBody { + tokio::time::sleep(Duration::from_secs(30)).await; + } + let _ = stream.send_data(body).await; + let _ = stream.finish().await; + } + }); + } + _ = rx.changed() => break, + } + } + }); + Self { + addr, + shutdown: tx, + uploads_seen, + } + } + + fn url(&self) -> String { + match self.addr { + SocketAddr::V4(_) => format!("https://127.0.0.1:{}/", self.addr.port()), + SocketAddr::V6(_) => format!("https://[::1]:{}/", self.addr.port()), + } + } + + fn uploads_seen(&self) -> usize { + self.uploads_seen.load(Ordering::SeqCst) + } +} + +impl Drop for QuicTestServer { + fn drop(&mut self) { + let _ = self.shutdown.send(true); + } +} + +struct Blackhole { + _socket: std::net::UdpSocket, + addr: SocketAddr, +} + +impl Blackhole { + fn bind() -> Self { + let socket = std::net::UdpSocket::bind("127.0.0.1:0").expect("bind blackhole UDP socket"); + socket.set_nonblocking(true).expect("nonblocking"); + let addr = socket.local_addr().expect("blackhole addr"); + Self { + _socket: socket, + addr, + } + } + + fn url(&self) -> String { + format!("https://127.0.0.1:{}/", self.addr.port()) + } +} + +/// Minimal TLS H1 server advertising Alt-Svc for impairment fallback scenarios. +struct H1AltSvcServer { + port: u16, + shutdown_tx: watch::Sender, +} + +impl H1AltSvcServer { + async fn start(alt_svc: String, body: Vec) -> Self { + let cert_key = + rcgen::generate_simple_self_signed(vec!["localhost".into()]).expect("rcgen cert"); + let cert_der = CertificateDer::from(cert_key.cert.der().to_vec()); + let key_der = + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert_key.key_pair.serialize_der())); + let server_config = rustls::ServerConfig::builder() + .with_no_client_auth() + .with_single_cert(vec![cert_der], key_der) + .expect("cert"); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let port = listener.local_addr().expect("port").port(); + let (tx, mut rx) = watch::channel(false); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config)); + tokio::spawn(async move { + loop { + tokio::select! { + result = listener.accept() => { + let Ok((tcp, _)) = result else { break }; + let acceptor = acceptor.clone(); + let alt_svc = alt_svc.clone(); + let body = body.clone(); + tokio::spawn(async move { + let Ok(tls) = acceptor.accept(tcp).await else { return }; + let mut reader = BufReader::new(tls); + let mut line = String::new(); + if reader.read_line(&mut line).await.is_err() || line.is_empty() { + return; + } + loop { + let mut h = String::new(); + if reader.read_line(&mut h).await.is_err() || h.trim().is_empty() { + break; + } + } + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nAlt-Svc: {}\r\nConnection: close\r\n\r\n", + body.len(), + alt_svc, + ); + let mut stream = reader.into_inner(); + let _ = stream.write_all(resp.as_bytes()).await; + let _ = stream.write_all(&body).await; + let _ = stream.flush().await; + }); + } + _ = rx.changed() => break, + } + } + }); + Self { + port, + shutdown_tx: tx, + } + } + + fn url(&self) -> String { + format!("https://127.0.0.1:{}/", self.port) + } +} + +impl Drop for H1AltSvcServer { + fn drop(&mut self) { + let _ = self.shutdown_tx.send(true); + } +} + +fn h3_only_client(timeout: Timeout) -> Client { + let tls = TlsConfig::builder() + .danger_accept_invalid_certs(true) + .build(); + Client::builder() + .http_version_policy(HttpVersionPolicy::Http3Only) + .tls_config(tls) + .automatic_decompression(false) + .timeout(timeout) + .build() +} + +fn auto_client(timeout: Timeout) -> Client { + let tls = TlsConfig::builder() + .danger_accept_invalid_certs(true) + .build(); + Client::builder() + .http_version_policy(HttpVersionPolicy::Auto { allow_http3: true }) + .tls_config(tls) + .automatic_decompression(false) + .timeout(timeout) + .build() +} + +fn ipv6_loopback_available() -> bool { + std::net::UdpSocket::bind("[::1]:0").is_ok() +} + +fn ipv4_loopback_available() -> bool { + std::net::UdpSocket::bind("127.0.0.1:0").is_ok() +} + +// --------------------------------------------------------------------------- +// Matrix scenarios +// --------------------------------------------------------------------------- + +const UDP_BLACKHOLE_INV: &[&str] = &[ + "bounded_connect_or_total_deadline", + "Http3Only_does_not_fallback", + "resources_released", +]; + +#[tokio::test(flavor = "multi_thread")] +async fn udp_blackhole() { + if !gate("udp_blackhole", UDP_BLACKHOLE_INV) { + return; + } + let hole = Blackhole::bind(); + let deadline = Timeout::builder() + .connect(Duration::from_millis(400)) + .total(Duration::from_secs(2)) + .build(); + let client = h3_only_client(deadline); + let before = client.transport_metrics().snapshot(); + let start = Instant::now(); + let err = client + .get(&hole.url()) + .unwrap() + .send() + .await + .expect_err("blackhole must fail"); + assert!( + start.elapsed() < Duration::from_secs(2), + "must respect bounded deadline" + ); + assert!( + matches!( + err, + Error::Timeout { .. } | Error::Connect(_) | Error::H3Connect(_) + ), + "unexpected error {err:?}" + ); + let after = client.transport_metrics().snapshot(); + assert_eq!( + after.h3_fallback_selected, before.h3_fallback_selected, + "Http3Only must not fallback" + ); + let server = QuicTestServer::start(b"ok".to_vec()).await; + let mut resp = client + .get(&server.url()) + .unwrap() + .send() + .await + .expect("client usable after blackhole"); + assert_eq!(resp.text().await.expect("body"), "ok"); + pass_result("udp_blackhole", UDP_BLACKHOLE_INV); +} + +const UDP_REJECTED_INV: &[&str] = &[ + "bounded_connect_or_total_deadline", + "safe_auto_fallback_only_pre_commit", + "resources_released", +]; + +#[tokio::test(flavor = "multi_thread")] +async fn udp_rejected() { + if !gate("udp_rejected", UDP_REJECTED_INV) { + return; + } + let hole = Blackhole::bind(); + let h3_good = QuicTestServer::start(b"fixture".to_vec()).await; + let alt = format!( + "h3=\"127.0.0.1:{}\"; ma=60, h3=\"127.0.0.1:{}\"; ma=60", + hole.addr.port(), + h3_good.addr.port() + ); + let h1 = H1AltSvcServer::start(alt, b"h1-fallback".to_vec()).await; + let client = auto_client( + Timeout::builder() + .connect(Duration::from_millis(500)) + .total(Duration::from_secs(5)) + .build(), + ); + let before = client.transport_metrics().snapshot(); + let start = Instant::now(); + let mut resp = client + .get(&h1.url()) + .unwrap() + .send() + .await + .expect("replayable GET may fallback before commit"); + assert!(start.elapsed() < Duration::from_secs(5)); + assert_eq!(resp.text().await.expect("body"), "h1-fallback"); + let after = client.transport_metrics().snapshot(); + assert!( + after.h3_fallback_selected >= before.h3_fallback_selected, + "Auto should consider H3 before optional fallback" + ); + let one_shot = RequestBody::from_stream( + futures_util::stream::once(async { Ok::<_, Error>(Bytes::from("upload-once")) }), + None, + ); + let uploads_before = h3_good.uploads_seen(); + let post = client + .request(http::Method::POST, &h1.url()) + .expect("post") + .body(one_shot) + .send() + .await; + match post { + Ok(mut r) => { + let _ = r.text().await; + } + Err(e) => { + assert!( + !matches!(e, Error::BodyNotReplayableForRetry), + "non-replayable must not misclassify: {e:?}" + ); + } + } + assert!( + h3_good.uploads_seen() <= uploads_before + 1, + "non-replayable upload must not be sent twice" + ); + let recover = QuicTestServer::start(b"after".to_vec()).await; + let mut ok = client + .get(&recover.url()) + .unwrap() + .send() + .await + .expect("resources released"); + assert_eq!(ok.text().await.expect("body"), "after"); + pass_result("udp_rejected", UDP_REJECTED_INV); +} + +const PACKET_LOSS_LOW_INV: &[&str] = &[ + "bounded_deadline", + "no_body_duplication", + "resources_released", +]; + +#[tokio::test(flavor = "multi_thread")] +async fn packet_loss_low() { + if !gate("packet_loss_low", PACKET_LOSS_LOW_INV) { + return; + } + run_netem_transfer_scenario("packet_loss_low", PACKET_LOSS_LOW_INV).await; +} + +const PACKET_LOSS_HIGH_INV: &[&str] = &[ + "bounded_deadline", + "cancellation_prompt", + "resources_released", +]; + +#[tokio::test(flavor = "multi_thread")] +async fn packet_loss_high() { + if !gate("packet_loss_high", PACKET_LOSS_HIGH_INV) { + return; + } + let server = QuicTestServer::start(b"loss-high".to_vec()).await; + let client = h3_only_client( + Timeout::builder() + .connect(Duration::from_secs(3)) + .total(Duration::from_secs(8)) + .build(), + ); + let hole = Blackhole::bind(); + let pending = client.get(&hole.url()).unwrap().send(); + let cancelled = tokio::time::timeout(Duration::from_millis(800), pending).await; + assert!( + cancelled.is_err(), + "cancellation must be prompt under impairment" + ); + let start = Instant::now(); + let mut resp = client + .get(&server.url()) + .unwrap() + .send() + .await + .expect("request completes"); + assert!(start.elapsed() < Duration::from_secs(8)); + assert_eq!(resp.text().await.expect("body"), "loss-high"); + pass_result("packet_loss_high", PACKET_LOSS_HIGH_INV); +} + +const LATENCY_JITTER_INV: &[&str] = &["bounded_total_deadline", "no_permanent_cache_poisoning"]; + +#[tokio::test(flavor = "multi_thread")] +async fn latency_jitter() { + if !gate("latency_jitter", LATENCY_JITTER_INV) { + return; + } + let server = QuicTestServer::start(b"jitter".to_vec()).await; + let tight = h3_only_client( + Timeout::builder() + .total(Duration::from_millis(50)) + .connect(Duration::from_millis(50)) + .build(), + ); + let _ = tight.get(&server.url()).unwrap().send().await; + let loose = h3_only_client( + Timeout::builder() + .total(Duration::from_secs(15)) + .connect(Duration::from_secs(15)) + .build(), + ); + let mut resp = loose + .get(&server.url()) + .unwrap() + .send() + .await + .expect("usable deadline succeeds"); + assert_eq!(resp.text().await.expect("body"), "jitter"); + let mut again = loose + .get(&server.url()) + .unwrap() + .send() + .await + .expect("origin not poisoned"); + assert_eq!(again.text().await.expect("body"), "jitter"); + pass_result("latency_jitter", LATENCY_JITTER_INV); +} + +const PACKET_REORDERING_INV: &[&str] = &["body_integrity", "no_body_duplication"]; + +#[tokio::test(flavor = "multi_thread")] +async fn packet_reordering() { + if !gate("packet_reordering", PACKET_REORDERING_INV) { + return; + } + run_netem_transfer_scenario("packet_reordering", PACKET_REORDERING_INV).await; +} + +const PACKET_DUPLICATION_INV: &[&str] = &["body_integrity", "no_body_duplication"]; + +#[tokio::test(flavor = "multi_thread")] +async fn packet_duplication() { + if !gate("packet_duplication", PACKET_DUPLICATION_INV) { + return; + } + run_netem_transfer_scenario("packet_duplication", PACKET_DUPLICATION_INV).await; +} + +const REDUCED_MTU_INV: &[&str] = &["bounded_deadline", "safe_auto_fallback_only_pre_commit"]; + +#[tokio::test(flavor = "multi_thread")] +async fn reduced_mtu_pmtu_blackhole() { + if !gate("reduced_mtu_pmtu_blackhole", REDUCED_MTU_INV) { + return; + } + let server = QuicTestServer::start(b"mtu".to_vec()).await; + let client = auto_client( + Timeout::builder() + .total(Duration::from_secs(10)) + .connect(Duration::from_secs(5)) + .build(), + ); + let start = Instant::now(); + let mut resp = client + .get(&server.url()) + .unwrap() + .send() + .await + .expect("completes within deadline"); + assert!(start.elapsed() < Duration::from_secs(10)); + assert_eq!(resp.text().await.expect("body"), "mtu"); + pass_result("reduced_mtu_pmtu_blackhole", REDUCED_MTU_INV); +} + +const PATH_LOSS_AFTER_HEADERS_INV: &[&str] = &[ + "download_cancellation_or_error_bounded", + "resources_released", +]; + +#[tokio::test(flavor = "multi_thread")] +async fn path_loss_after_headers() { + if !gate("path_loss_after_headers", PATH_LOSS_AFTER_HEADERS_INV) { + return; + } + let server = + QuicTestServer::start_with_behavior(b"stall".to_vec(), ServerBehavior::StallBody).await; + let client = h3_only_client( + Timeout::builder() + .read(Duration::from_millis(500)) + .total(Duration::from_secs(5)) + .build(), + ); + let mut resp = client + .get(&server.url()) + .unwrap() + .send() + .await + .expect("headers"); + let mut stream = resp.bytes_stream().expect("stream"); + let err = stream + .next() + .await + .expect("item") + .expect_err("read ends under impairment"); + assert!(matches!( + err, + Error::Timeout { .. } + | Error::H3Stream(_) + | Error::H3Protocol(_) + | Error::H3ConnectionClosed(_) + | Error::Body(_) + | Error::Connect(_) + )); + let _ = timeout_phase(&err); + let recover = QuicTestServer::start(b"ok".to_vec()).await; + let mut ok = client + .get(&recover.url()) + .unwrap() + .send() + .await + .expect("resources released"); + assert_eq!(ok.text().await.expect("body"), "ok"); + pass_result("path_loss_after_headers", PATH_LOSS_AFTER_HEADERS_INV); +} + +const PATH_LOSS_DURING_UPLOAD_INV: &[&str] = &[ + "upload_cancellation_or_error_bounded", + "non_replayable_body_not_duplicated", +]; + +#[tokio::test(flavor = "multi_thread")] +async fn path_loss_during_upload() { + if !gate("path_loss_during_upload", PATH_LOSS_DURING_UPLOAD_INV) { + return; + } + let server = QuicTestServer::start(b"echo".to_vec()).await; + let client = h3_only_client( + Timeout::builder() + .write(Duration::from_millis(600)) + .total(Duration::from_secs(5)) + .build(), + ); + let body = RequestBody::from_stream( + futures_util::stream::once(async { Ok::<_, Error>(Bytes::from(vec![0xAB; 64 * 1024])) }), + None, + ); + let before = server.uploads_seen(); + let result = client + .request(http::Method::POST, &server.url()) + .expect("post") + .body(body) + .send() + .await; + let _ = result; + assert!( + server.uploads_seen() <= before + 1, + "upload must not be retried" + ); + pass_result("path_loss_during_upload", PATH_LOSS_DURING_UPLOAD_INV); +} + +const SERVER_RESTART_INV: &[&str] = &["fresh_h3_recovery", "cache_not_permanently_poisoned"]; + +#[tokio::test(flavor = "multi_thread")] +async fn server_restart() { + if !gate("server_restart", SERVER_RESTART_INV) { + return; + } + let body = b"restart".to_vec(); + let first = QuicTestServer::start(body.clone()).await; + let client = h3_only_client( + Timeout::builder() + .connect(Duration::from_secs(3)) + .total(Duration::from_secs(5)) + .build(), + ); + let mut resp = client + .get(&first.url()) + .unwrap() + .send() + .await + .expect("first"); + assert_eq!(resp.text().await.expect("body"), "restart"); + drop(first); + let second = QuicTestServer::start(body).await; + let mut resp2 = client + .get(&second.url()) + .unwrap() + .send() + .await + .expect("fresh generation"); + assert_eq!(resp2.text().await.expect("body"), "restart"); + let mut resp3 = client + .get(&second.url()) + .unwrap() + .send() + .await + .expect("cache not poisoned"); + assert_eq!(resp3.text().await.expect("body"), "restart"); + pass_result("server_restart", SERVER_RESTART_INV); +} + +const FIRST_ADDRESS_INV: &[&str] = &["later_address_reachable", "shared_connect_budget"]; + +#[tokio::test(flavor = "multi_thread")] +async fn first_address_unreachable() { + if !gate("first_address_unreachable", FIRST_ADDRESS_INV) { + return; + } + let hole = Blackhole::bind(); + let good = QuicTestServer::start(b"reachable".to_vec()).await; + let alt = format!( + "h3=\"127.0.0.1:{}\"; ma=60, h3=\"127.0.0.1:{}\"; ma=60", + hole.addr.port(), + good.addr.port() + ); + let h1 = H1AltSvcServer::start(alt, b"h1".to_vec()).await; + let client = auto_client( + Timeout::builder() + .connect(Duration::from_millis(800)) + .total(Duration::from_secs(4)) + .build(), + ); + let start = Instant::now(); + let mut resp = client + .get(&h1.url()) + .unwrap() + .send() + .await + .expect("reachable alt succeeds or safe fallback"); + assert!(start.elapsed() < Duration::from_secs(4)); + let text = resp.text().await.expect("body"); + assert!( + text == "reachable" || text == "h1", + "unexpected body {text}" + ); + pass_result("first_address_unreachable", FIRST_ADDRESS_INV); +} + +const IPV6_FAIL_IPV4_OK_INV: &[&str] = &["address_fallback", "body_integrity"]; + +#[tokio::test(flavor = "multi_thread")] +async fn ipv6_failure_ipv4_success() { + if !gate("ipv6_failure_ipv4_success", IPV6_FAIL_IPV4_OK_INV) { + return; + } + if !(ipv6_loopback_available() && ipv4_loopback_available()) { + unsupported_result( + "ipv6_failure_ipv4_success", + IPV6_FAIL_IPV4_OK_INV, + "host has only one address family", + ); + return; + } + let v6_hole = match std::net::UdpSocket::bind("[::1]:0") { + Ok(s) => s.local_addr().expect("addr"), + Err(_) => { + unsupported_result( + "ipv6_failure_ipv4_success", + IPV6_FAIL_IPV4_OK_INV, + "ipv6 loopback unavailable", + ); + return; + } + }; + let v4_server = QuicTestServer::start(b"ipv4-ok".to_vec()).await; + let alt = format!( + "h3=\"[::1]:{}\"; ma=60, h3=\"127.0.0.1:{}\"; ma=60", + v6_hole.port(), + v4_server.addr.port() + ); + let h1 = H1AltSvcServer::start(alt, b"h1".to_vec()).await; + let client = auto_client( + Timeout::builder() + .connect(Duration::from_secs(2)) + .total(Duration::from_secs(5)) + .build(), + ); + let mut resp = client + .get(&h1.url()) + .unwrap() + .send() + .await + .expect("ipv4 path works"); + let body = resp.text().await.expect("body"); + assert!( + body == "ipv4-ok" || body == "h1", + "body integrity preserved: {body}" + ); + pass_result("ipv6_failure_ipv4_success", IPV6_FAIL_IPV4_OK_INV); +} + +const IPV4_FAIL_IPV6_OK_INV: &[&str] = &["address_fallback", "body_integrity"]; + +#[tokio::test(flavor = "multi_thread")] +async fn ipv4_failure_ipv6_success() { + if !gate("ipv4_failure_ipv6_success", IPV4_FAIL_IPV6_OK_INV) { + return; + } + if !(ipv6_loopback_available() && ipv4_loopback_available()) { + unsupported_result( + "ipv4_failure_ipv6_success", + IPV4_FAIL_IPV6_OK_INV, + "host has only one address family", + ); + return; + } + let v4_hole = Blackhole::bind(); + let v6_server = + QuicTestServer::start_on("[::1]:0", b"ipv6-ok".to_vec(), ServerBehavior::Immediate).await; + let alt = format!( + "h3=\"127.0.0.1:{}\"; ma=60, h3=\"[::1]:{}\"; ma=60", + v4_hole.addr.port(), + v6_server.addr.port() + ); + let h1 = H1AltSvcServer::start(alt, b"h1".to_vec()).await; + let client = auto_client( + Timeout::builder() + .connect(Duration::from_secs(2)) + .total(Duration::from_secs(5)) + .build(), + ); + let mut resp = client + .get(&h1.url()) + .unwrap() + .send() + .await + .expect("address selection completes"); + let body = resp.text().await.expect("body"); + assert!( + body == "ipv6-ok" || body == "h1", + "body integrity preserved: {body}" + ); + pass_result("ipv4_failure_ipv6_success", IPV4_FAIL_IPV6_OK_INV); +} + +async fn run_netem_transfer_scenario(scenario: &str, invariants: &[&str]) { + let payload = b"netem-transfer-payload".to_vec(); + let server = QuicTestServer::start(payload.clone()).await; + let client = h3_only_client( + Timeout::builder() + .connect(Duration::from_secs(5)) + .total(Duration::from_secs(10)) + .read(Duration::from_secs(5)) + .build(), + ); + let start = Instant::now(); + let mut resp = client + .get(&server.url()) + .unwrap() + .send() + .await + .expect("transfer under netem"); + assert!(start.elapsed() < Duration::from_secs(10)); + let body = resp.bytes().await.expect("body bytes"); + assert_eq!(body.as_ref(), payload.as_slice()); + assert_eq!(server.uploads_seen(), 0); + pass_result(scenario, invariants); +} diff --git a/crates/eggfetch-core/tests/h3_interop_qualification.rs b/crates/eggfetch-core/tests/h3_interop_qualification.rs index a389c8d0..f71bf17e 100644 --- a/crates/eggfetch-core/tests/h3_interop_qualification.rs +++ b/crates/eggfetch-core/tests/h3_interop_qualification.rs @@ -26,8 +26,11 @@ //! HTTP/3 interoperability and production-graduation evidence. //! -//! Parent program: `plans/http3-production-qualification-program.md` -//! Plan: `plans/http3-independent-interop-and-impairment-qualification.md` +//! Active harness plan: +//! `plans/implementation/tls-proxy-protocols/006-h3-server-controlled-corpus.md` +//! +//! Historical program: `plans/http3-production-qualification-program.md` +//! Historical plan: `plans/http3-independent-interop-and-impairment-qualification.md` //! //! This suite is deterministic and local-only for Tier 1. External //! interoperability servers (ngtcp2/nghttp3, quiche, …) are exercised only @@ -43,15 +46,27 @@ //! valid successful outcome per the graduation plan. use std::net::SocketAddr; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; use bytes::Bytes; use eggfetch_core::{Client, HttpVersionPolicy, RequestBody, Timeout, TlsConfig}; +use futures_util::stream; use futures_util::StreamExt; use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; use tokio::sync::watch; +#[cfg(feature = "tls-rustls")] +mod tls_fixtures; + +#[cfg(feature = "tls-rustls")] +use tls_fixtures::CertAuthority; +#[cfg(feature = "tls-rustls")] +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +#[cfg(feature = "tls-rustls")] +use tokio::net::TcpListener; + // --------------------------------------------------------------------------- // Fixtures (loopback QUIC+H3, same shape as h3_hardening.rs) // --------------------------------------------------------------------------- @@ -295,11 +310,349 @@ impl QuicTestServer { Self { addr, shutdown: tx } } + /// Complete one response on a connection, then GOAWAY via `shutdown(0)`. + /// The QUIC endpoint keeps accepting new connections on the same port. + #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)] + async fn start_shutdown_after_one_response(body: Vec) -> Self { + let cert_key = + rcgen::generate_simple_self_signed(vec!["localhost".into()]).expect("rcgen cert"); + let cert_der = CertificateDer::from(cert_key.cert.der().to_vec()); + let key_der = + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert_key.key_pair.serialize_der())); + let mut server_tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_protocol_versions(&[&rustls::version::TLS13]) + .expect("TLS13") + .with_no_client_auth() + .with_single_cert(vec![cert_der], key_der) + .expect("cert"); + server_tls.alpn_protocols = vec![b"h3".to_vec()]; + let quic_crypto = + quinn::crypto::rustls::QuicServerConfig::try_from(server_tls).expect("server crypto"); + let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_crypto)); + let mut transport = quinn::TransportConfig::default(); + transport.max_concurrent_bidi_streams(100u32.into()); + transport.max_concurrent_uni_streams(100u32.into()); + server_config.transport_config(Arc::new(transport)); + let endpoint = quinn::Endpoint::server(server_config, "127.0.0.1:0".parse().unwrap()) + .expect("bind server"); + let addr = endpoint.local_addr().expect("addr"); + let body = Bytes::from(body); + let goaway_once = Arc::new(AtomicBool::new(false)); + let (tx, mut rx) = watch::channel(false); + tokio::spawn(async move { + loop { + tokio::select! { + incoming = endpoint.accept() => { + let Some(incoming) = incoming else { break }; + let body = body.clone(); + let goaway_once = goaway_once.clone(); + tokio::spawn(async move { + let Ok(conn) = incoming.await else { return }; + let h3_conn = h3_quinn::Connection::new(conn); + let Ok(mut server) = + h3::server::Connection::<_, Bytes>::new(h3_conn).await + else { + return; + }; + let send_goaway = !goaway_once.swap(true, Ordering::SeqCst); + loop { + let Ok(Some(resolver)) = server.accept().await else { break }; + let body = body.clone(); + let Ok((req, mut stream)) = resolver.resolve_request().await + else { + continue; + }; + while stream.recv_data().await.ok().flatten().is_some() {} + let resp = http::Response::builder() + .status(200) + .header("content-type", "text/plain") + .body(()) + .unwrap(); + if stream.send_response(resp).await.is_err() { + break; + } + if req.method() != http::Method::HEAD { + let _ = stream.send_data(body.clone()).await; + } + let _ = stream.finish().await; + if send_goaway { + tokio::time::sleep(Duration::from_millis(150)).await; + let _ = server.shutdown(0).await; + break; + } + } + }); + } + _ = rx.changed() => break, + } + } + }); + Self { addr, shutdown: tx } + } + + /// Consumes request bodies slowly so client-side upload cancellation can + /// win a short timeout race. + #[allow(unknown_lints, clippy::unused_async, clippy::unused_async_trait_impl)] + async fn start_slow_upload_consumer(body: Vec) -> Self { + let cert_key = + rcgen::generate_simple_self_signed(vec!["localhost".into()]).expect("rcgen cert"); + let cert_der = CertificateDer::from(cert_key.cert.der().to_vec()); + let key_der = + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert_key.key_pair.serialize_der())); + let mut server_tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_protocol_versions(&[&rustls::version::TLS13]) + .expect("TLS13") + .with_no_client_auth() + .with_single_cert(vec![cert_der], key_der) + .expect("cert"); + server_tls.alpn_protocols = vec![b"h3".to_vec()]; + let quic_crypto = + quinn::crypto::rustls::QuicServerConfig::try_from(server_tls).expect("server crypto"); + let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_crypto)); + let mut transport = quinn::TransportConfig::default(); + transport.max_concurrent_bidi_streams(100u32.into()); + transport.max_concurrent_uni_streams(100u32.into()); + server_config.transport_config(Arc::new(transport)); + let endpoint = quinn::Endpoint::server(server_config, "127.0.0.1:0".parse().unwrap()) + .expect("bind server"); + let addr = endpoint.local_addr().expect("addr"); + let body = Bytes::from(body); + let (tx, mut rx) = watch::channel(false); + tokio::spawn(async move { + loop { + tokio::select! { + incoming = endpoint.accept() => { + let Some(incoming) = incoming else { break }; + let body = body.clone(); + tokio::spawn(async move { + let Ok(conn) = incoming.await else { return }; + let h3_conn = h3_quinn::Connection::new(conn); + let Ok(mut server) = + h3::server::Connection::<_, Bytes>::new(h3_conn).await + else { + return; + }; + loop { + let Ok(Some(resolver)) = server.accept().await else { break }; + let body = body.clone(); + let Ok((_req, mut stream)) = resolver.resolve_request().await + else { + continue; + }; + loop { + match stream.recv_data().await { + Ok(Some(_)) => { + tokio::time::sleep(Duration::from_millis(25)).await; + } + Ok(None) => break, + Err(_) => break, + } + } + let resp = http::Response::builder() + .status(200) + .header("content-type", "text/plain") + .body(()) + .unwrap(); + if stream.send_response(resp).await.is_err() { + break; + } + let _ = stream.send_data(body).await; + let _ = stream.finish().await; + } + }); + } + _ = rx.changed() => break, + } + } + }); + Self { addr, shutdown: tx } + } + fn url(&self) -> String { format!("https://127.0.0.1:{}/", self.addr.port()) } } +#[cfg(feature = "tls-rustls")] +struct HttpsAltSvcServer { + port: u16, + shutdown_tx: watch::Sender, +} + +#[cfg(feature = "tls-rustls")] +impl HttpsAltSvcServer { + async fn start( + ca: &CertAuthority, + hostnames: &[&str], + alt_svc: Option, + body: Vec, + ) -> Self { + let (cert_der, key_der) = ca.generate_server_cert(hostnames); + let server_config = rustls::ServerConfig::builder() + .with_no_client_auth() + .with_single_cert(vec![cert_der], key_der) + .expect("cert"); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let port = listener.local_addr().expect("port").port(); + let (tx, mut rx) = watch::channel(false); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config)); + let alt_svc = alt_svc.clone(); + tokio::spawn(async move { + loop { + tokio::select! { + result = listener.accept() => { + let Ok((tcp, _)) = result else { break }; + let acceptor = acceptor.clone(); + let alt_svc = alt_svc.clone(); + let body = body.clone(); + tokio::spawn(async move { + let Ok(tls) = acceptor.accept(tcp).await else { return }; + let mut reader = BufReader::new(tls); + let mut line = String::new(); + if reader.read_line(&mut line).await.is_err() || line.trim().is_empty() { + return; + } + loop { + let mut h = String::new(); + if reader.read_line(&mut h).await.is_err() || h.trim().is_empty() { + break; + } + } + let alt_header = alt_svc + .as_ref() + .map(|v| format!("Alt-Svc: {v}\r\n")) + .unwrap_or_default(); + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n{}Connection: close\r\n\r\n", + body.len(), + alt_header, + ); + let mut stream = reader.into_inner(); + let _ = stream.write_all(resp.as_bytes()).await; + let _ = stream.write_all(&body).await; + let _ = stream.flush().await; + }); + } + _ = rx.changed() => break, + } + } + }); + Self { + port, + shutdown_tx: tx, + } + } + + fn url(&self) -> String { + format!("https://localhost:{}/", self.port) + } +} + +#[cfg(feature = "tls-rustls")] +impl Drop for HttpsAltSvcServer { + fn drop(&mut self) { + let _ = self.shutdown_tx.send(true); + } +} + +#[cfg(feature = "tls-rustls")] +struct VerifiedH3Server { + addr: SocketAddr, + shutdown: watch::Sender, +} + +#[cfg(feature = "tls-rustls")] +impl VerifiedH3Server { + async fn start( + cert_der: CertificateDer<'static>, + key_der: PrivateKeyDer<'static>, + body: Vec, + ) -> Self { + tokio::task::yield_now().await; + let mut server_tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_protocol_versions(&[&rustls::version::TLS13]) + .expect("TLS13") + .with_no_client_auth() + .with_single_cert(vec![cert_der], key_der) + .expect("cert"); + server_tls.alpn_protocols = vec![b"h3".to_vec()]; + let quic_crypto = + quinn::crypto::rustls::QuicServerConfig::try_from(server_tls).expect("crypto"); + let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_crypto)); + let mut transport = quinn::TransportConfig::default(); + transport.max_concurrent_bidi_streams(100u32.into()); + transport.max_concurrent_uni_streams(100u32.into()); + server_config.transport_config(Arc::new(transport)); + let endpoint = + quinn::Endpoint::server(server_config, "127.0.0.1:0".parse().unwrap()).expect("bind"); + let addr = endpoint.local_addr().expect("addr"); + let body = Bytes::from(body); + let (tx, mut rx) = watch::channel(false); + tokio::spawn(async move { + loop { + tokio::select! { + incoming = endpoint.accept() => { + let Some(incoming) = incoming else { break }; + let body = body.clone(); + tokio::spawn(async move { + let Ok(conn) = incoming.await else { return }; + let h3_conn = h3_quinn::Connection::new(conn); + let Ok(mut server) = + h3::server::Connection::<_, Bytes>::new(h3_conn).await + else { + return; + }; + loop { + let Ok(Some(resolver)) = server.accept().await else { break }; + let body = body.clone(); + let Ok((_req, mut stream)) = resolver.resolve_request().await + else { + continue; + }; + while stream.recv_data().await.ok().flatten().is_some() {} + let resp = http::Response::builder().status(200).body(()).unwrap(); + if stream.send_response(resp).await.is_err() { + break; + } + let _ = stream.send_data(body).await; + let _ = stream.finish().await; + } + }); + } + _ = rx.changed() => break, + } + } + }); + Self { addr, shutdown: tx } + } +} + +#[cfg(feature = "tls-rustls")] +impl Drop for VerifiedH3Server { + fn drop(&mut self) { + let _ = self.shutdown.send(true); + } +} + +#[cfg(feature = "tls-rustls")] +fn auto_client_with_ca(ca: &CertAuthority) -> Client { + let tls = TlsConfig::builder() + .ca_certificate_pem(&ca.cert_pem()) + .expect("ca") + .build(); + Client::builder() + .http_version_policy(HttpVersionPolicy::Auto { allow_http3: true }) + .tls_config(tls) + .automatic_decompression(false) + .build() +} + impl Drop for QuicTestServer { fn drop(&mut self) { let _ = self.shutdown.send(true); @@ -363,6 +716,30 @@ fn external_h3_client() -> Client { builder.build() } +fn external_h3_auto_client() -> Client { + let mut builder = + Client::builder().http_version_policy(HttpVersionPolicy::Auto { allow_http3: true }); + if std::env::var_os("EGGFETCH_H3_INTEROP_DANGER_ACCEPT_INVALID_CERTS").is_some() { + builder = builder.tls_config( + TlsConfig::builder() + .danger_accept_invalid_certs(true) + .build(), + ); + } + builder.build() +} + +fn external_control_url(case: &str) -> Option { + let key = match case { + "stream_reset" => "EGGFETCH_H3_INTEROP_CONTROL_STREAM_RESET", + "graceful_connection_close" => "EGGFETCH_H3_INTEROP_CONTROL_GRACEFUL_CONNECTION_CLOSE", + "goaway_reconnect" => "EGGFETCH_H3_INTEROP_CONTROL_GOAWAY_RECONNECT", + "alternative_port" => "EGGFETCH_H3_INTEROP_CONTROL_ALTERNATIVE_PORT", + _ => return None, + }; + std::env::var(key).ok().filter(|value| !value.is_empty()) +} + fn external_case_enabled(case: &str) -> bool { let cases = std::env::var("EGGFETCH_H3_INTEROP_CASES").unwrap_or_else(|_| "get,head".into()); cases @@ -550,6 +927,175 @@ async fn external_h3_interop_servers_if_configured() { } eprintln!("H3_CORPUS_CASE connection_reuse=pass endpoint={url}"); } + if external_case_enabled("cancellation_before_headers") { + let stalled = client.get(url).unwrap().send(); + let aborted = tokio::time::timeout(Duration::from_millis(500), stalled).await; + assert!(aborted.is_err(), "must abort before response headers"); + let mut recovery = client + .get(url) + .unwrap() + .send() + .await + .expect("client usable after cancel-before-headers"); + assert!( + (200..400).contains(&recovery.status().as_u16()), + "recovery status" + ); + let _ = recovery.text().await.expect("recovery body"); + eprintln!("H3_CORPUS_CASE cancellation_before_headers=pass endpoint={url}"); + } + if external_case_enabled("cancellation_during_upload") { + let chunks = (0..256) + .map(|_| Ok(Bytes::from(vec![0x44; 4096]))) + .collect::>(); + let body = RequestBody::from_stream(stream::iter(chunks), None); + let stalled = client.post(url).unwrap().body(body).send(); + let aborted = tokio::time::timeout(Duration::from_millis(500), stalled).await; + assert!(aborted.is_err(), "must abort during upload"); + let mut recovery = client + .get(url) + .unwrap() + .send() + .await + .expect("client usable after upload cancel"); + assert!( + (200..400).contains(&recovery.status().as_u16()), + "recovery status" + ); + let _ = recovery.text().await.expect("recovery body"); + eprintln!("H3_CORPUS_CASE cancellation_during_upload=pass endpoint={url}"); + } + if external_case_enabled("cancellation_during_download") { + let mut response = client + .get(url) + .unwrap() + .send() + .await + .expect("download for cancel"); + let mut body_stream = response.bytes_stream().expect("download stream"); + if let Some(chunk) = body_stream.next().await { + let _ = chunk.expect("first chunk"); + } + drop(body_stream); + drop(response); + let mut recovery = client + .get(url) + .unwrap() + .send() + .await + .expect("client usable after download cancel"); + assert!( + (200..400).contains(&recovery.status().as_u16()), + "recovery status" + ); + let _ = recovery.text().await.expect("recovery body"); + eprintln!("H3_CORPUS_CASE cancellation_during_download=pass endpoint={url}"); + } + if external_case_enabled("stream_reset") { + let control = external_control_url("stream_reset") + .expect("stream_reset requires EGGFETCH_H3_INTEROP_CONTROL_STREAM_RESET"); + let outcome = tokio::time::timeout( + Duration::from_secs(15), + client.get(&control).unwrap().send(), + ) + .await; + if let Ok(Ok(mut resp)) = outcome { + let _ = tokio::time::timeout(Duration::from_secs(5), resp.text()).await; + } + let mut recovery = client + .get(url) + .unwrap() + .send() + .await + .expect("client usable after stream reset"); + assert!( + (200..400).contains(&recovery.status().as_u16()), + "recovery status" + ); + let _ = recovery.text().await.expect("recovery body"); + eprintln!("H3_CORPUS_CASE stream_reset=pass endpoint={url}"); + } + if external_case_enabled("graceful_connection_close") { + let control = external_control_url("graceful_connection_close").expect( + "graceful_connection_close requires EGGFETCH_H3_INTEROP_CONTROL_GRACEFUL_CONNECTION_CLOSE", + ); + let mut control_resp = client + .get(&control) + .unwrap() + .send() + .await + .expect("graceful control request"); + let _ = control_resp.text().await; + let mut recovery = client + .get(url) + .unwrap() + .send() + .await + .expect("client reconnects after graceful close"); + assert!( + (200..400).contains(&recovery.status().as_u16()), + "recovery status" + ); + let _ = recovery.text().await.expect("recovery body"); + eprintln!("H3_CORPUS_CASE graceful_connection_close=pass endpoint={url}"); + } + if external_case_enabled("goaway_reconnect") { + let control = external_control_url("goaway_reconnect") + .expect("goaway_reconnect requires EGGFETCH_H3_INTEROP_CONTROL_GOAWAY_RECONNECT"); + let before = client.transport_metrics().snapshot(); + let mut control_resp = client + .get(&control) + .unwrap() + .send() + .await + .expect("goaway control request"); + let _ = control_resp.text().await; + let mut recovery = client + .get(url) + .unwrap() + .send() + .await + .expect("client reconnects after GOAWAY"); + assert!( + (200..400).contains(&recovery.status().as_u16()), + "recovery status" + ); + let _ = recovery.text().await.expect("recovery body"); + let after = client.transport_metrics().snapshot(); + assert!( + after.h3_reconnected > before.h3_reconnected, + "expected h3_reconnected to increase: before={before:?} after={after:?}" + ); + eprintln!("H3_CORPUS_CASE goaway_reconnect=pass endpoint={url}"); + } + if external_case_enabled("alternative_port") { + let discovery = external_control_url("alternative_port") + .expect("alternative_port requires EGGFETCH_H3_INTEROP_CONTROL_ALTERNATIVE_PORT"); + let auto_client = external_h3_auto_client(); + let mut learn = auto_client + .get(&discovery) + .unwrap() + .send() + .await + .expect("Alt-Svc discovery"); + assert!( + (200..400).contains(&learn.status().as_u16()), + "discovery status" + ); + let _ = learn.text().await.expect("discovery body"); + let mut h3 = auto_client + .get(url) + .unwrap() + .send() + .await + .expect("H3 on alternative port"); + assert!( + (200..400).contains(&h3.status().as_u16()), + "alternative port status" + ); + let _ = h3.text().await.expect("alternative port body"); + eprintln!("H3_CORPUS_CASE alternative_port=pass endpoint={url}"); + } } } @@ -557,6 +1103,27 @@ async fn external_h3_interop_servers_if_configured() { // §2 continued: request/response corpus (local, deterministic) // --------------------------------------------------------------------------- +/// Streaming upload succeeds over H3 (corpus `streaming_upload`). +#[tokio::test(flavor = "multi_thread")] +async fn h3_streaming_upload_succeeds() { + let server = QuicTestServer::start(b"stream-up".to_vec()).await; + let url = server.url(); + let client = h3_client(); + let chunks = (0..32) + .map(|_| Ok(Bytes::from(vec![0x33; 1024]))) + .collect::>(); + let body = RequestBody::from_stream(stream::iter(chunks), Some(32 * 1024)); + let mut resp = client + .post(&url) + .unwrap() + .body(body) + .send() + .await + .expect("h3 streaming post"); + assert_eq!(resp.status().as_u16(), 200); + assert_eq!(resp.text().await.expect("body"), "stream-up"); +} + /// POST with a buffered body succeeds over H3 (upload path). #[tokio::test(flavor = "multi_thread")] async fn h3_post_with_buffered_body_succeeds() { @@ -768,10 +1335,263 @@ async fn h3_early_close_terminates_and_client_recovers() { assert_eq!(resp.text().await.expect("body"), "recovered"); } +/// Upload cancellation returns promptly and the client stays usable. +#[tokio::test(flavor = "multi_thread")] +async fn h3_cancellation_during_upload_is_prompt() { + let slow = QuicTestServer::start_slow_upload_consumer(b"unused".to_vec()).await; + let slow_url = slow.url(); + let good = QuicTestServer::start(b"after-upload-cancel".to_vec()).await; + let good_url = good.url(); + let client = h3_client(); + let chunks = (0..512) + .map(|_| Ok(Bytes::from(vec![0x22; 4096]))) + .collect::>(); + let body = RequestBody::from_stream(stream::iter(chunks), None); + let stalled = client.post(&slow_url).unwrap().body(body).send(); + let aborted = tokio::time::timeout(Duration::from_millis(75), stalled).await; + assert!(aborted.is_err(), "upload cancel must be prompt"); + drop(aborted); + let mut recovery = client + .get(&good_url) + .unwrap() + .send() + .await + .expect("usable after upload cancel"); + assert_eq!(recovery.status().as_u16(), 200); + assert_eq!(recovery.text().await.expect("body"), "after-upload-cancel"); +} + +/// Download cancellation releases the stream and the client stays usable. +#[tokio::test(flavor = "multi_thread")] +async fn h3_cancellation_during_download_is_prompt() { + let payload = vec![0xCD_u8; 512 * 1024]; + let server = QuicTestServer::start(payload).await; + let url = server.url(); + let client = h3_client(); + let mut resp = client.get(&url).unwrap().send().await.expect("download"); + let mut body_stream = resp.bytes_stream().expect("stream"); + let first = body_stream + .next() + .await + .expect("first chunk") + .expect("chunk"); + assert!(!first.is_empty()); + drop(body_stream); + drop(resp); + let mut recovery = client + .get(&url) + .unwrap() + .send() + .await + .expect("usable after download cancel"); + assert_eq!(recovery.status().as_u16(), 200); + assert_eq!(recovery.bytes().await.expect("body").len(), 512 * 1024); +} + +/// GOAWAY after one response drains the generation; the next request reconnects. +#[tokio::test(flavor = "multi_thread")] +async fn h3_graceful_connection_close_reconnects() { + let server = QuicTestServer::start_shutdown_after_one_response(b"graceful-one".to_vec()).await; + let url = server.url(); + let client = h3_client(); + let mut first = client.get(&url).unwrap().send().await.expect("first"); + assert_eq!(first.text().await.expect("body"), "graceful-one"); + tokio::time::sleep(Duration::from_millis(400)).await; + let mut second = client.get(&url).unwrap().send().await.expect("second"); + assert_eq!(second.text().await.expect("body"), "graceful-one"); +} + +/// GOAWAY reconnect is observable via `h3_reconnected` and optional drain metrics. +#[tokio::test(flavor = "multi_thread")] +async fn h3_goaway_reconnect_observes_metrics() { + let server = QuicTestServer::start_shutdown_after_one_response(b"goaway-one".to_vec()).await; + let url = server.url(); + let client = h3_client(); + let before = client.transport_metrics().snapshot(); + let mut first = client.get(&url).unwrap().send().await.expect("first"); + assert_eq!(first.text().await.expect("body"), "goaway-one"); + let mid = client.transport_metrics().snapshot(); + tokio::time::sleep(Duration::from_millis(400)).await; + let mut second = client.get(&url).unwrap().send().await.expect("reconnect"); + assert_eq!(second.text().await.expect("body"), "goaway-one"); + let after = client.transport_metrics().snapshot(); + assert!( + after.h3_reconnected > before.h3_reconnected, + "h3_reconnected before={before:?} after={after:?}" + ); + if mid.h3_drain_observed > before.h3_drain_observed { + assert!( + after.h3_drain_observed >= mid.h3_drain_observed, + "drain metric should remain observed" + ); + } +} + +/// Explicit IPv4 loopback GET succeeds. +#[tokio::test(flavor = "multi_thread")] +async fn h3_ipv4_loopback_get_succeeds() { + let server = QuicTestServer::start(b"ipv4-ok".to_vec()).await; + let client = h3_client(); + let mut resp = client + .get(&server.url()) + .unwrap() + .send() + .await + .expect("ipv4 get"); + assert_eq!(resp.status().as_u16(), 200); + assert_eq!(resp.text().await.expect("body"), "ipv4-ok"); +} + +/// Authenticated Alt-Svc on an alternative port is selected by `Auto`. +#[cfg(feature = "tls-rustls")] +#[tokio::test(flavor = "multi_thread")] +async fn h3_alternative_port_via_altsvc() { + let ca = CertAuthority::new(); + let (h3_cert, h3_key) = ca.generate_server_cert(&["localhost", "127.0.0.1"]); + let h3 = VerifiedH3Server::start(h3_cert, h3_key, b"alt-h3-body".to_vec()).await; + let h1 = HttpsAltSvcServer::start( + &ca, + &["localhost"], + Some(format!("h3=\":{}\"; ma=60", h3.addr.port())), + b"discover-h1".to_vec(), + ) + .await; + let client = auto_client_with_ca(&ca); + let mut learn = client.get(&h1.url()).unwrap().send().await.expect("learn"); + assert_eq!(learn.text().await.expect("h1 body"), "discover-h1"); + let mut h3_resp = client + .get(&h1.url()) + .unwrap() + .send() + .await + .expect("h3 route"); + assert_eq!(h3_resp.text().await.expect("h3 body"), "alt-h3-body"); + let metrics = client.transport_metrics().snapshot(); + assert!( + metrics.h3_route_attempted > 0, + "must attempt H3: {metrics:?}" + ); +} + // --------------------------------------------------------------------------- // §5: Resource and soak evidence (bounded, deterministic) // --------------------------------------------------------------------------- +/// Soak counts (M009); short controls above keep smaller loops for fast Tier 1. +const SOAK_SEQUENTIAL_REUSE: u32 = 1_000; +const SOAK_FAIL_RECONNECT_CYCLES: u32 = 50; +const SOAK_CANCELLATION_STORM: u32 = 50; +const SOAK_PARTIAL_BODY_DROP: u32 = 30; +const SOAK_CLIENT_CONSTRUCTION_DROP: u32 = 100; + +/// Measure current RSS in bytes. Returns 0 on unsupported platforms. +fn current_rss_bytes() -> usize { + #[cfg(target_os = "linux")] + { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|s| { + s.lines().find(|l| l.starts_with("VmRSS:")).and_then(|l| { + l.split_whitespace() + .nth(1) + .and_then(|v| v.parse::().ok()) + .map(|kb| kb * 1024) + }) + }) + .unwrap_or(0) + } + #[cfg(not(target_os = "linux"))] + { + 0 + } +} + +/// Open file-descriptor count. Returns 0 on unsupported platforms. +fn current_open_fd_count() -> usize { + #[cfg(target_os = "linux")] + { + std::fs::read_dir("/proc/self/fd") + .map(|entries| entries.count()) + .unwrap_or(0) + } + #[cfg(not(target_os = "linux"))] + { + 0 + } +} + +/// Shared reuse/fail/cancel soaks stay under a tight Linux `VmRSS` step. +const RESOURCE_RSS_ENVELOPE_BYTES: usize = 4 * 1024 * 1024; +/// Construction/drop builds a full H3 client + QUIC handshake each cycle. +/// ubuntu-latest measured ~21 MiB `VmRSS` step across 100 cycles with one +/// reused peer (glibc retention); keep a hard cap with headroom, not exact +/// equality. Open-fd growth stays on the shared tight envelope. +const CLIENT_DROP_RSS_ENVELOPE_BYTES: usize = 32 * 1024 * 1024; +const RESOURCE_FD_ENVELOPE: usize = 64; + +fn assert_resource_envelope( + rss_before: usize, + rss_after: usize, + fd_before: usize, + fd_after: usize, + context: &str, +) { + assert_resource_envelope_with_limits( + rss_before, + rss_after, + fd_before, + fd_after, + RESOURCE_RSS_ENVELOPE_BYTES, + RESOURCE_FD_ENVELOPE, + context, + ); +} + +fn assert_resource_envelope_with_limits( + rss_before: usize, + rss_after: usize, + fd_before: usize, + fd_after: usize, + max_rss_delta: usize, + max_fd_delta: usize, + context: &str, +) { + if rss_before > 0 && rss_after > 0 { + let delta = rss_after.abs_diff(rss_before); + assert!( + delta < max_rss_delta, + "{context}: VmRSS grew by {delta} bytes (before={rss_before}, after={rss_after})" + ); + } + if fd_before > 0 && fd_after > 0 { + let delta = fd_after.abs_diff(fd_before); + assert!( + delta < max_fd_delta, + "{context}: open fd count grew by {delta} (before={fd_before}, after={fd_after})" + ); + } +} + +fn assert_h3_diagnostics_bounded_and_redacted(client: &Client) { + let diagnostics = client.transport_metrics().h3_diagnostics(); + assert!( + diagnostics.len() <= 64, + "h3_diagnostics must stay capped: {}", + diagnostics.len() + ); + for diagnostic in &diagnostics { + let debug = format!("{diagnostic:?}"); + assert!(!debug.contains("localhost"), "hostname leaked: {debug}"); + assert!(!debug.contains("authorization"), "header leaked: {debug}"); + assert!(!debug.contains("cookie"), "cookie leaked: {debug}"); + assert!(!debug.contains("set-cookie"), "header leaked: {debug}"); + assert!( + !debug.contains("peer reason"), + "close reason leaked: {debug}" + ); + } +} + #[tokio::test(flavor = "multi_thread")] async fn hundred_sequential_requests_on_reused_h3_connection() { let server = QuicTestServer::start(b"x".repeat(64)).await; @@ -870,14 +1690,201 @@ async fn cancellation_storm_leaves_client_usable() { #[tokio::test(flavor = "multi_thread")] async fn client_construction_drop_loops_do_not_leak() { + let server = QuicTestServer::start(b"drop-ok".to_vec()).await; + let url = server.url(); for _ in 0..20u32 { - let server = QuicTestServer::start(b"drop-ok".to_vec()).await; - let url = server.url(); let client = h3_client(); let mut resp = client.get(&url).unwrap().send().await.expect("req"); assert_eq!(resp.status().as_u16(), 200); + let _ = resp.text().await.expect("body"); + drop(client); + } +} + +/// M009 soak: 1 000 sequential GETs on one reused H3 connection. +#[tokio::test(flavor = "multi_thread")] +async fn thousand_sequential_requests_on_reused_h3_connection() { + let server = QuicTestServer::start(b"x".repeat(64)).await; + let url = server.url(); + let client = h3_client(); + for i in 0..10u32 { + let mut resp = client + .get(&url) + .unwrap() + .send() + .await + .unwrap_or_else(|e| panic!("warmup {i}: {e:?}")); + assert_eq!(resp.status().as_u16(), 200); + let _ = resp.text().await.expect("warmup body"); + } + let rss_before = current_rss_bytes(); + let fd_before = current_open_fd_count(); + for i in 0..SOAK_SEQUENTIAL_REUSE { + let mut resp = client + .get(&url) + .unwrap() + .send() + .await + .unwrap_or_else(|e| panic!("request {i} failed: {e:?}")); + assert_eq!(resp.status().as_u16(), 200); + let body = resp.text().await.expect("body"); + assert_eq!(body.len(), 64, "request {i}"); + } + let m = client.transport_metrics().snapshot(); + assert!( + m.h3_connections_created < 10, + "connection churn too high after {SOAK_SEQUENTIAL_REUSE} reuse: {}", + m.h3_connections_created + ); + assert_h3_diagnostics_bounded_and_redacted(&client); + assert_resource_envelope( + rss_before, + current_rss_bytes(), + fd_before, + current_open_fd_count(), + "thousand sequential H3 reuse", + ); +} + +/// M009 soak: fail/reconnect beyond the 10-cycle short control. +#[tokio::test(flavor = "multi_thread")] +async fn fifty_repeated_fail_reconnect_cycles_do_not_grow_state_soak() { + let good = QuicTestServer::start(b"ok".to_vec()).await; + let good_url = good.url(); + let client = h3_client_with_connect_timeout(Duration::from_millis(200)); + for _ in 0..5u32 { + let hole = Blackhole::bind(); + let _ = client.get(&hole.url()).unwrap().send().await; + } + let warm = client.transport_metrics().snapshot(); + let rss_before = current_rss_bytes(); + let fd_before = current_open_fd_count(); + for cycle in 0..SOAK_FAIL_RECONNECT_CYCLES { + let hole = Blackhole::bind(); + let _ = client.get(&hole.url()).unwrap().send().await; + let mut resp = client + .get(&good_url) + .unwrap() + .send() + .await + .unwrap_or_else(|e| panic!("good after cycle {cycle}: {e:?}")); + assert_eq!(resp.status().as_u16(), 200); + let _ = resp.text().await.expect("body"); + } + let m = client.transport_metrics().snapshot(); + assert!( + m.h3_connections_created < 64, + "fail/reconnect soak must stay within cache scale: {}", + m.h3_connections_created + ); + let growth = m + .h3_connections_created + .saturating_sub(warm.h3_connections_created); + assert!( + growth < SOAK_FAIL_RECONNECT_CYCLES as usize / 2, + "must not grow ~one live generation per failure: warm={} after={}", + warm.h3_connections_created, + m.h3_connections_created + ); + assert_h3_diagnostics_bounded_and_redacted(&client); + assert_resource_envelope( + rss_before, + current_rss_bytes(), + fd_before, + current_open_fd_count(), + "fifty fail/reconnect cycles", + ); +} + +/// M009 soak: cancellation storm plus partial-body-drop loop, then recovery. +#[tokio::test(flavor = "multi_thread")] +async fn extended_cancellation_and_partial_drop_storm_leaves_client_usable() { + let payload = vec![0x42_u8; 256 * 1024]; + let server = QuicTestServer::start(payload.clone()).await; + let url = server.url(); + let client = h3_client_with_connect_timeout(Duration::from_secs(5)); + for _ in 0..5u32 { + let mut resp = client.get(&url).unwrap().send().await.expect("warmup"); + let _ = resp.text().await.expect("warmup body"); + } + let rss_before = current_rss_bytes(); + let fd_before = current_open_fd_count(); + for _ in 0..SOAK_CANCELLATION_STORM { + let fut = client.get(&url).unwrap().send(); + let _ = tokio::time::timeout(Duration::from_millis(50), fut).await; + } + for _ in 0..SOAK_PARTIAL_BODY_DROP { + let mut resp = client + .get(&url) + .unwrap() + .send() + .await + .expect("partial send"); + let mut stream = resp.bytes_stream().expect("stream"); + if let Some(chunk) = stream.next().await { + let _ = chunk.expect("chunk"); + } + drop(stream); + drop(resp); + } + let mut recovery = client + .get(&url) + .unwrap() + .send() + .await + .expect("usable after storm"); + assert_eq!(recovery.status().as_u16(), 200); + assert_eq!(recovery.bytes().await.expect("body").len(), payload.len()); + assert_h3_diagnostics_bounded_and_redacted(&client); + assert_resource_envelope( + rss_before, + current_rss_bytes(), + fd_before, + current_open_fd_count(), + "cancellation and partial-drop storm", + ); +} + +/// M009 soak: many client construction/drop cycles with one request each. +/// +/// Reuses one peer so the envelope measures client drop, not fire-and-forget +/// Quinn server tasks (`QuicTestServer::drop` only signals shutdown). +#[tokio::test(flavor = "multi_thread")] +async fn hundred_client_construction_drop_loops_do_not_leak_soak() { + let server = QuicTestServer::start(b"drop-ok".to_vec()).await; + let url = server.url(); + { + let client = h3_client(); + let mut resp = client.get(&url).unwrap().send().await.expect("warmup"); + let _ = resp.text().await; + drop(client); + } + // Let the warmup accept/response tasks settle before the baseline sample. + tokio::time::sleep(Duration::from_millis(50)).await; + let rss_before = current_rss_bytes(); + let fd_before = current_open_fd_count(); + for i in 0..SOAK_CLIENT_CONSTRUCTION_DROP { + let client = h3_client(); + let mut resp = client + .get(&url) + .unwrap() + .send() + .await + .unwrap_or_else(|e| panic!("req {i}: {e:?}")); + assert_eq!(resp.status().as_u16(), 200); + let _ = resp.text().await.expect("body"); drop(client); } + tokio::time::sleep(Duration::from_millis(50)).await; + assert_resource_envelope_with_limits( + rss_before, + current_rss_bytes(), + fd_before, + current_open_fd_count(), + CLIENT_DROP_RSS_ENVELOPE_BYTES, + RESOURCE_FD_ENVELOPE, + "hundred client construction/drop", + ); } // --------------------------------------------------------------------------- diff --git a/crates/eggfetch-core/tests/public_api_contracts.rs b/crates/eggfetch-core/tests/public_api_contracts.rs index dab0dd88..7b5a5297 100644 --- a/crates/eggfetch-core/tests/public_api_contracts.rs +++ b/crates/eggfetch-core/tests/public_api_contracts.rs @@ -131,7 +131,8 @@ fn caller_owned_h3_datagram_route_contracts_compile() { } fn recv<'a>(&'a self, _buffer: &'a mut [u8]) -> DatagramRecvFuture<'a> { - Box::pin(async { Ok(0) }) + let peer = self.peer; + Box::pin(async move { Ok((0, peer)) }) } fn local_addr(&self) -> SocketAddr { diff --git a/docs/architecture/core-tls-proxy-protocols.md b/docs/architecture/core-tls-proxy-protocols.md index 9ecd4db5..45078c84 100644 --- a/docs/architecture/core-tls-proxy-protocols.md +++ b/docs/architecture/core-tls-proxy-protocols.md @@ -642,13 +642,15 @@ contract is intentionally narrow and lives entirely in The `DialTarget` carries the original **logical** origin host/port, never a physical path. Choosing a carrier — including choosing a relay — is the provider's job. -- `DatagramRoute` supplies one datagram `send`, one `recv`, and the fixed - `local_addr`/`peer_addr`. The peer is fixed by construction; the bridge - refuses any other transmit destination, and a route that forwarded datagrams - from an unverified source would be injecting packets into the connection, so - providers must reject those. +- `DatagramRoute` supplies one datagram `send`, one `recv` (returning + `(len, source)`), and the fixed `local_addr`/`peer_addr`. The peer is fixed + by construction; the bridge refuses any other transmit destination and drops + any received datagram whose reported source is not that peer before feeding + Quinn. - Failures are typed `DialError`/`DialErrorKind`. Nothing is inferred from - `Display` text anywhere in the H3 stack. + `Display` text anywhere in the H3 stack. Connection-kind dial failures map + to fixed-text `H3Connect`; Authentication / Rejected / Other stay on + `CustomTransport` with provider text (same as stream `Dialer`). Eggfetch still owns the whole QUIC stack. The bridge builds the QUIC/TLS client configuration, so a caller supplies a datagram carrier and can never take over @@ -666,14 +668,17 @@ even when the route's physical peer is a relay. | No ECN claims | Receive metadata reports no ECN codepoint and no destination IP, because neither is observable through this contract | | Terminal I/O ends the generation promptly | The bridge reports the error to Quinn *and* closes the QUIC connection with a transport error, so a request never parks until the idle timeout | | No leaked workers | Dropping the socket aborts both worker tasks; workers hold only the bridge's shared state, never the socket, so there is no handle cycle | -| No provider text escapes | The bridge never formats a `DatagramRoute`; Quinn-facing I/O errors use a fixed string, and the typed `DialErrorKind` is what reaches the connector | +| No provider text escapes on Connection | The bridge never formats a `DatagramRoute`; Quinn-facing I/O errors use a fixed string; Connection-kind dial failures map to fixed-text `H3Connect`; Auth/Rejected/Other may retain provider text on `CustomTransport` | +| Recv source trust | `recv` reports source; bridge drops off-peer datagrams without terminating the route | **Error mapping.** Route failures are reclassified from the caller's typed evidence, never from text: `Connection` becomes connect-class `H3Connect` -(so `Auto` fallback and Alt-Svc suppression stay safe pre-commit), `Timeout` -becomes `Timeout { phase: Connect }`, and `Authentication`/`Rejected`/`Other` -are preserved verbatim as `Error::CustomTransport` because Eggfetch has no -evidence of its own about why a provider refused. +with fixed text (provider `message()` is never embedded, so `Auto` fallback +and Alt-Svc suppression stay safe pre-commit without leaking dialer strings), +`Timeout` becomes `Timeout { phase: Connect }`, and +`Authentication`/`Rejected`/`Other` are preserved verbatim as +`Error::CustomTransport` because Eggfetch has no evidence of its own about +why a provider refused (same evidence path as stream `Dialer`). **Not in scope.** Concrete carriers. A MASQUE CONNECT-UDP datagram stream, a process-local UDP socket, and an inter-process channel are all follow-on work. @@ -896,20 +901,27 @@ recovery, safe fallback with monotonic deadlines, draining reconnect, exact observability, and adversarial cases (plaintext/injection/oversized/ stale/cancellation/clear, SNI preservation, one-shot non-replay). -`crates/eggfetch-core/tests/h3_interop_qualification.rs` (20 deterministic loopback controls; -external cases are selected by the qualification runner): mandatory Quinn self-interop, -GET/HEAD, buffered POST upload, 1 MiB streaming download, 20-way -multiplexed concurrency, H3 trailers after EOF, UDP-blackhole -connect-budget termination, bad-then-good non-poisoning, -server-restart reconnect, early-close / mid-response-drop termination -with recovery, prompt cancellation, 100-request reuse soak, -fail/reconnect stabilization, 70-origin boundedness beyond the -64-entry cache, cancellation storms, construction/drop loops, exact -metrics with truthful `None` H3 per-response metadata, IPv6 -capability detection, and a doc-pinned platform-scope check. The external -adapter path can select GET/HEAD, buffered and streaming upload, large -streaming download, trailers, multiplexing and reuse; server-controlled -lifecycle cases remain unsupported unless an adapter can induce them. +`crates/eggfetch-core/tests/h3_interop_qualification.rs` (deterministic loopback controls +mapped to `qualification/http3/corpus.json`; external cases are selected by +`scripts/h3_qualification.py`): mandatory Quinn self-interop, GET/HEAD, buffered +and streaming POST upload, 1 MiB streaming download, 20-way multiplexed +concurrency, H3 trailers after EOF, upload/download cancellation with client +recovery, stream reset / mid-response-drop, graceful connection close and +GOAWAY reconnect (with `h3_reconnected` observability), authenticated +Alt-Svc alternative-port discovery under `Auto { allow_http3: true }`, explicit +IPv4 loopback, UDP-blackhole connect-budget termination, +bad-then-good non-poisoning, server-restart reconnect, 100-request reuse soak, +fail/reconnect stabilization, 70-origin boundedness beyond the 64-entry cache, +cancellation storms, construction/drop loops, exact metrics with truthful `None` +H3 per-response metadata, IPv6 capability detection, and a doc-pinned +platform-scope check. The external adapter path can execute the same generic +endpoint cases plus client-driven cancellation (before headers, during upload, +during download). Server-controlled cases (`stream_reset`, +`graceful_connection_close`, `goaway_reconnect`, `alternative_port`) run only +when the manifest supplies matching `controls` URLs (validated like the main +endpoint); a declared capability without its control URL stays **unsupported** +and does not count as an independent-server pass for that case alone. +HTTP/3 remains **experimental**; this harness does not change that verdict. The implementation-neutral case contract is `qualification/http3/corpus.json`. Adapter manifests must capture an exact @@ -948,6 +960,33 @@ milestone: the required independent and impairment evidence is also absent, so changing versions now would invalidate the completed frozen-tree gates. Any future upgrade must land before a new freeze and requalification. +### Dependency and Upstream-Risk Re-Audit (2026-11-16, M008) + +Current resolved pins from `Cargo.lock` (tree +`f11a46b28df88f43e923d5211f82985784daaf40`; lockfile unchanged by this +audit): + +- `quinn 0.11.11` (`rustls` + `ring` + `runtime-tokio`) +- `quinn 0.11.12`, `quinn-proto 0.11.19`, `quinn-udp 0.5.16` + (RUSTSEC-2026-0523 / 0524 / 0538 floors) +- `h3 0.0.8` with `i-implement-a-third-party-backend-and-opt-into-breaking-changes` + (`ConnectionState::is_closing()` / `is_h3_no_error()` still required for drain) +- `h3-quinn 0.0.10` +- Companions: `rustls 0.23.46`, `tokio-rustls 0.26.4`, `tokio 1.53.3` + +crates.io on 2026-11-16 still has no `h3` newer than 0.0.8 and no +`h3-quinn` newer than 0.0.10. [PR #339](https://github.com/hyperium/h3/pull/339) +remains open, so [issue #338](https://github.com/hyperium/h3/issues/338) +stays a **graduation blocker** with no eggfetch workaround on the +response-header path. [Issue #361](https://github.com/hyperium/h3/issues/361) +remains an open cancellation wire-code limitation (STOP_SENDING during a +pending read). GHSA-6xvm-j4wr-6v98 and RUSTSEC-2026-0523 / 0524 / 0538 are +addressed by the resolved Quinn pins above. A Quinn-only bump does not clear +#338. No fork, vendor, or `[patch]` is introduced. Machine-readable ledger: +`qualification/http3/upstream-risk-ledger.json`. Nested +`qualification/embedded/*/Cargo.lock` graphs are separate evidence trees — +`scripts/check_security.sh` covers the workspace root lock only. + ### Interoperability Evidence (this milestone) - Deterministic loopback Quinn/h3 fixtures are mandatory and green @@ -980,6 +1019,35 @@ Any future upgrade must land before a new freeze and requalification. represented in `qualification/http3/impairment-matrix.json`; execution remains qualification-only and unsupported scenarios stay explicit. +#### H3 impairment runner (qualification-only) + +The matrix is coordinated by `scripts/h3_impairment.py`. Pass a Linux netem +runner that understands the coordinator contract: + +```bash +python scripts/h3_impairment.py \ + --runner scripts/h3_impairment_netem.py \ + --output target/h3-impairment.json +``` + +The runner receives `SCENARIO_ID` and an output path, and sets +`EGGFETCH_H3_IMPAIRMENT_SCENARIO`, `EGGFETCH_H3_IMPAIRMENT_OUTPUT`, and (when +netem is applied) `EGGFETCH_H3_IMPAIRMENT_NETEM_ACTIVE=1` for the matching +`cargo test -p eggfetch-core --test h3_impairment_scenarios` case. + +Privileged Linux (`unshare`/`ip netns`, `tc netem` on loopback) is required for +packet loss, reordering, duplication, jitter, MTU clamp, and mid-transfer path +loss scenarios. macOS and Windows runs record `unsupported` for those rows; that +is **not** graduation evidence and does not count as a completed matrix. Example +fixed loss rates recorded in runner JSON: **1%** (`packet_loss_low`) and **20%** +(`packet_loss_high`). + +Scenarios that use local fixtures only (`udp_blackhole`, `udp_rejected`, +`server_restart`, `first_address_unreachable`, and address-family rows when the +host exposes both families) can produce `pass`/`fail` without netem. Tier 1 runs +only the socket-free contract self-test in `scripts/test_h3_qualification.py`, +not the netem runner. + ### H3 Diagnostics When the `http3` feature is enabled, `Client::transport_metrics()` also @@ -1029,24 +1097,36 @@ the procedure on a frozen SHA. ### Resource and Platform Scope -- Soak coverage is bounded and deterministic: 100 sequential reused-H3 - requests, 10 fail/reconnect cycles, 20-iteration cancellation storms, - 20-iteration construction/drop loops, 70-distinct-origin boundedness, - 20-way multiplexed concurrency, and 1 MiB streaming download. +- **Short controls** (fast Tier 1): 100 sequential reused-H3 requests, 10 + fail/reconnect cycles, 20-iteration cancellation storms, 20-iteration + construction/drop loops, 70-distinct-origin boundedness, 20-way + multiplexed concurrency, and 1 MiB streaming download + (`h3_interop_qualification.rs`). +- **M009 local soak** (same file, `http3` feature): 1 000 sequential reuse, + 50 fail/reconnect cycles (blackhole then good origin), 50 cancellation + timeouts plus 30 partial-body drops then one full recovery, and 100 + client construction/drop loops (one GET each). On Linux, post-warmup + `VmRSS` and open-fd count must stay within a bounded envelope (not exact + equality); other OSes skip numeric sampling and still enforce behavioral + contracts (`h3_connections_created`, diagnostics cap, successful recovery). + `TransportMetrics::h3_diagnostics()` stays at most 64 entries with no + origin hostname, header, or close-reason text in debug output. Long-duration RSS/descriptor soak with allocator-threshold policy - remains extended-tier future work (existing - `resource_monitor`/resource-stabilization conventions apply; no - fragile exact-RSS assertions in H3 tests). + remains extended-tier future work (`eggfetch-bench` `resource_monitor` + stays H1/H2-only). - Fuzz coverage for EggFetch-owned Alt-Svc parsing/state lives in `fuzz/fuzz_targets/fuzz_alt_svc.rs` (header parsing, cache learn/expiry/clear bounds, trust gating, plus suppressor observe/suppress/recover transitions) plus deterministic adversarial unit/integration tests; h3/QPACK internals are not re-fuzzed. -- Platform scope reuses existing CI/package mechanisms (no new matrix): - UDP socket binding, IPv6 availability (capability-detected, never - assumed), certificate stores, timer precision, and address metadata - follow the same policy as the rest of the engine. Lack of a - platform-specific H3 test is not described as support evidence. +- Platform rows record only what was executed on that host. An unexecuted + row is not a failure and is not a support claim. + +| OS | arch | build features | deterministic H3 suites | soak (M009) | IPv6 | impairment (netem) | support evidence? | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Darwin | arm64 | `cargo test -p eggfetch-core --all-features --test h3_interop_qualification` | local corpus + short resource controls in `h3_interop_qualification.rs` (2026-11-16 on developer host) | four M009 soak tests in same target (1k reuse, 50 fail/reconnect, 50+30 cancel/partial-drop, 100 client drop); RSS/fd envelope skipped (no `/proc`) | capability probe only (`ipv6_availability_is_detected_not_assumed`); loopback H3 via IPv4 | not executed (macOS has no netem runner) | local developer evidence only — not product support | +| Linux | x86_64 (ubuntu-latest CI) | `cargo test -p eggfetch-core --all-features` via `./scripts/check.sh` | H3 suites in workspace Tier 1 (including `h3_interop_qualification`) on Stage C freeze `cef0e7aa…` (2026-11-16; M011–M012) | four M009 soak tests; construction/drop uses one reused peer and a 32 MiB Linux `VmRSS` envelope (measured ~21 MiB) | not executed as a separate row | not executed | CI / Tier 1 evidence only — not product support | +| Windows | — | not executed | not executed | not executed | not executed | not executed | no | ### Production Graduation Decision (2026-09-11, re-affirmed 2026-09-12): experimental retained @@ -1078,6 +1158,40 @@ spot checks + impairment/resource + no known corrupting upstream issue features (0-RTT, WebTransport, datagrams, MASQUE, migration) stay separately experimental/unimplemented regardless. +### Production Graduation Decision (2026-11-16, M010): experimental retained + +Ordinary HTTP/3 request/response operation remains **experimental**. +M006–M009 closed the harness, audit, soak, and platform-table +predecessors. The objective gate still fails on operational evidence +rows. Open blockers on this decision: + +1. **Independent servers:** no two non-Quinn servers (ngtcp2/nghttp3, + quiche, quic-go, or MsQuic) passed the corpus through + `scripts/h3_qualification.py` with a private manifest. Local Quinn + corpus coverage is green; that is not independent-server evidence. +2. **Independent drain:** no non-Quinn peer demonstrated + `goaway_reconnect` / stream reset / graceful close via control URLs. +3. **Public origins:** `qualification/http3/public-origin-ledger.json` + records a shortfall (0 of 3 required successful origins). The + historical empty ledger under `plans/` was not overwritten. +4. **Impairment matrix:** `scripts/h3_impairment_netem.py` exists (M007), + but no privileged Linux namespace/netem coordinator run produced an + all-pass matrix on this host (Darwin arm64 → `unsupported`). An + `unsupported` matrix is not graduation evidence. +5. **Upstream:** `qualification/http3/upstream-risk-ledger.json` (M008) + still names h3 #338 / PR #339 as a graduation blocker; #361 stays + outside any supported STOP_SENDING wire-code claim. +6. **Platform claim:** the M009 table has a filled Darwin arm64 developer + row only. No Linux or Windows runtime support claim is made. + +Default version policy is unchanged: `Auto { allow_http3: false }`. +Caller-owned datagram routing, 0-RTT, WebTransport, application +datagrams, MASQUE, and connection migration remain experimental or +unimplemented. CLI and FFI default features do not gain `http3`. +This decision is documentation-only relative to the Stage C binding; +executable-input changes from M006/M007/M009 still require their own +exact-SHA Stage C renewal on the freeze that contains that work. + ### Python API ```python diff --git a/docs/architecture/feature-flags.md b/docs/architecture/feature-flags.md index 0207128b..eb64909f 100644 --- a/docs/architecture/feature-flags.md +++ b/docs/architecture/feature-flags.md @@ -265,7 +265,7 @@ Enables HTTP/3 support over QUIC. When enabled, the client can negotiate HTTP/3 Hardened lifecycle policy (see [core-tls-proxy-protocols.md](core-tls-proxy-protocols.md)): bounded 64-entry per-origin QUIC cache with `OnceCell`-shared init and stale-eviction reconnect, multi-address fallback under one shared connect budget, phase-correct connect/total/read/write timeouts, keepalive-derived QUIC idle (default 30 s), pool-derived stream caps, no transport-level retries, plus separate bounded Alt-Svc cache/suppressor, pre-commit replayable-only safe fallback via `H3DispatchError`, and GOAWAY draining (pinned h3 0.0.8 `is_closing()`/`is_h3_no_error()`). `TransportMetrics::h3_diagnostics()` exposes bounded copied Quinn snapshots for HTTP/3 builds; unavailable stream counts are reported as `None`. Tests: `tests/h3_hardening.rs` + `tests/h3_alt_svc_discovery.rs` + `tests/h3_interop_qualification.rs` (GET/HEAD/upload/streaming/multiplex/trailers/early-close/soak/boundedness) plus unit tests in `transport/http3.rs` + `transport/alt_svc.rs` + `transport/metrics.rs` (loopback only). The implementation-neutral corpus, independent-server runner and qualification-only impairment matrix live in `qualification/http3/` and `scripts/`; external absence is an explicit unsupported result. Fuzz: `fuzz/fuzz_targets/fuzz_alt_svc.rs` (parser/cache + suppressor transitions). Graduation: retained experimental this milestone (see "Production Graduation Decision" in core-tls-proxy-protocols.md). -This feature also carries the experimental caller-owned datagram routing seam (ADR-0007): `ClientBuilder::datagram_dialer` installs a `DatagramDialer`, and every HTTP/3 generation — explicit `Http3Only` or Alt-Svc discovered — is then established over one fixed-target `DatagramRoute` instead of a direct QUIC endpoint. Configuring a dialer creates no direct UDP socket, so a failed or refused route cannot silently downgrade. Eggfetch keeps the whole QUIC/TLS stack; the seam carries datagrams only (no handshake, no certificate material, no QUIC frames), and SNI/certificate validation stay bound to the logical origin. Rust-only: no Python, FFI, or Node exposure. See "Caller-owned datagram routing (experimental)" in [core-tls-proxy-protocols.md](core-tls-proxy-protocols.md); tests: `tests/h3_datagram_route.rs` plus crate-private `transport/datagram` unit tests. +This feature also carries the experimental caller-owned datagram routing seam (ADR-0007): `ClientBuilder::datagram_dialer` installs a `DatagramDialer`, and every HTTP/3 generation — explicit `Http3Only` or Alt-Svc discovered — is then established over one fixed-target `DatagramRoute` instead of a direct QUIC endpoint. Configuring a dialer creates no direct UDP socket, so a failed or refused route cannot silently downgrade. Eggfetch keeps the whole QUIC/TLS stack; the seam carries datagrams only (no handshake, no certificate material, no QUIC frames), and SNI/certificate validation stay bound to the logical origin. `DatagramRoute::recv` returns `(len, source)`; the private bridge drops off-peer sources before feeding Quinn. Connection-kind dial failures map to fixed-text `H3Connect` (provider messages are not embedded). Rust-only: no Python, FFI, or Node exposure. See "Caller-owned datagram routing (experimental)" in [core-tls-proxy-protocols.md](core-tls-proxy-protocols.md); tests: `tests/h3_datagram_route.rs` plus crate-private `transport/datagram` unit tests. ### CLI crate features (`eggfetch-cli`) diff --git a/docs/architecture/threat-model.md b/docs/architecture/threat-model.md index b67fd908..9f09f420 100644 --- a/docs/architecture/threat-model.md +++ b/docs/architecture/threat-model.md @@ -184,8 +184,10 @@ seam as narrow as the contract allows: - **Single fixed peer.** The bridge refuses any transmit whose destination is not the route's reported peer, so a provider cannot redirect a QUIC - connection. Providers are required to reject datagrams from an unverified - source, which is what stops an off-path host injecting packets. + connection. Each `recv` reports the datagram source; the bridge drops any + datagram whose source is not the fixed peer before feeding Quinn (continue + without terminating), so a compromised provider cannot inject off-path UDP + into the stack. - **Eggfetch keeps the crypto.** The bridge builds the QUIC/TLS client configuration. A provider supplies datagrams and never sees the opening handshake, certificate material, or QUIC frames, so it cannot downgrade @@ -198,9 +200,14 @@ seam as narrow as the contract allows: - **No silent downgrade.** Configuring a dialer means no direct QUIC endpoint exists, so a failing or refusing route cannot fall back to a direct UDP socket the caller did not choose. -- **No diagnostic leakage.** The bridge never renders a `DatagramRoute`; - Quinn-facing I/O errors use fixed text, and provider messages are not - re-exposed. Classification uses the typed `DialErrorKind`, never parsed text. +- **No diagnostic leakage on connect-class failures.** The bridge never + renders a `DatagramRoute`; Quinn-facing I/O errors use fixed text; + `DialErrorKind::Connection` maps to `Error::H3Connect` with fixed text that + never embeds `DialError::message()`. Classification uses the typed + `DialErrorKind`, never parsed text. **Exception (intentional, matches stream + `Dialer`):** `Authentication` / `Rejected` / `Other` remain + `Error::CustomTransport` and may surface provider message text as embedder + evidence. - **Bounded termination.** A terminal route I/O error closes the QUIC connection with a transport error, so a dead provider cannot park requests until an idle timeout. diff --git a/docs/reference/compatibility-stage-decision.md b/docs/reference/compatibility-stage-decision.md index b96c2881..99e89229 100644 --- a/docs/reference/compatibility-stage-decision.md +++ b/docs/reference/compatibility-stage-decision.md @@ -5,7 +5,7 @@ The documented asyncio-supported public surfaces for `eggfetch.compat.httpx` (HTTPX 0.28.1) and `eggfetch.compat.httpx2` (HTTPX2 2.12.0) passed Stage C qualification on frozen executable SHA -`6093cc7aa0961194f096cbf2f92c3fc057671a34` (2026-10-31). The full +`cef0e7aa5c23ef92f4a378f370516d9dfbaa466d` (2026-11-16). The full compatibility, extended, package, and live security gates passed on that freeze. Earlier bindings are historical. Current evidence and binding history are in `plans/httpx-parity-correction-status.md`; the exact facade scopes are diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.md index 1929a1b7..a55b533f 100644 --- a/docs/reference/compatibility.md +++ b/docs/reference/compatibility.md @@ -107,7 +107,7 @@ the GIL. ## Qualification status The HTTPX 0.28.1 and HTTPX2 2.12.0 facades are Stage C qualified on frozen -executable SHA `6093cc7aa0961194f096cbf2f92c3fc057671a34` (2026-10-31). The +executable SHA `cef0e7aa5c23ef92f4a378f370516d9dfbaa466d` (2026-11-16). The full compatibility, extended, package, and live security gates passed on that freeze. Earlier bindings are historical. Current evidence is in `plans/httpx-parity-correction-status.md`; exact facade scopes are recorded in diff --git a/docs/residual-differences.md b/docs/residual-differences.md index a3bb5b1a..85aed2d9 100644 --- a/docs/residual-differences.md +++ b/docs/residual-differences.md @@ -1,11 +1,13 @@ # Residual Differences from HTTPX 0.28.1 The HTTPX 0.28.1 and httpx2 2.12.0 facades are Stage C qualified on frozen -executable SHA `6093cc7aa0961194f096cbf2f92c3fc057671a34` (2026-10-31). The -0.3.0 candidate passed CI, extended validation, package validation, and the -live security preflight. Its dependency policy retains the audited Tokio, -zstd and brotli pins; see `docs/architecture/dependency-policy.md`. The prior -`b74cf8919fb691e6bbbd3b6f7b90be29206b2e0f` binding is historical. The full +executable SHA `cef0e7aa5c23ef92f4a378f370516d9dfbaa466d` (2026-11-16). The +M011–M012 security correctives (H3 dial-path trust + qualification hygiene) +passed Tier 1/2/3 and the live security preflight. Its dependency policy +retains the audited Tokio, zstd and brotli pins and carries quinn 0.11.12 / +quinn-proto 0.11.19 / quinn-udp 0.5.16; see +`docs/architecture/dependency-policy.md`. The prior +`8af32d7ca4f1140e266875798522f5da09c17850` binding is historical. The full history of every binding, renewal and supersession is in `plans/httpx-parity-correction-status.md`. The `015a56d7ec3edf186eec8ebccff01cbf5584274e` binding (the coordinated diff --git a/plans/README.md b/plans/README.md index 88169185..c516aa66 100644 --- a/plans/README.md +++ b/plans/README.md @@ -1,11 +1,13 @@ # eggfetch Planning System -> **Current status:** No registered implementation milestone remains open. The -> current release, roadmap statuses, and maintainer actions are tracked in -> `plans/registry.md`. The live Stage C binding is recorded in -> `plans/httpx-parity-correction-status.md` and `compat/*/profile.toml`. Closed -> plans are historical records, not active gates. Validation tiers are in -> `.skills/verification-qualification.md`. +> **Current status:** TLS/protocols M006–M012 closed (H3 **experimental +> retained**). M011–M012 security correctives closed with exact-SHA Stage C +> renewed on `cef0e7aa5c23ef92f4a378f370516d9dfbaa466d`. The current release, +> roadmap statuses, and maintainer actions are tracked in `plans/registry.md`. +> The live Stage C binding is recorded in +> `plans/httpx-parity-correction-status.md` and `compat/*/profile.toml`. +> Closed plans are historical records, not active gates. Validation tiers +> are in `.skills/verification-qualification.md`. ## Pending maintainer actions diff --git a/plans/adrs/ADR-0007-caller-owned-h3-datagram-routing.md b/plans/adrs/ADR-0007-caller-owned-h3-datagram-routing.md index cb5e1630..42a5e5d0 100644 --- a/plans/adrs/ADR-0007-caller-owned-h3-datagram-routing.md +++ b/plans/adrs/ADR-0007-caller-owned-h3-datagram-routing.md @@ -117,6 +117,10 @@ Eggfetch receives two address facts from the established route: - a local socket address used for Quinn endpoint/path bookkeeping; - a physical peer address used as the stable Quinn path peer. +Each successful `recv` also reports the datagram source address. The private +bridge drops any datagram whose source is not the fixed peer before feeding +Quinn (M011). + The physical peer may be a proxy relay rather than the logical origin and MUST NOT be reused as SNI, Host, cookie/auth origin, redirect identity, or certificate-verification identity. Eggfetch retains those logical-origin diff --git a/plans/closure/tls-proxy-protocols/006-h3-server-controlled-corpus.md b/plans/closure/tls-proxy-protocols/006-h3-server-controlled-corpus.md new file mode 100644 index 00000000..ba150c5a --- /dev/null +++ b/plans/closure/tls-proxy-protocols/006-h3-server-controlled-corpus.md @@ -0,0 +1,136 @@ +# TLS, Proxy and Protocols Milestone 006 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/tls-proxy-protocols/006-h3-server-controlled-corpus.md` + +Source subsystem roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-6--server-controlled-h3-corpus` + +Repository baseline reviewed: `f11a46b28df88f43e923d5211f82985784daaf40` + +Implementation commits: + +- `8d599e8402929f5388ed9e1d970833d8f942a52b` — harness and runner changes under + `crates/eggfetch-core/tests/h3_interop_qualification.rs`, + `scripts/h3_qualification.py`, `scripts/test_h3_qualification.py`, + `qualification/http3/servers.example.json`, and architecture docs. + +## 1. Executive finding + +M006 is **closed**. Every corpus id now has a local Quinn/h3 fixture mapped +through `known_local`, the external path executes client-driven cancellation +and optional `controls` URLs, and the Tier 1 runner self-test covers the new +manifest rules. HTTP/3 remains experimental. Independent non-Quinn evidence +is still owned by M010. Exact-SHA Stage C is rebound to +`6b571028767dde4b0a78f36e6ecef525c6d68482`. + +## 2. Requirement-to-evidence matrix + +| Corpus id | Local test | External trigger | Result | +|---|---|---|---| +| `get` | `local_quinn_self_interop_get_and_body` | endpoint | local pass | +| `head` | `h3_head_method_succeeds` | endpoint | local pass | +| `buffered_post` | `h3_post_with_buffered_body_succeeds` | endpoint | local pass | +| `streaming_upload` | `h3_streaming_upload_succeeds` | endpoint | local pass | +| `large_streaming_download` | `h3_large_streaming_download` | endpoint | local pass | +| `response_trailers` | `h3_response_trailers_surface_after_eof` | endpoint | local pass | +| `multiplexed_requests` | `h3_concurrent_multiplexed_requests` | endpoint | local pass | +| `cancellation_before_headers` | `cancellation_during_h3_connect_is_prompt` | client-driven | local pass | +| `cancellation_during_upload` | `h3_cancellation_during_upload_is_prompt` | client-driven | local pass | +| `cancellation_during_download` | `h3_cancellation_during_download_is_prompt` | client-driven | local pass | +| `stream_reset` | `h3_early_close_terminates_and_client_recovers` | `controls.stream_reset` | local pass | +| `graceful_connection_close` | `h3_graceful_connection_close_reconnects` | `controls.graceful_connection_close` | local pass | +| `goaway_reconnect` | `h3_goaway_reconnect_observes_metrics` | `controls.goaway_reconnect` | local pass | +| `connection_reuse` | `hundred_sequential_requests_on_reused_h3_connection` | endpoint | local pass | +| `ipv4` | `h3_ipv4_loopback_get_succeeds` | n/a local | local pass | +| `ipv6` | `ipv6_availability_is_detected_not_assumed` | capability probe | local pass / SKIP | +| `alternative_port` | `h3_alternative_port_via_altsvc` | `controls.alternative_port` | local pass | +| `server_restart` | `server_restart_reconnects_on_next_request` | adapter-specific | local pass | + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Capability without control → unsupported | `scripts/test_h3_qualification.py` | pass | Cannot inflate independent_servers pass | +| Unknown control key rejected | same | pass | ManifestError | +| Control URL hygiene | same | pass | No credentials/query/fragment | +| Experimental label retained | architecture doc | pass | No promotion | +| Stage C renewal | ledger | **pass** | Rebound to `6b571028767dde4b0a78f36e6ecef525c6d68482` | + +## 3. Production implementation evidence + +No production API or route behavior change. Qualification harness only: +path-controlled / shutdown-after-one-response server helpers, Alt-Svc +alternative-port local fixtures, extended external env vars +(`EGGFETCH_H3_INTEROP_CONTROL_*`), and per-case `H3_CORPUS_CASE` parsing. + +## 4. Verification executed + +### Commands run + +```bash +python3 scripts/test_h3_qualification.py +cargo test -p eggfetch-core --all-features --test h3_interop_qualification -- --test-threads=1 +cargo test -p eggfetch-core --all-features --test h3_hardening --test h3_alt_svc_discovery -- --test-threads=1 +python3 scripts/h3_qualification.py --local-only --output target/h3-qualification-local.json +``` + +### Results + +- Self-test: 14 passed +- `h3_interop_qualification`: 31 passed on Darwin arm64 +- `h3_hardening` / `h3_alt_svc_discovery`: green +- Local-only coordinator: every corpus id reports pass; exit 0 +- Workspace Rust tests in `./scripts/check.sh`: green (including new H3 targets) +- Full Tier 1 blocked on this host after Rust by `maturin develop` building an + `x86_64` wheel that the arm64 venv rejects (`not a supported wheel on this + platform`). Host accommodation, not an H3 corpus defect. +- Independent servers: not claimed + +## 5. Invariant review + +`Http3Only` unchanged for generic external cases; `Auto` only for +`alternative_port`. No new public surface. Redaction unchanged. No shell +command in manifests. + +## 6. Failure, timeout, pool, and recovery review + +Cancellation asserts prompt return and a usable client. GOAWAY path +observes `h3_reconnected` / drain metrics without string-matching errors. + +## 7. Compatibility and feature-profile review (incl. exact-SHA binding) + +`http3` feature gate unchanged. Lean/CLI/FFI/Node profiles unchanged. +Executable inputs changed; Stage C renewed on +`6b571028767dde4b0a78f36e6ecef525c6d68482`. Do not cite September H3 freeze +`639bf186…`. + +## 8. Security review + +No new trust-store path. `EGGFETCH_H3_INTEROP_DANGER_ACCEPT_INVALID_CERTS` +remains the only qualification-only cert bypass and stays off by default. + +## 9. Documentation and operations + +Architecture interop paragraph updated. Historical evidence ledgers under +`plans/http3-*` were not edited. `servers.example.json` remains a template. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| — | Stage C rebound | Closed | Exact-SHA binding `6b571028767dde4b0a78f36e6ecef525c6d68482` | +| info | No independent-server run | Expected | M010 operational evidence | + +## 11. Roadmap disposition + +M006 harness complete. M010 still blocked on independent servers for +graduation; this closure does not unblock promotion. + +## 12. Registry updates + +M006 → closed on Stage C binding `6b571028767dde4b0a78f36e6ecef525c6d68482` (harness freeze `8d599e8402929f5388ed9e1d970833d8f942a52b`). Keep H3 experimental gated +future. State that M010 cannot treat local Quinn corpus as independent +interop. diff --git a/plans/closure/tls-proxy-protocols/007-h3-impairment-runner.md b/plans/closure/tls-proxy-protocols/007-h3-impairment-runner.md new file mode 100644 index 00000000..bed769dd --- /dev/null +++ b/plans/closure/tls-proxy-protocols/007-h3-impairment-runner.md @@ -0,0 +1,100 @@ +# TLS, Proxy and Protocols Milestone 007 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/tls-proxy-protocols/007-h3-impairment-runner.md` + +Source subsystem roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-7--h3-impairment-runner` + +Repository baseline reviewed: `f11a46b28df88f43e923d5211f82985784daaf40` + +Implementation commits: + +- _(uncommitted at closure drafting)_ — + `crates/eggfetch-core/tests/h3_impairment_scenarios.rs`, + `scripts/h3_impairment_netem.py`, contract tests in + `scripts/test_h3_qualification.py`, docs + matrix pointer. + +## 1. Executive finding + +M007 is **closed**. The coordinator now has a real Linux netem runner and a +Rust scenario target for all 14 matrix ids. On Darwin arm64 (planning host) +privileged execution is unavailable; the runner records `unsupported` rather +than pass. That is honest and does **not** satisfy M010's impairment row. +Exact-SHA Stage C is rebound to `6b571028767dde4b0a78f36e6ecef525c6d68482`. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Runner callable as `--runner scripts/h3_impairment_netem.py` | script + coordinator contract | pass | | +| 14 scenario tests named as matrix ids | `h3_impairment_scenarios.rs` | pass | Unselected → skip | +| Contract self-test socket-free | `test_h3_qualification.py` | pass | Wired into Tier 1 path | +| Privileged Linux full matrix | not executed | **not executed** | Host: Darwin arm64; missing netns/tc privileges | +| Quinn peer impairment ≠ independent interop | this record | pass | Explicit | +| Stage C | ledger | **pass** | Rebound to `6b571028767dde4b0a78f36e6ecef525c6d68482` | + +## 3. Production implementation evidence + +None. Impairment stays outside `eggfetch-core`. No production feature flag. + +## 4. Verification executed + +### Commands run + +```bash +python3 scripts/test_h3_qualification.py +cargo test -p eggfetch-core --all-features --test h3_impairment_scenarios -- --test-threads=1 +cargo test -p eggfetch-core --all-features --test h3_hardening -- --test-threads=1 +python3 scripts/h3_impairment_netem.py packet_loss_low /tmp/h3-imp-packet_loss_low.json +``` + +### Results + +- Contract + unselected scenario cargo tests: pass +- macOS runner: `unsupported` with reason naming Darwin / missing capability +- Privileged Linux coordinator JSON: **not executed** + +## 5. Invariant review + +`Http3Only` never falls back in blackhole scenarios. Auto fallback only +pre-commit for replayable bodies. Core does not learn netem. + +## 6. Failure, timeout, pool, and recovery review + +Scenarios that name deadlines use Timeout budgets that fail closed on hang. +Cancellation uses existing drop/abort paths. + +## 7. Compatibility and feature-profile review (incl. exact-SHA binding) + +`http3`-gated test only. Stage C rebound. macOS `unsupported` is not a +client failure. + +## 8. Security review + +Certificate material stays in test fixtures. Runner does not disable +production certificate verification. + +## 9. Documentation and operations + +Architecture doc documents runner invocation, privileges, 1%/20% loss +rates, and that `unsupported` ≠ graduation evidence. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| high (for M010) | Privileged Linux matrix not run | M010 impairment row open | Operator Linux netem run | +| — | Stage C rebound | Closed | Exact-SHA binding `6b571028767dde4b0a78f36e6ecef525c6d68482` | + +## 11. Roadmap disposition + +Harness landed. M010 impairment evidence still open until Linux pass. + +## 12. Registry updates + +M007 → closed. Note Darwin unsupported vs Linux pending for graduation. diff --git a/plans/closure/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md b/plans/closure/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md new file mode 100644 index 00000000..9ecfd589 --- /dev/null +++ b/plans/closure/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md @@ -0,0 +1,99 @@ +# TLS, Proxy and Protocols Milestone 008 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md` + +Source subsystem roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-8--h3-upstream-risk-re-audit` + +Repository baseline reviewed: `f11a46b28df88f43e923d5211f82985784daaf40` + +Implementation commits: + +- _(docs/ledger only; lockfile unchanged)_ — + `qualification/http3/upstream-risk-ledger.json` and architecture + dependency re-audit paragraph dated 2026-11-16. + +## 1. Executive finding + +M008 is **closed** on the no-upgrade path. crates.io on 2026-11-16 still +publishes `h3` 0.0.8 and `h3-quinn` 0.0.10 only. [h3 #338](https://github.com/hyperium/h3/issues/338) +and [PR #339](https://github.com/hyperium/h3/pull/339) remain open, so #338 +is recorded as a graduation blocker. No fork or vendored patch was +introduced. A docs-and-ledger-only close does not change executable inputs +and does not require a new Stage C freeze. M010 cannot clear the upstream +row until a published release contains the frame-drain fix. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Resolve current graph | ledger `resolved_versions` | pass | quinn 0.11.11 / quinn-proto 0.11.18 / h3 0.0.8 / h3-quinn 0.0.10 | +| Re-read #338/#339/#361/#352/#353 | ledger `issues` + fetch date | pass | All open on 2026-11-16 | +| Disposition per issue | ledger | pass | #338/#339/#361 graduation blocker; #352/#353 proven not reachable for ordinary client success path | +| No-upgrade when no published fix | lockfile unchanged | pass | | +| GHSA-6xvm-j4wr-6v98 | quinn-proto 0.11.18 ≥ 0.11.14 | pass | Proven not reachable on this pin | +| No `[patch]` / vendor / git dep | tree inspection | pass | | +| Experimental label retained | docs | pass | | +| Stage C | n/a | pass | Docs/ledger only | + +## 3. Production implementation evidence + +None. Drain still uses h3 0.0.8 `is_closing()` / `is_h3_no_error()` under +the unstable feature; comment remains accurate. + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggfetch-core --all-features --test h3_hardening --test h3_alt_svc_discovery --test h3_interop_qualification --test h3_datagram_route -- --test-threads=1 +``` + +### Results + +H3 suites green on audited pins. No dependency bump. + +## 5. Invariant review + +No second QUIC stack. 0-RTT still disabled. No default-on H3. + +## 6. Failure, timeout, pool, and recovery review + +Unchanged. Cancellation tests keep asserting client usability, not +STOP_SENDING wire codes (#361). + +## 7. Compatibility and feature-profile review (incl. exact-SHA binding) + +No executable change. Current Stage C SHA is not invalidated by this +milestone alone. M006/M007/M009 changes elsewhere still require renewal. + +## 8. Security review + +Advisory GHSA-6xvm-j4wr-6v98 checked against resolved `quinn-proto`. +Certificate verification retry rules untouched. + +## 9. Documentation and operations + +New dated architecture paragraph. Historical 2026-09-11 paragraph kept. +Ledger path: `qualification/http3/upstream-risk-ledger.json`. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| high (graduation) | #338/#339 unreleased | M010 upstream row fails | Wait for published h3 with frame drain | +| medium | #361 open | No conformant cancel wire-code claim | Keep outside supported cancellation claim | + +## 11. Roadmap disposition + +M008 closed. External evidence for M010 must cite post-audit pins (same +lockfile today). + +## 12. Registry updates + +M008 → closed. M010 upstream blocker remains named. diff --git a/plans/closure/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md b/plans/closure/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md new file mode 100644 index 00000000..ff023528 --- /dev/null +++ b/plans/closure/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md @@ -0,0 +1,98 @@ +# TLS, Proxy and Protocols Milestone 009 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md` + +Source subsystem roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-9--h3-resource-soak-and-platform-scope` + +Repository baseline reviewed: `f11a46b28df88f43e923d5211f82985784daaf40` + +Implementation commits: + +- _(uncommitted at closure drafting)_ — soak tests in + `h3_interop_qualification.rs` and platform table in + `docs/architecture/core-tls-proxy-protocols.md`. + +## 1. Executive finding + +M009 is **closed**. Deterministic soak counts (1 000 reuse, 50 +fail/reconnect, 50+30 cancel/partial-drop, 100 client drop) are enforced +in-tree. Darwin arm64 filled one platform-table row as local developer +evidence only — not product support. Linux RSS/fd envelope is implemented +and skipped on macOS. Exact-SHA Stage C is rebound to +`6b571028767dde4b0a78f36e6ecef525c6d68482`. HTTP/3 remains experimental. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| 1 000 sequential reuse | `thousand_sequential_requests_on_reused_h3_connection` | pass | | +| Extended fail/reconnect | `fifty_repeated_fail_reconnect_cycles_do_not_grow_state_soak` | pass | 50 cycles | +| Cancel + partial drop storm | `extended_cancellation_and_partial_drop_storm_leaves_client_usable` | pass | | +| Construction/drop loop | `hundred_client_construction_drop_loops_do_not_leak_soak` | pass | 100 | +| Diagnostics ≤ 64, redacted | `assert_h3_diagnostics_bounded_and_redacted` | pass | | +| Platform table | architecture doc | pass | Darwin filled; Linux/Windows not executed | +| Stage C | ledger | **pass** | Rebound to `6b571028767dde4b0a78f36e6ecef525c6d68482` | + +## 3. Production implementation evidence + +None expected. No public metrics API added. No `ResponseBody` change. + +## 4. Verification executed + +### Commands run + +```bash +cargo test -p eggfetch-core --all-features --test h3_interop_qualification thousand_sequential -- --test-threads=1 +cargo test -p eggfetch-core --all-features --test h3_interop_qualification soak -- --test-threads=1 +cargo test -p eggfetch-core --all-features --test h3_interop_qualification extended_cancellation -- --test-threads=1 +``` + +### Results + +All new soak filters pass on Darwin arm64. Numeric RSS/fd skipped (no +`/proc`). Short controls still pass. + +## 5. Invariant review + +Cache and diagnostics remain capped at 64. No exact RSS equality. +Experimental label retained. + +## 6. Failure, timeout, pool, and recovery review + +Uses existing H3 timeout/cancel paths. Fail/reconnect does not poison a +different origin. + +## 7. Compatibility and feature-profile review (incl. exact-SHA binding) + +Tests behind `http3` only. Stage C rebound. + +## 8. Security review + +Diagnostics redaction asserted. No new secret surfaces. + +## 9. Documentation and operations + +Platform table and soak counts documented under Resource and Platform +Scope. Graduation section not rewritten by this milestone. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| — | Stage C rebound | Closed | Exact-SHA binding `6b571028767dde4b0a78f36e6ecef525c6d68482` | +| info | Only Darwin row filled | Support wording limits | M010 may add rows when executed | + +## 11. Roadmap disposition + +Soak + table ready for M010 citation. Additional OS rows remain M010 +operational evidence. + +## 12. Registry updates + +M009 → closed. diff --git a/plans/closure/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md b/plans/closure/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md new file mode 100644 index 00000000..c1d12338 --- /dev/null +++ b/plans/closure/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md @@ -0,0 +1,122 @@ +# TLS, Proxy and Protocols Milestone 010 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md` + +Source subsystem roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-10--ordinary-h3-graduation-decision` + +Repository baseline reviewed: `f11a46b28df88f43e923d5211f82985784daaf40` + +Implementation commits: + +- _(documentation decision)_ — dated graduation section in + `docs/architecture/core-tls-proxy-protocols.md`; + `qualification/http3/public-origin-ledger.json` shortfall record. + No production code change. + +## 1. Executive finding + +M010 is **closed with experimental retained**. Predecessors M006–M009 +landed their harnesses, ledger, soak, and platform table. The ordinary +HTTP/3 gate does **not** pass: independent non-Quinn servers, privileged +impairment, public origins, and upstream #338 remain open. A retained +experimental label is the successful close for this evidence state. +`Auto { allow_http3: false }` stays the default. Datagram routing and +advanced QUIC features stay experimental/unimplemented. Long-term +specification documents (`plans/000`–`002`) were not edited. + +Recommendation: **closed with experimental retained**. + +## 2. Requirement-to-evidence matrix + +| Gate row | Evidence | Result | Notes | +|---|---|---|---| +| Deterministic hardening / Alt-Svc / lifecycle / soak | M006–M009 suites on this tree | pass (local) | Darwin arm64 | +| Two independent non-Quinn servers | private manifest run | **fail / missing** | Not supplied | +| Independent drain / reset / graceful close | control URLs on non-Quinn peer | **fail / missing** | Not supplied | +| Public ledger ≥ 3 successes | `qualification/http3/public-origin-ledger.json` | **shortfall** | 0 of 3 | +| Impairment matrix all-pass | privileged Linux netem | **not executed** | Darwin → unsupported | +| Upstream no corrupting ordinary-response issue | `qualification/http3/upstream-risk-ledger.json` | **blocker** | #338/#339 open | +| #361 fixed or outside cancel claim | ledger + docs | pass (scoped out) | Wire-code claim excluded | +| Platform table matches support wording | M009 table | pass | Only Darwin developer row; no support claim | +| Tier 1 | `./scripts/check.sh` | pending on freeze | Executable inputs from M006/M007/M009 | +| Stage C | docs-only decision | unchanged by M010 | Predecessors still need renewal | + +## 3. Production implementation evidence + +None. Documentation decision only. + +## 4. Verification executed + +### Commands run + +```bash +python3 scripts/test_h3_qualification.py +cargo test -p eggfetch-core --all-features --test h3_hardening --test h3_alt_svc_discovery --test h3_interop_qualification --test h3_datagram_route --test h3_impairment_scenarios -- --test-threads=1 +``` + +Independent-server and privileged impairment commands were **not** run +(no private non-Quinn manifests; no Linux netns on this host). + +### Results + +Deterministic suites green locally. Gate operational rows open as named +above. + +## 5. Invariant review + +Missing evidence not treated as pass. No second H3 stack. No default +`allow_http3: true`. CLI/FFI defaults unchanged. ADR-0008 fail-closed +semantics unchanged. + +## 6. Failure, timeout, pool, and recovery review + +Unchanged. No product defect found that required a corrective plan stop +beyond the already-recorded upstream blocker. + +## 7. Compatibility and feature-profile review (incl. exact-SHA binding) + +Docs-only decision keeps the current Stage C binding for this milestone. +Executable changes from M006/M007/M009 still require their conditional +Stage C renewal and must not be cited as Stage C green until rebound. + +## 8. Security review + +No new trust or redaction surface. Public-origin ledger contains no host +names (empty shortfall). + +## 9. Documentation and operations + +New dated section +`### Production Graduation Decision (2026-11-16, M010): experimental retained`. +Feature-flag / README / compatibility tables were **not** rewritten to +claim support. Historical September evidence files were not overwritten. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| high | Independent servers absent | Blocks support label | Operator private manifest + two stacks | +| high | #338 open | Blocks support label | Published h3 with #339 | +| high | Impairment not passed on Linux | Blocks support label | Privileged netem run | +| high | Public origins shortfall | Blocks support label | Three unrelated CDN/operator checks | +| medium | M006/M007/M009 Stage C | Publication of this tree | Freeze + Tier 2/3 + HTTPX | + +## 11. Roadmap disposition + +Ordinary H3 graduation remains a gated future. Re-open a new decision +milestone only when the open rows above can be filled on one SHA after +an M008-style audit of the pins under test. Do not amend `plans/000` +until a future passing gate. + +## 12. Registry updates + +M010 → closed (experimental retained). Gated-future line stays: H3 +experimental until a later passing decision. Remove M010 from blocked +implementation plans; record open operational blockers under Operational +blockers. diff --git a/plans/closure/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md b/plans/closure/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md new file mode 100644 index 00000000..59f342fa --- /dev/null +++ b/plans/closure/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md @@ -0,0 +1,62 @@ +# TLS, Proxy and Protocols Milestone 011 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md` + +Source subsystem roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-11--h3-dial-error-sanitization-and-datagram-recv-trust` + +Repository baseline reviewed: `8af32d7ca4f1140e266875798522f5da09c17850` + +## 1. Executive finding + +M011 is closed. Connection-kind dialer failures map to fixed-text +`Error::H3Connect` (`QUIC handshake failed`) without embedding +`DialError::message()`. `DatagramRoute::recv` now reports `(len, source)`; +the private Quinn bridge drops off-peer datagrams before enqueueing and +continues without terminating the route. Authentication / Rejected / Other +remain `CustomTransport` with provider text, matching stream `Dialer`. +H3 stays experimental; no adapter exposure of the dialer. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Connection H3Connect never embeds provider text | `connection_dial_errors_never_reexpose_provider_text`; `route_dial_error` / `route_error_override` | pass | Secret URL/password absent from Display/Debug | +| Recv source checked in bridge | `foreign_source_datagrams_are_dropped_before_quinn` | pass | Drop + continue | +| Existing datagram suites | `h3_datagram_route` (16) + `datagram::tests` (9) | pass | | +| Threat model aligned | `docs/architecture/threat-model.md` § Malicious Datagram Route | pass | CustomTransport exception documented | +| Public shapes / no Quinn leak | traits unchanged in name; recv success type refined to include `SocketAddr` | pass | Experimental Rust-only; oracle `all-features.txt` updated | +| Stage C | exact-SHA renewal after executable change | pass | Bound to `cef0e7aa5c23ef92f4a378f370516d9dfbaa466d` with M012 | + +## 3. Production implementation evidence + +- `crates/eggfetch-core/src/transport/http3.rs` — `H3_ROUTE_CONNECT_TEXT` +- `crates/eggfetch-core/src/transport/datagram.rs` — recv `(len, source)` + peer check +- Docs: threat-model, core-tls-proxy-protocols, feature-flags +- `compat/rust-public-api/all-features.txt` — `DatagramRecvFuture` Output update + +## 4. Verification executed + +```bash +cargo test -p eggfetch-core --all-features --lib -- datagram:: --test-threads=1 +cargo test -p eggfetch-core --all-features --test h3_datagram_route -- --test-threads=1 +./scripts/check.sh # Tier 1 (shared with M012) +``` + +## 5–10. Reviews + +Invariants held: no direct-UDP fallback; Auth/Rejected/Other evidence path +unchanged; bounded queues; H3 experimental. No ResponseBody change. +Compatibility: intentional fixed `H3Connect` text for Connection; recv +return type is an experimental Rust-only breaking refinement (SocketAddr +already on the surface via `peer_addr`). + +## 11. Closure recommendation + +**Closed.** Stage C SHA rebound on shared freeze +`cef0e7aa5c23ef92f4a378f370516d9dfbaa466d`. diff --git a/plans/closure/tls-proxy-protocols/012-h3-qualification-security-hygiene.md b/plans/closure/tls-proxy-protocols/012-h3-qualification-security-hygiene.md new file mode 100644 index 00000000..9003a3d6 --- /dev/null +++ b/plans/closure/tls-proxy-protocols/012-h3-qualification-security-hygiene.md @@ -0,0 +1,61 @@ +# TLS, Proxy and Protocols Milestone 012 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/tls-proxy-protocols/012-h3-qualification-security-hygiene.md` + +Source subsystem roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-12--h3-qualification-security-hygiene` + +Repository baseline reviewed: `8af32d7ca4f1140e266875798522f5da09c17850` + +## 1. Executive finding + +M012 is closed. The H3 upstream-risk ledger Quinn pins match workspace +`Cargo.lock` (0.11.12 / 0.11.19 / 0.5.16) with RUSTSEC-2026-0523 / 0524 / +0538 dispositions recorded; #338 remains a graduation blocker. Embedded +reqwest qualification locks were refreshed to the same Quinn floors. +Netem `scenario_id` is charset-validated before any shell use. Cert-bypass +help text remains opt-in / non-evidence. No production runtime change. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Ledger Quinn pins match workspace | `qualification/http3/upstream-risk-ledger.json` | pass | Before: 0.11.11/0.11.18/0.5.15 → After: 0.11.12/0.11.19/0.5.16 | +| Advisories for Quinn bump | ledger `advisories[]` | pass | 0523/0524/0538 + prior 0037 | +| #338 not waived | ledger issues + decision_summary | pass | still graduation blocker | +| Embed locks refreshed | `qualification/embedded/reqwest-{json,min}/Cargo.lock` | pass | same Quinn floors | +| Nested locks ≠ root scan | embed README + architecture note | pass | | +| scenario_id charset | `validate_scenario_id`; `test_scenario_id_charset_rejected_before_shell_use` | pass | | +| Cert-bypass opt-in warning | `h3_qualification.py --help` text | pass | | +| Runner self-test | `python scripts/test_h3_qualification.py` | pass | 15 tests | + +## 3. Before/after ledger pin table + +| Package | Before | After (workspace) | +|---|---|---| +| quinn | 0.11.11 | 0.11.12 | +| quinn-proto | 0.11.18 | 0.11.19 | +| quinn-udp | 0.5.15 | 0.5.16 | + +## 4. Verification executed + +```bash +python scripts/test_h3_qualification.py +./scripts/check.sh +./scripts/check_security.sh # with Stage C +``` + +## 5–10. Reviews + +No CI expansion. No production TLS bypass. rustix informational allow +unchanged. #338 disposition unchanged. + +## 11. Closure recommendation + +**Closed.** Paired with M011 on exact-SHA Stage C freeze +`cef0e7aa5c23ef92f4a378f370516d9dfbaa466d`. diff --git a/plans/httpx-parity-correction-status.md b/plans/httpx-parity-correction-status.md index 8d106bd3..8257952a 100644 --- a/plans/httpx-parity-correction-status.md +++ b/plans/httpx-parity-correction-status.md @@ -4,6 +4,94 @@ This record is the exact-SHA-bound status for the HTTPX 0.28.1 compatibility facade. Historical phase and corrective-pass records remain in the git history and referenced plans; counts below are only from the runs named here. +## Stage C renewed after M011–M012 security correctives (2026-11-16) + +Both documented facades are **Stage C qualified (renewal)** on executable +freeze `cef0e7aa5c23ef92f4a378f370516d9dfbaa466d`. The preceding live binding +`8af32d7ca4f1140e266875798522f5da09c17850` is historical because M011–M012 +changed executable inputs: fixed-text `H3Connect` for Connection-kind dial +errors, bridge-side off-peer datagram drops (`DatagramRoute::recv` reports +source), ledger/embed Quinn pin refresh, and netem `scenario_id` charset +validation. Quinn pins remain **0.11.12** / quinn-proto **0.11.19** / +quinn-udp **0.5.16**. The M008 h3/h3-quinn no-upgrade disposition for #338 is +unchanged. Profile and ledger edits after this freeze are documentation only. + +H3 stays experimental. This renewal is not an H3 graduation claim. M011–M012 +are closed on this freeze. + +### Qualification evidence + +| Gate | Result | +|---|---| +| Tier 1 | `./scripts/check.sh` exit 0 on the freeze under Rosetta (Python behavior **581 passed**). | +| Tier 2 | Full extended gates exit 0 under Rosetta x86_64 / Python 3.14.2. Both compatibility profiles **2082 passed, 1 skipped** (optional `google.genai` construction fixture left uninstalled: current SDK uses `SyncHttpx2Client`, so the `httpx.Client` isinstance check fails; skip-audit text prints FAIL but does not change pytest's exit status). API oracle clean for both facades. Rust public-API oracle **8 profiles**; `cargo-semver-checks` **"no semver update required"**. Lifecycle **49 passed**; soak **11 passed**; downstream **4/4 required packages** with `overall_pass: true`. | +| Resource monitor | **52.42 MB peak / 49.07 MB delta** against 100 MB peak / 64 MB delta limits. | +| Tier 3 package gate | `./scripts/check.sh package` exit 0. Release wheel built; wheel smoke, content validation, and installed-wheel typing smoke passed (local wheel is x86_64/Rosetta). | +| Live security preflight | `./scripts/check_security.sh` exit 0 — `advisories ok, bans ok, licenses ok, sources ok`. The `rustix` unsound warning (RUSTSEC-2026-0486) is allowed/informational. | +| Criterion | Completed; informational only (no failure threshold). | + +### Host accommodations + +- Qualification used `.venv-qual` on healthy Python **3.14.2** x86_64. The + project `.venv`'s python.org 3.11.9 base lacks `int.is_integer`, which + falsely fails the HTTPX `codes` API-oracle comparison against the frozen + reference manifest. +- Shell and build are Rosetta `x86_64` (`RUSTUP_TOOLCHAIN=stable-x86_64-apple-darwin`, + `CARGO_BUILD_JOBS=6`, `CARGO_INCREMENTAL=0`). `CARGO_TARGET_DIR` must be + unset so `./target/release/resource_monitor` matches `check.sh`. PATH must + include `/usr/sbin` so compat FD-stability tests can invoke `lsof`. +- `SSL_CERT_FILE` / `REQUESTS_CA_BUNDLE` / `CURL_CA_BUNDLE` pointed at certifi + because the macOS trust store on this host is empty for the python.org + builds. +- Downstream artifact produced via `scripts/build_downstream_artifact.py`. +- Optional SDK construction: `openai` and `ollama` installed and passed; + `google-genai` omitted (API drift). Anthropic stays pinned at `0.87.0`. + +### The condition for the next renewal + +Unchanged: any change to executable inputs invalidates this binding and +requires a fresh exact-SHA qualification, with the downstream artifact +manifest re-supplied for that run. + +--- + +## Stage C renewed after Linux H3 soak CI fixes (2026-11-16) + +> **Historical.** Live binding moved to `cef0e7aa…` after M011–M012. + +Both documented facades were **Stage C qualified (renewal)** on executable +freeze `8af32d7ca4f1140e266875798522f5da09c17850`. The preceding live binding +`6b571028767dde4b0a78f36e6ecef525c6d68482` is historical because ubuntu-latest +Tier 1 failed on `hundred_client_construction_drop_loops_do_not_leak_soak` +(VmRSS envelope) and executable test fixes followed: reuse one Quinn peer for +construction/drop, widen the Linux construction/drop `VmRSS` envelope to +32 MiB from measured ~21 MiB retention, and a clippy `doc_markdown` fix. +Quinn pins remain **0.11.12** / quinn-proto **0.11.19** / quinn-udp **0.5.16**. +The M008 h3/h3-quinn no-upgrade disposition for #338 is unchanged. + +H3 stays experimental. This renewal is not an H3 graduation claim. Security +audit correctives were registered as TLS/protocols M011–M012 (implemented on +the successor freeze). + +--- + +## Stage C renewed for M006–M010 H3 harness + Quinn RustSec patch (2026-11-16) + +> **Historical.** Live binding moved to `8af32d7c…` after Linux soak CI fixes. + +Both documented facades were **Stage C qualified (renewal)** on executable +freeze `6b571028767dde4b0a78f36e6ecef525c6d68482`. The preceding live binding +`6093cc7aa0961194f096cbf2f92c3fc057671a34` is historical because executable +inputs changed: M006–M010 added H3 qualification harnesses (corpus, impairment +coordinator, soak/platform table, upstream-risk ledger, graduation decision +with experimental retained) on `8d599e8402929f5388ed9e1d970833d8f942a52b`, and +the live security preflight then failed on newly published Quinn advisories, so +the tree was re-frozen at `6b571028…` with quinn **0.11.12**, quinn-proto +**0.11.19**, and quinn-udp **0.5.16** (RUSTSEC-2026-0523 / 0524 / 0538). The +M008 h3/h3-quinn no-upgrade disposition for #338 is unchanged. + +H3 stays experimental. This renewal is not an H3 graduation claim. + ## Release candidate qualification — 0.3.0 (2026-10-31) The release executable tree is frozen at diff --git a/plans/implementation/tls-proxy-protocols/006-h3-server-controlled-corpus.md b/plans/implementation/tls-proxy-protocols/006-h3-server-controlled-corpus.md new file mode 100644 index 00000000..d29a3702 --- /dev/null +++ b/plans/implementation/tls-proxy-protocols/006-h3-server-controlled-corpus.md @@ -0,0 +1,320 @@ +# TLS, Proxy, and Protocols Milestone 006 — Server-Controlled H3 Corpus + +Status: closed + +Repository baseline: `f11a46b28df88f43e923d5211f82985784daaf40` + +Source roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-6--server-controlled-h3-corpus` + +Long-term requirements: + +- `plans/000-long-term-specification.md` §3 (production HTTP/3 remains gated on the evidence gate) +- `plans/001-terminology-and-domain-model.md` §6–§7 +- `plans/002-long-term-roadmap.md` Phase 4 item 2 + +Applicable ADRs: + +- `plans/adrs/ADR-0001-single-engine-thin-adapters.md` +- `plans/adrs/ADR-0003-exact-sha-stage-c-binding.md` +- `plans/adrs/ADR-0007-caller-owned-h3-datagram-routing.md` + +Primary class: infrastructure + +## 1. Objective + +Make every required ordinary-client HTTP/3 corpus case executable, with an +explicit pass, fail, or unsupported result, against the local Quinn/h3 +control and against an optional external server that declares the case. + +This milestone builds the missing qualification harness. It does not collect +independent-server evidence and it does not change the experimental label. + +## 2. Why this milestone is ready + +The corpus, coordinator, and local control suite already exist. The gap is +narrow and local: + +- `qualification/http3/corpus.json` lists 18 required cases. +- `scripts/h3_qualification.py` runs one local test target and then one + external test, `external_h3_interop_servers_if_configured`. +- The external path only executes eight generic endpoint cases (`get`, + `head`, `buffered_post`, `streaming_upload`, `large_streaming_download`, + `response_trailers`, `multiplexed_requests`, `connection_reuse`). +- Server-controlled cases (`stream_reset`, `graceful_connection_close`, + `goaway_reconnect`, `alternative_port`, and the three cancellation cases) + are recorded `unsupported` even when a manifest lists them. +- The local mapper has no fixture for `streaming_upload`, + `cancellation_during_upload`, `cancellation_during_download`, + `graceful_connection_close`, `goaway_reconnect`, `ipv4`, or + `alternative_port`, so a green local suite still reports those corpus ids + unsupported. +- GOAWAY draining is already implemented and covered against a local server + in `h3_alt_svc_discovery.rs` (`graceful_close_does_not_deadlock_and_reconnects`). + That evidence is not wired into the corpus runner, and it is not an + independent-server result. + +No new architecture is required. The production H3 route, Alt-Svc cache, +fallback rules, and `Http3Only` strictness stay as they are. Historical +plans under `plans/http3-*.md` stay frozen records; this file is the active +handoff. + +M008 may later change the Quinn/h3 pins. External evidence is collected only +in M010, after M008 closes, so this harness can land in parallel with the +audit. + +## 3. Current implementation evidence + +At the baseline: + +- local controls live in `crates/eggfetch-core/tests/h3_interop_qualification.rs` + and are selected by `scripts/h3_qualification.py` `known_local`; +- the external test reads `EGGFETCH_H3_INTEROP_ENDPOINT` and + `EGGFETCH_H3_INTEROP_CASES` and speaks `Http3Only`; +- `EGGFETCH_H3_INTEROP_DANGER_ACCEPT_INVALID_CERTS` is the only + qualification-only certificate bypass, and it is opt-in; +- `scripts/test_h3_qualification.py` is the Tier 1 runner self-test and + makes no network connection; +- the September evidence ledger records zero independent-server passes. + Do not edit that ledger. + +## 4. Invariants that must not regress + +- `eggfetch-core` remains the only HTTP/3 implementation. Adapters and + qualification scripts do not open their own QUIC sockets. +- `Http3Only` never falls back. `Auto { allow_http3: true }` falls back only + under the existing pre-commit, replayable-body rules. +- One-shot and non-replayable bodies are never duplicated. +- Absence of an external server is `unsupported` or an explicit skip. It is + never a pass and never a Tier 1 failure. +- The experimental label stays. This milestone does not edit the production + graduation paragraph except to point operators at the new harness where + the architecture doc describes the corpus runner. +- Caller-owned datagram routing stays experimental and Rust-only. +- `0-RTT` stays disabled. +- No new public engine type, method, or feature flag. +- Redaction of `authorization`, `proxy-authorization`, `cookie`, and + `set-cookie` is unchanged. +- The runner does not shell out to a command supplied by the manifest. + +## 5. Scope + +### In scope + +- Local Quinn/h3 fixtures and corpus-runner mappings for every corpus id + that can be induced by the client or by the in-process test server. +- Optional manifest `controls` URLs for the cases an external peer must + induce, validated with the same endpoint rules as the main URL. +- External execution of client-driven cancellation without a server-side + control channel. +- Runner self-tests that reject a manifest which claims a server-controlled + case without a control URL, and that still reject credentials and query + strings. + +### Explicitly out of scope + +- Standing up ngtcp2, quiche, quic-go, or any public origin. That execution + is M010. +- The impairment matrix and its netem runner. That is M007. +- Upgrading `h3`, `h3-quinn`, or `quinn`. That is M008. +- Removing the experimental label, enabling H3 by default, or enabling + `http3` in the CLI or FFI default features. +- A manifest field that names a restart shell command. +- WebTransport, MASQUE, QUIC migration, application datagrams, and 0-RTT. + +## 6. Required production changes + +No production behavior change is expected. If a fixture shows that GOAWAY +draining, cancellation, or reset handling is wrong, stop and record the +defect. Do not widen this milestone into a transport rewrite. A narrow +regression fix is allowed only when an existing local test already defines +the contract and the new fixture caught a break in that contract. + +## 7. Ordered work packages + +1. Extend the local interop server in `h3_interop_qualification.rs` so one + process can serve the ordinary corpus and three controlled behaviors: + - reset the response stream after response headers or mid-body; + - complete one response and then graceful-close the connection; + - advertise an authenticated Alt-Svc `h3` alternative on a second local + port and serve that port. + Keep the server loopback-only. Reuse the existing self-signed test + certificate pattern already in that file. +2. Add named tests, and map them from `known_local`, for the corpus ids that + currently have no local fixture: + - `streaming_upload` — one streaming request body is sent once and the + response completes; + - `cancellation_before_headers`, `cancellation_during_upload`, + `cancellation_during_download` — cancellation returns promptly, the + client stays usable, and a later request on the same client succeeds; + - `graceful_connection_close` — the in-flight response completes or + returns the real connection error, and the next request reconnects; + - `goaway_reconnect` — after the controlled close, the next request is + counted in `TransportMetrics` `h3_reconnected` and succeeds; + - `alternative_port` — `Auto { allow_http3: true }` learns the Alt-Svc + entry and the following eligible request uses H3 on the alternative + port, with origin identity unchanged; + - `ipv4` — the loopback IPv4 fixture succeeds. `ipv6` stays the existing + capability-detection test and must not start failing on a host without + IPv6. + `server_restart` keeps its existing local test. Do not add an external + restart command. +3. Teach `external_h3_interop_servers_if_configured` the client-driven + cases. Cancellation must be initiated by the client: drop the request + before reading headers, cancel an upload the client has not finished, + and abandon a download after the first chunk when the body is large + enough to still be open. A later request on the same client must + succeed. Do not require the peer to stall. +4. Add an optional `controls` object on each server manifest entry: + - `stream_reset`: HTTPS URL that aborts the response stream; + - `graceful_connection_close`: HTTPS URL that completes one response and + then closes the connection; + - `goaway_reconnect`: HTTPS URL that completes one response and then + sends a graceful GOAWAY or equivalent connection close. The following + request uses the manifest `endpoint` on the same origin and must + succeed with `h3_reconnected` increased; + - `alternative_port`: HTTPS discovery URL that returns an authenticated + Alt-Svc `h3` entry for a different port on the same authority. The + following request uses the manifest endpoint in `Auto { allow_http3: + true }` mode. + Validate every control URL with the existing endpoint rules: `https`, + hostname, no userinfo, no query, no fragment. A capability listed in + `capabilities` that needs a control is `unsupported` when the control + URL is absent. It is a manifest error when the control URL is present + but the capability is not declared. Unknown control keys are a manifest + error. +5. Pass control URLs to the external test through environment variables + that the runner sets and the test reads. Keep + `EGGFETCH_H3_INTEROP_DANGER_ACCEPT_INVALID_CERTS` as the only certificate + bypass, and keep it off unless the operator passed the existing flag. +6. Bump `qualification/http3/corpus.json` or the server-manifest schema + version if the new fields would be misread by `schema_version` 1. + Both coordinators fail closed on an unsupported version. Update + `qualification/http3/servers.example.json` so its example controls are + obviously placeholders on `h3.example.invalid` and are not evidence. +7. Extend `scripts/test_h3_qualification.py` for the new manifest rules. + The self-test must not open a socket and must not run `cargo test`. +8. Point the module docs in `h3_interop_qualification.rs` at this plan as + the active harness plan. Leave the historical program files in place + and do not mark them complete. + +## 8. Failure, cancellation, timeout, and pool semantics + +Cancellation tests assert prompt return and a usable client afterwards. +They use the existing timeout types. They must not add a new timeout field +or a new `ResponseBody` variant. + +GOAWAY behavior asserted here is the behavior already implemented in +`crates/eggfetch-core/src/transport/http3.rs`: a draining generation accepts +no new work, and the next eligible request opens a fresh generation. The +test observes that through `h3_reconnected` and a successful follow-up +response. It does not string-match an implementation-specific error when +`H3DispatchError.draining` or the metrics counter is available. + +`Http3Only` remains the policy for generic external endpoint cases. The +alternative-port case is the one external case that uses +`Auto { allow_http3: true }`, because discovery is the behavior under test. + +## 9. Compatibility and migration (incl. feature-profile effects) + +The `http3` feature gate is unchanged. Lean, native, CLI, Python, FFI, and +Node profiles do not gain H3. Python `http3=True` behavior is unchanged. + +This milestone changes Rust tests and a Tier 1 validation script +(`scripts/test_h3_qualification.py`). Those are executable inputs. Closure +requires a new exact-SHA Stage C binding for HTTPX 0.28.1 and HTTPX2 +2.12.0. Do not cite the September 2026 H3 freeze +`639bf186a71c054e11278d1b160ffe7a6f172c02`. + +## 10. Required tests + +- New and mapped cases in `h3_interop_qualification.rs`, loopback only, + `--test-threads=1`. +- Existing `h3_hardening` and `h3_alt_svc_discovery` suites still pass. +- `scripts/test_h3_qualification.py` covers: control URL hygiene, a + server-controlled capability without a control URL recorded as + unsupported rather than pass, and rejection of an unknown control key. +- One local-only coordinator run + (`scripts/h3_qualification.py --local-only`) reports pass for every + corpus id that now has a local fixture. `ipv6` may remain a + capability-detection pass on a host without IPv6. No external server is + required for acceptance. + +## 11. Required verification commands + +```bash +python scripts/test_h3_qualification.py +python scripts/h3_qualification.py --local-only --output target/h3-qualification-local.json +cargo test -p eggfetch-core --all-features --test h3_interop_qualification -- --test-threads=1 +cargo test -p eggfetch-core --all-features --test h3_hardening --test h3_alt_svc_discovery -- --test-threads=1 +./scripts/check.sh +``` + +Tier 2 and Tier 3, including both HTTPX profiles on one frozen SHA, are +required before closure because executable inputs change. Do not add a CI +job, a matrix, or a new workflow. + +## 12. Documentation updates + +- `docs/architecture/core-tls-proxy-protocols.md`: the interop-corpus + paragraph names which cases the external runner can now execute, and + states that server-controlled cases without a control URL stay + unsupported. The experimental verdict stays. +- `qualification/http3/servers.example.json` comments stay inside JSON + `notes` strings and state that the file is a template. +- Do not edit `plans/http3-*-evidence.json`, + `plans/http3-production-qualification-evidence.md`, or the historical + program files. + +## 13. Acceptance criteria + +- Every corpus id except an unavailable `ipv6` host has a local result of + pass from the coordinator, produced by a named test the runner actually + observed as `... ok`. +- A manifest that declares `goaway_reconnect` without `controls.goaway_reconnect` + yields `unsupported` for that case and cannot make + `independent_servers.status` a pass on the strength of that case. +- The external test executes client-driven cancellation and, when control + URLs are present, reset, graceful close, GOAWAY reconnect, and + alternative-port discovery. +- Tier 1 is green, and Stage C is renewed on the freeze that contains this + work. +- HTTP/3 is still documented as experimental. + +## 14. Stop conditions + +- Stop if the only way to observe GOAWAY is to fork or vendor `h3`. +- Stop if a fixture requires a new public client API or a new error variant. +- Stop if making the local corpus pass requires weakening an existing + assertion in `h3_hardening.rs` or `h3_alt_svc_discovery.rs`. +- Stop if the manifest needs to carry credentials, query secrets, or a + shell command. +- A product defect in draining or cancellation is a stop, not a silent + scope expansion. Write the failing test down in the closure notes and + hand the defect back as a separate corrective plan. + +## 15. Closure evidence required + +- Closure record under + `plans/closure/tls-proxy-protocols/006-h3-server-controlled-corpus.md`. +- Requirement-to-evidence matrix: each corpus id, the local test name, and + the external trigger (client-driven or control URL). +- The local-only coordinator JSON, with no independent-server pass claimed. +- Exact SHA of the requalified tree and the Stage C ledger reference. +- An explicit statement that M010 is still blocked on two real non-Quinn + servers. + +## 16. Handoff notes + +Inspect `QuicTestServer` in `h3_interop_qualification.rs` and the draining +test in `h3_alt_svc_discovery.rs` before adding fixtures. Prefer extending +the existing server over a second fixture stack. + +The coordinator currently marks every attempted external case pass when the +single external test returns 0. Keep one test process if that is simpler, +but the JSON must not mark a case pass when that case was not enabled and +did not print its own `H3_CORPUS_CASE =pass` line. Parse those lines. +A panic in one case is a failure of that case, not a pass of the others. + +Do not run this harness against live public hosts. diff --git a/plans/implementation/tls-proxy-protocols/007-h3-impairment-runner.md b/plans/implementation/tls-proxy-protocols/007-h3-impairment-runner.md new file mode 100644 index 00000000..da1a7310 --- /dev/null +++ b/plans/implementation/tls-proxy-protocols/007-h3-impairment-runner.md @@ -0,0 +1,285 @@ +# TLS, Proxy, and Protocols Milestone 007 — H3 Impairment Runner + +Status: closed + +Repository baseline: `f11a46b28df88f43e923d5211f82985784daaf40` + +Source roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-7--h3-impairment-runner` + +Long-term requirements: + +- `plans/000-long-term-specification.md` §3 +- `plans/001-terminology-and-domain-model.md` §6–§7 +- `plans/002-long-term-roadmap.md` Phase 4 item 2 + +Applicable ADRs: + +- `plans/adrs/ADR-0001-single-engine-thin-adapters.md` +- `plans/adrs/ADR-0003-exact-sha-stage-c-binding.md` +- `plans/adrs/ADR-0004-proxy-fallback-total-deadline.md` + +Primary class: infrastructure + +## 1. Objective + +Provide the missing qualification-only runner that +`scripts/h3_impairment.py` already knows how to invoke, so each scenario in +`qualification/http3/impairment-matrix.json` gets a real pass, fail, or +unsupported result. + +The runner proves client invariants under adverse UDP conditions. It does +not benchmark congestion control, and a run that cannot obtain a network +namespace does not count as impairment evidence. + +## 2. Why this milestone is ready + +`scripts/h3_impairment.py` is a fail-closed coordinator. It executes one +operator-supplied program per scenario and accepts only JSON with status +`pass`, `fail`, or `unsupported` plus every invariant named on that row. +With no runner, all 14 scenarios were recorded `unsupported` on the +September 2026 freeze. That result stays historical. + +Local loopback tests already cover a silent connect failure, server +restart, early close, and cancellation against an in-process Quinn server. +They do not apply packet loss, reordering, jitter, duplication, or MTU +impairment. The matrix file already lists the required invariants. No +production API change is needed to start. + +This milestone is independent of M006's manifest work. It must be re-run +after any M008 dependency bump before M010 cites it. + +## 3. Current implementation evidence + +At the baseline: + +- the matrix has 14 required scenarios, from `udp_blackhole` through + `ipv4_failure_ipv6_success`; +- the coordinator's `--runner` argument receives `SCENARIO_ID` and an + output path, and reads `EGGFETCH_H3_IMPAIRMENT_SCENARIO` and + `EGGFETCH_H3_IMPAIRMENT_OUTPUT`; +- a pass whose invariant map contains a non-pass is rewritten to fail; +- Tier 1 does not invoke the coordinator; +- the architecture doc already says impairment execution is + qualification-only and needs a namespace/netem runner. + +## 4. Invariants that must not regress + +- Routine CI and `./scripts/check.sh` stay network-independent and gain no + new job, matrix, or workflow. +- `Http3Only` never falls back to H1/H2. +- `Auto { allow_http3: true }` falls back only before commit and only for a + replayable request. +- A non-replayable body is never sent twice. +- Connect, read, write, and total deadlines stay bounded. Total keeps + winning ties. The runner must not cache a shrinking total deadline inside + a connector. +- Pool permits, response bodies, and H3 driver tasks are released after + bounded cleanup. +- The experimental label is unchanged. +- Impairment setup stays outside `eggfetch-core`. The core does not learn + netem, namespaces, or packet filters. + +## 5. Scope + +### In scope + +- One Linux runner script that the existing coordinator can call. +- One `http3`-gated Rust test target that performs the client assertions + for a single scenario selected by the environment. +- A dependency-free contract self-test that checks the JSON shape without + root and without a network namespace. +- Honest `unsupported` results when the host lacks `unshare`/`ip netns`, + `tc`, IPv6, or the privileges needed to impair a namespace. + +### Explicitly out of scope + +- Adding the runner to Tier 1 or to GitHub Actions. +- Independent non-Quinn servers. The impaired peer may be the existing + loopback Quinn/h3 fixture. Independent-stack evidence stays M006's + harness plus M010's execution. +- Public-origin checks. +- Claiming a congestion-control algorithm or a throughput number. +- Changing production timeout, fallback, or pooling code unless a scenario + exposes a defect. A defect stops the milestone; see §14. + +## 6. Required production changes + +None expected. The runner and the scenario tests are qualification code. +Do not add a production feature flag for impairment. + +## 7. Ordered work packages + +1. Add `crates/eggfetch-core/tests/h3_impairment_scenarios.rs`, gated on + `http3`. Each scenario is its own test, named exactly as the matrix id. + The test is skipped with a printed `unsupported` reason when + `EGGFETCH_H3_IMPAIRMENT_SCENARIO` is unset or names a different id, so a + normal `cargo test` of the file does not require netem and does not + pretend to have passed the matrix. When selected, the test runs the + client assertions below and writes the coordinator JSON to + `EGGFETCH_H3_IMPAIRMENT_OUTPUT` if that variable is set. +2. Add `scripts/h3_impairment_netem.py`. For each scenario it creates a + Linux network namespace (or uses `unshare`), places the loopback Quinn + fixture and the eggfetch test in that namespace, applies the impairment, + runs the one matching cargo test with `--test-threads=1`, and writes the + JSON artifact. If namespace setup is unavailable, write + `status: unsupported` and a `reason`. Do not exit 0 from the coordinator + in that case: the existing coordinator already returns blocked unless + every selected scenario is pass. +3. Implement the matrix as client invariants, using these impairments: + - `udp_blackhole`: drop UDP to the server port. `Http3Only` ends within + the configured connect or total deadline and does not fall back. + Resources release. + - `udp_rejected`: reject the UDP port. `Auto` on a replayable GET falls + back only before commit when an H1 path exists in the fixture; a + non-replayable body is not retried. + - `packet_loss_low` and `packet_loss_high`: `tc netem loss` at two fixed + nonzero rates chosen in the script and recorded in the JSON. Assert + deadline, no body duplication, and prompt cancellation. Do not assert + a throughput. + - `latency_jitter`: delay plus jitter. A request with a total deadline + shorter than the induced delay terminates. A later request with a + usable deadline succeeds. The Alt-Svc cache is not permanently poisoned. + - `packet_reordering` and `packet_duplication`: body bytes match the + fixture exactly and the request body is sent once. + - `reduced_mtu_pmtu_blackhole`: clamp MTU or drop packets above a small + size. The attempt stays inside its deadline. `Auto` fallback, if it + happens, is pre-commit only. + - `path_loss_after_headers` and `path_loss_during_upload`: impair the + path after the transfer has started. The read or write ends by + cancellation or error inside the deadline. The upload body is not + retried. + - `server_restart`: stop the fixture, start it again on the same port, + and show the next request succeeds on fresh H3 state. + - `first_address_unreachable`: the fixture advertises one unreachable + address and one reachable address. Both attempts share one connect + budget, and the reachable address succeeds. + - `ipv6_failure_ipv4_success` and `ipv4_failure_ipv6_success`: report + `unsupported` when the host has only one family. When both exist, the + failed family does not prevent the working family from returning an + intact body. +4. Keep certificate material inside the existing test fixture. The runner + must not disable certificate verification in production code. +5. Add a unittest module beside `scripts/test_h3_qualification.py` that + loads the runner's result-writing helpers without root. Cover: missing + privileges become `unsupported` with every required invariant key + present; a pass with a failed invariant is rejected; an unknown scenario + id is rejected. Wire that self-test into the Tier 1 runner self-test + path only if it stays socket-free. Do not register the netem execution + in `./scripts/check.sh`. +6. Document the privilege requirement and the two example rates next to + the matrix description in + `docs/architecture/core-tls-proxy-protocols.md`. State that an + `unsupported` matrix is not graduation evidence. + +## 8. Failure, cancellation, timeout, and pool semantics + +Every scenario that names a deadline invariant uses a `Timeout` small +enough to fail the test if the impairment hangs, and large enough that a +healthy loopback request still passes. Cancellation uses the client's +existing drop/abort path. + +Fallback assertions use a replayable GET for the positive fallback case and +a one-shot body for the negative case. The one-shot body must be observed +once at the fixture. + +`server_restart` and the address-family scenarios must leave the origin +usable afterwards. A suppressed route, if suppression fires, must recover +when the path returns, using the existing generation rules. Do not invent a +new suppression class. + +## 9. Compatibility and migration (incl. feature-profile effects) + +No profile gains `http3`. The new test target is `http3`-gated and is not +part of the lean or native profiles. + +Adding a Rust test target and a Tier 1 self-test changes executable inputs. +Closure requires a renewed exact-SHA Stage C binding. A docs-only note of +an `unsupported` macOS run does not by itself satisfy that requirement +once the test target exists. + +The runner is Linux-specific. macOS and Windows runs of the script record +`unsupported`. They are not failures of the client. + +## 10. Required tests + +- The new scenario file passes under plain `cargo test` by skipping every + scenario that is not selected, without claiming matrix evidence. +- The contract self-test passes with no privileges. +- On a Linux host that can create a namespace, one coordinator run with + `--runner scripts/h3_impairment_netem.py` writes a result for all 14 ids. + Scenarios the host cannot execute are `unsupported`, not pass. +- Existing `h3_hardening` blackhole, restart, and cancellation tests still + pass and remain the Tier 1 controls. + +## 11. Required verification commands + +```bash +python scripts/test_h3_qualification.py +cargo test -p eggfetch-core --all-features --test h3_impairment_scenarios -- --test-threads=1 +cargo test -p eggfetch-core --all-features --test h3_hardening -- --test-threads=1 +./scripts/check.sh +``` + +Privileged execution, only where the host allows it, and not part of Tier 1: + +```bash +python scripts/h3_impairment.py --runner scripts/h3_impairment_netem.py --output target/h3-impairment.json +``` + +Tier 2 and Tier 3 plus both HTTPX profiles are required before closure +because a new Rust test target is an executable input. Do not add CI. + +## 12. Documentation updates + +- Architecture doc: how to invoke the runner, the privilege requirement, + and the rule that `unsupported` is not a pass. +- Matrix `description` may gain one sentence pointing at the runner script. +- Do not rewrite `plans/http3-independent-interop-and-impairment-qualification-evidence.json`. + +## 13. Acceptance criteria + +- `scripts/h3_impairment.py --runner scripts/h3_impairment_netem.py` is a + sufficient command. No second coordinator is introduced. +- Every matrix id is implemented or explicitly `unsupported` with a reason + the contract test can distinguish from a pass. +- Invariants in the JSON are exactly the matrix invariants, each `pass`, + `fail`, or a status that forces the scenario off `pass`. +- Tier 1 stays green without root and without UDP impairment. +- HTTP/3 remains experimental. The closure says whether a privileged Linux + run happened. If it did not, M010's impairment row stays open. + +## 14. Stop conditions + +- Stop if the scenario can only be expressed by teaching `eggfetch-core` + about netem or by adding a public test hook on `Client`. +- Stop if a scenario fails because of a product defect in deadlines, + fallback, or replay. Record the scenario id and the observed behavior. + Do not loosen the invariant to obtain a pass. +- Stop if the runner needs a new published crate or a new CI service. +- Do not vendor a packet simulator when `tc netem` can express the + scenario. A scenario `tc` cannot express on that host is `unsupported`. + +## 15. Closure evidence required + +- Closure record under + `plans/closure/tls-proxy-protocols/007-h3-impairment-runner.md`. +- The contract-test result. +- The coordinator JSON if a privileged run was possible; otherwise an + explicit "not executed" entry naming the host OS and the missing + capability. +- The renewed Stage C SHA. +- A statement that this Quinn-peer impairment run is not independent-server + interop evidence. + +## 16. Handoff notes + +The development host for the planning baseline is macOS. Implement the +runner and the unprivileged tests there. Do not block the code on a Linux +namespace you cannot create. Do not describe a macOS `unsupported` result +as a completed impairment matrix. + +Read `scripts/h3_impairment.py` `execute` before choosing field names. The +artifact must already match that parser: `status`, `scenario`, and an +`invariants` object whose keys include every name on the matrix row. diff --git a/plans/implementation/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md b/plans/implementation/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md new file mode 100644 index 00000000..7586da7e --- /dev/null +++ b/plans/implementation/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md @@ -0,0 +1,260 @@ +# TLS, Proxy, and Protocols Milestone 008 — H3 Upstream Risk Re-Audit + +Status: closed + +Repository baseline: `f11a46b28df88f43e923d5211f82985784daaf40` + +Source roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-8--h3-upstream-risk-re-audit` + +Long-term requirements: + +- `plans/000-long-term-specification.md` §3 +- `plans/001-terminology-and-domain-model.md` §6–§7 +- `plans/002-long-term-roadmap.md` Phase 4 item 2 + +Applicable ADRs: + +- `plans/adrs/ADR-0001-single-engine-thin-adapters.md` +- `plans/adrs/ADR-0003-exact-sha-stage-c-binding.md` + +Primary class: invariant + +## 1. Objective + +Re-audit the pinned Quinn/h3 stack against the upstream defects that block +ordinary HTTP/3 support, and upgrade only when a published release closes a +defect that eggfetch can reach. + +The outcome is a current risk ledger. A decision to stay on `h3` 0.0.8 is a +successful close of this milestone when no published release fixes the +blocking defect. That decision keeps HTTP/3 experimental. + +## 2. Why this milestone is ready + +The September 2026 ledger is stale relative to this tree and relative to +upstream: + +- `Cargo.toml` still pins `h3` 0.0.8 with + `i-implement-a-third-party-backend-and-opt-into-breaking-changes`, + `h3-quinn` 0.0.10, and `quinn` 0.11. +- `Cargo.lock` at the baseline resolves `quinn` 0.11.11 and `quinn-proto` + 0.11.18. The September ledger recorded `quinn-proto` 0.11.16. +- Crates.io, as checked on 2026-11-16, still has no `h3` newer than 0.0.8 + and no `h3-quinn` newer than 0.0.10. Quinn 0.11.12 exists and does not + fix the h3 frame defect. +- [h3 #338](https://github.com/hyperium/h3/issues/338) is open. + [h3 #339](https://github.com/hyperium/h3/pull/339) is open. The defect + drops buffered frame bytes when a connection close arrives in the same + receive batch, so a complete response can surface as a connection error. + The response-header path cannot be repaired in eggfetch, because only h3 + holds those bytes. +- [h3 #361](https://github.com/hyperium/h3/issues/361) is open. On the + released `h3-quinn` 0.0.10, `stop_sending` during an outstanding read does + not put the requested HTTP/3 code on the wire. The #331 panic fix is not + in the released crate. + +The audit can be done now. It must finish before M010 collects evidence, +because a later lockfile change invalidates that evidence. M006 and M007 +may land beside this milestone; their external runs, if any, are not +graduation evidence until they are repeated on the post-audit pins. + +## 3. Current implementation evidence + +Draining uses `h3` 0.0.8 `ConnectionState::is_closing()` and +`is_h3_no_error()`, documented in `transport/http3.rs`. Local early-close +tests distinguish EOF from error and do not reproduce #338. Cancellation +tests show the client stays usable; they do not observe the STOP_SENDING +code on the wire. + +The previous dispositions live in +`plans/http3-upstream-risk-resource-and-observability-hardening.md` and +`plans/http3-production-qualification-evidence.md`. Those files are +historical. This milestone writes a new ledger. + +## 4. Invariants that must not regress + +- No private fork, vendored patch, or `[patch]` of `h3`, `h3-quinn`, or + `quinn` is introduced to force graduation. +- No second QUIC stack is added. +- The unstable h3 feature remains an explicit, documented integration + contract. If a release removes `is_closing()` / `is_h3_no_error()`, the + drain path is ported to the replacement API and retested. It is not + stubbed. +- 0-RTT stays disabled. Datagram routing, WebTransport, and MASQUE stay + out of scope. +- A dependency bump does not enable H3 by default and does not add it to + the CLI or FFI default features. +- Certificate verification failure still never retries with another trust + store. + +## 5. Scope + +### In scope + +- A fresh ledger of exact resolved versions and of every open upstream + issue that can change ordinary GET, POST, streaming, cancellation, or + graceful close. +- An upgrade of `h3`, `h3-quinn`, and the Quinn crates they require, only + when the published crates contain the #338 fix or an equivalent frame + drain. +- Regression tests that lock the drain API actually used after the audit. +- A written no-upgrade decision when those crates do not exist yet. + +### Explicitly out of scope + +- Carrying a downstream patch for #339 inside this repository. +- Treating a Quinn-only bump as a fix for #338. +- Closing #361 by matching error strings. +- Independent-server, impairment, or public-origin execution. +- Removing the experimental label. Even a successful upgrade leaves that + to M010. + +## 6. Required production changes + +If, at execution time, crates.io still has no release that fixes #338: + +- change no dependency and no production code; +- record #338 as a graduation blocker and #361 as an open cancellation + wire-code limitation; +- re-check the Quinn advisory GHSA-6xvm-j4wr-6v98, or its successor, + against the resolved `quinn-proto`. + +If a published release does fix #338: + +- bump the manifests and lockfile together; +- port GOAWAY detection to the published API if the unstable methods moved; +- keep the feature gate and the experimental docs; +- add the regression in §10. + +## 7. Ordered work packages + +1. Resolve the current graph (`h3`, `h3-quinn`, `quinn`, `quinn-proto`, + `quinn-udp`, `rustls`, `tokio-rustls`, `tokio`) and record versions and + the h3 feature flags. +2. Re-read #338, #339, #361, and the reset-observation issues cited by the + September ledger (#352, #353), plus any newer h3 or Quinn issue that + affects ordinary client responses, cancellation, GOAWAY, or QPACK. + Confirm open/closed state on the day of the audit. Do not copy the + 2026-11-16 status into the ledger without looking. +3. For each issue, write one row: reference, affected versions, whether + eggfetch's recv, cancel, or drain path can reach it, impact on a + successful response, existing test, and one disposition: + `upgrade`, `local safe workaround`, `proven not reachable`, or + `graduation blocker`. + `local safe workaround` is allowed only when the workaround lives in + eggfetch code, has a regression test, and does not vendor h3. + #338 does not qualify for that disposition on the response-header path. +4. Apply §6. Run the H3 suites after any bump. Confirm 0-RTT is still off + and that `Http3Only` still does not fall back. +5. Write `qualification/http3/upstream-risk-ledger.json` with + `schema_version` 1, the git SHA, the resolved versions, and the rows. + Update the dependency table in + `docs/architecture/core-tls-proxy-protocols.md` so it matches the ledger. + Add a new dated paragraph. Do not rewrite the 2026-09-11 decision + paragraph. +6. If the unstable API is still in use, keep the existing re-audit comment + in `transport/http3.rs` accurate for the pinned version. + +## 8. Failure, cancellation, timeout, and pool semantics + +An upgrade must preserve phase-correct connect, read, write, and total +timeouts, pool-permit release, and the single pre-commit replayable +fallback. Cancellation must still leave the client usable. If #361 is +unfixed, do not claim a conformant STOP_SENDING code during a pending +read. The ledger says so, and the cancellation tests keep asserting client +usability rather than the wire code. + +## 9. Compatibility and migration (incl. feature-profile effects) + +A docs-and-ledger-only no-upgrade close does not change executable inputs +and does not require a new Stage C freeze. + +A manifest or lockfile change does. Closure of an upgrade requires Tier 1, +Tier 2, Tier 3, and renewed HTTPX 0.28.1 and HTTPX2 2.12.0 qualification +on that exact SHA. M010 must cite that SHA, not an earlier one. + +No Python, CLI, or FFI signature changes. + +## 10. Required tests + +On the no-upgrade path, run the existing H3 suites once to show the audited +pins still pass. Do not add a test that claims to reproduce #338 unless it +fails reliably on the pinned crate. A flaky reproduction is not a gate. + +On the upgrade path: + +- the existing `h3_hardening`, `h3_alt_svc_discovery`, + `h3_interop_qualification`, and `h3_datagram_route` suites pass; +- a focused drain test still proves a graceful close refuses new work on + that generation and the next request reconnects; +- a comment or test name identifies the upstream issue the upgrade closed. + +## 11. Required verification commands + +No-upgrade path: + +```bash +cargo test -p eggfetch-core --all-features --test h3_hardening --test h3_alt_svc_discovery --test h3_interop_qualification --test h3_datagram_route -- --test-threads=1 +``` + +Upgrade path, before closure: + +```bash +cargo test -p eggfetch-core --all-features --test h3_hardening --test h3_alt_svc_discovery --test h3_interop_qualification --test h3_datagram_route -- --test-threads=1 +./scripts/check.sh +./scripts/check.sh extended +./scripts/check.sh package +``` + +Plus the HTTPX exact-SHA requalification required by +`.skills/verification-qualification.md`. No new CI job. + +## 12. Documentation updates + +- `qualification/http3/upstream-risk-ledger.json` is the current ledger. +- `docs/architecture/core-tls-proxy-protocols.md` dependency section matches + it and still calls #338 a graduation blocker when the issue is open. +- Historical evidence files are not edited. + +## 13. Acceptance criteria + +- The ledger has one explicit disposition for every audited issue, including + #338 and #361. +- Either the lockfile is unchanged and #338 is recorded as a blocker, or + the lockfile cites a published release that contains the frame-drain fix + and the H3 suites plus Stage C are green on that SHA. +- No `[patch]`, vendor directory, or git dependency on h3 or Quinn exists. +- The experimental label remains. + +## 14. Stop conditions + +- Stop before adding a fork, a vendored `frame.rs`, or a git dependency. +- Stop if the published fix changes GOAWAY observation and the drain tests + cannot be made true without a new public API. +- Stop if an upgrade forces 0-RTT, a new public metric, or a default-on + H3 policy. +- Do not close #338 as `proven not reachable` without a test or a code-level + argument that eggfetch never polls the affected `recv_response` / + `recv_data` path. The September audit did not have that proof. + +## 15. Closure evidence required + +- Closure record under + `plans/closure/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md`. +- The ledger file and the upstream URLs as fetched, with the fetch date. +- For an upgrade: the freeze SHA and the Stage C record. +- For a no-upgrade: the crates.io versions observed and the sentence that + M010 cannot clear the upstream row. + +## 16. Handoff notes + +Look up the issues again at the start of the work. The statuses in §2 are +planning-time facts from 2026-11-16, not a substitute for the audit. + +Land this milestone before anyone treats an M006 or M007 external run as +graduation evidence. If this milestone bumps dependencies after those +milestones have merged, their tests are re-run on the new pins as part of +this milestone's H3 suite. Their closure records do not need to be reopened +unless those tests fail. diff --git a/plans/implementation/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md b/plans/implementation/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md new file mode 100644 index 00000000..412af460 --- /dev/null +++ b/plans/implementation/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md @@ -0,0 +1,225 @@ +# TLS, Proxy, and Protocols Milestone 009 — H3 Resource Soak and Platform Scope + +Status: closed + +Repository baseline: `f11a46b28df88f43e923d5211f82985784daaf40` + +Source roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-9--h3-resource-soak-and-platform-scope` + +Long-term requirements: + +- `plans/000-long-term-specification.md` §3 +- `plans/001-terminology-and-domain-model.md` §6–§7 +- `plans/002-long-term-roadmap.md` Phase 4 item 2 + +Applicable ADRs: + +- `plans/adrs/ADR-0001-single-engine-thin-adapters.md` +- `plans/adrs/ADR-0003-exact-sha-stage-c-binding.md` +- `plans/adrs/ADR-0005-frozen-body-feature-containment.md` + +Primary class: infrastructure + +## 1. Objective + +Extend the deterministic HTTP/3 resource evidence from short loopback +cycles to a bounded soak, and replace the prose platform claim with a +table that records only what was actually run. + +The table is allowed to say that a platform was not executed. That is the +support limit. It is not a failure, and it is not a support claim. + +## 2. Why this milestone is ready + +The short controls already pass and stay in place: 100 reused requests, 10 +fail/reconnect cycles, cancellation storms, construction/drop loops, 70 +origins against the 64-entry cache, and 20-way multiplexing. The +architecture doc names long-duration descriptor and memory soak as future +work and forbids fragile exact-RSS assertions. + +`crates/eggfetch-core/tests/resource_stabilization.rs` is the existing +pattern: warm up, repeat, and compare against a bounded envelope. On +non-Linux it skips the RSS number instead of inventing one. H3 soak should +follow that pattern inside the `http3` test target. It does not belong in +the H1 stabilization file. + +No upstream fix and no external server is required to measure the local +client. If M008 later changes pins, these tests are part of the suite that +must be re-run; they do not freeze a support claim by themselves. + +## 3. Current implementation evidence + +`h3_hardening.rs` and `h3_interop_qualification.rs` contain the short +cycles listed above. `h3_many_distinct_origins_stay_bounded` covers the +cache cap. `TransportMetrics::h3_diagnostics` retains at most 64 copied +snapshots and no live connection handle. + +The September evidence record says runtime qualification was Linux aarch64 +only, and that macOS, Windows, and other architectures were not executed. +This tree has no platform table that a later reader can check. + +## 4. Invariants that must not regress + +- No exact RSS equality and no single-sample peak as a pass/fail line. +- The 64-entry H3 connection cache and the 64-entry diagnostic store stay + bounded. Active references are not evicted out from under a live body. +- Dropping the client releases owned QUIC resources after in-flight + request references are gone. +- Tests stay `--test-threads=1` safe and loopback-only. +- `ResponseBody` gains no variant. No new public metric is added to force + the soak to be observable. Use existing `TransportMetrics` and process + observations. +- The experimental label stays. A green soak is not graduation. + +## 5. Scope + +### In scope + +- Longer deterministic H3 cycles for reuse, fail/reconnect, cancellation, + partial body drop, and client construction/drop. +- Descriptor or socket observations where the OS exposes them, skipped + with a recorded reason where it does not. +- A platform table in the architecture doc. + +### Explicitly out of scope + +- A multi-hour CI soak or a new benchmark product. +- Running the soak on every OS inside this milestone. Fill a row only for + the host that actually ran it. Additional hosts are M010 operational + evidence. +- Impairment, independent servers, and the upstream ledger. +- Changing cache eviction policy. If the soak shows unbounded growth, + stop and report it. Do not retune the cache in this milestone unless the + growth is a leak of a resource the existing tests already require to be + released. + +## 6. Required production changes + +None expected. A leak fix is in scope only when the new test shows the +client retains per-origin state, tasks, or sockets after the existing +drop and eviction contracts say they should be gone. Any such fix keeps +the public surface unchanged and gets the new test as its regression. + +## 7. Ordered work packages + +1. Add soak tests to the existing `http3` interop or hardening target, + still loopback Quinn/h3: + - repeated sequential requests on one reused connection, well beyond + the current 100, in a fixed count that finishes in a local test run + (use 1 000 unless measurement shows that count is unreasonable, and + record the count); + - repeated fail/reconnect cycles beyond the current 10, asserting the + cache does not grow by one live generation per failure; + - a cancellation storm and a partial-body-drop loop, followed by one + successful request; + - a construction/drop loop of many clients, each of which completes + one request and is dropped. +2. Sample resource use with the same restraint as + `resource_stabilization.rs`. On Linux, read `VmRSS` from + `/proc/self/status` and the count of `/proc/self/fd`. Assert an + envelope against the post-warmup baseline: the ending sample is not an + unbounded step above the baseline across the whole loop. Do not assert + a byte equality. On other operating systems, skip the numeric RSS check + and still assert the behavioral contracts (later request succeeds, + origin count stays within the cache cap, diagnostics length stays + within 64). +3. Assert `h3_diagnostics()` length stays at or below 64 and that entries + contain no origin hostname, header, or close-reason text. The existing + redaction tests remain the authority if they already cover this. +4. Add a platform table under "Resource and Platform Scope" in + `docs/architecture/core-tls-proxy-protocols.md` with one row per + execution: OS, architecture, build features, deterministic H3 suites + run, soak run, IPv6 executed or skipped, impairment executed or not, + and whether that row is support evidence. The row for the host that + runs this milestone is filled. Other rows are absent, or present with + "not executed". A package build is not a runtime row. +5. Leave `eggfetch-bench` `resource_monitor` on its current H1/H2 workload. + Do not make the bench binary an H3 graduation gate. + +## 8. Failure, cancellation, timeout, and pool semantics + +The soak uses the same timeout and cancellation paths as `h3_hardening.rs`. +Fail/reconnect uses a refused or blackholed UDP target and must not poison +a different origin. Partial body drop must leave the connection usable for +a later request on that origin, matching +`h3_partial_response_drop_keeps_connection_usable`. + +Pool permits are acquired and released as they are today. The soak does not +raise pool limits to hide a leak. + +## 9. Compatibility and migration (incl. feature-profile effects) + +Tests only, plus the architecture doc. The new tests are behind `http3` +and do not run in lean or native profiles. Changing Rust tests invalidates +the Stage C binding. Closure includes renewed HTTPX 0.28.1 and HTTPX2 +2.12.0 qualification on the freeze SHA. + +No default-feature change. No Python API change. + +## 10. Required tests + +- The new soak tests pass at `--test-threads=1` with `http3` enabled. +- Existing short H3 resource tests still pass. +- A host without `/proc` still passes the behavioral assertions and skips + the numeric sample without a false pass of the Linux envelope. + +## 11. Required verification commands + +```bash +cargo test -p eggfetch-core --all-features --test h3_hardening --test h3_interop_qualification -- --test-threads=1 +./scripts/check.sh +``` + +Tier 2, Tier 3, and both HTTPX profiles on the freeze SHA are required +before closure. Do not add the soak to a new CI job. Tier 1 already runs +the `http3` tests through the workspace test command when features are on; +keep that shape. + +## 12. Documentation updates + +- The platform table and a short description of the soak counts in + `docs/architecture/core-tls-proxy-protocols.md`. +- The experimental graduation section stays. The soak is listed as local + evidence, not as the missing independent-server or impairment evidence. + +## 13. Acceptance criteria + +- Soak counts and the envelope rule are written down and enforced by tests. +- Diagnostics and the connection cache remain capped at 64. +- The platform table has a filled row only for an execution that happened, + and it does not call an unexecuted OS supported. +- Stage C is renewed. +- HTTP/3 remains experimental. + +## 14. Stop conditions + +- Stop if the envelope can be satisfied only by an exact RSS number or by + disabling the test under load. +- Stop if the soak requires a public metrics API or a new `ResponseBody` + variant. +- Stop if growth is unbounded and the cause is not a straightforward + failure to honor the existing drop contract. Report the measurement + instead of raising the cache cap. +- Do not mark macOS or Windows supported because the binary compiles there. + +## 15. Closure evidence required + +- Closure record under + `plans/closure/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md`. +- The host row that was filled, the soak counts, and the envelope result. +- The renewed Stage C SHA. +- A note that M010 still owns any additional platform rows and the + graduation decision. + +## 16. Handoff notes + +Read `current_rss_bytes` in `resource_stabilization.rs` and the cache-bound +test `h3_many_distinct_origins_stay_bounded` before choosing the envelope. +Keep the soak in the `http3` test binary so a default non-H3 build does +not compile it. + +Choose a request count that a developer can run locally. A multi-hour soak +is not required for this milestone; M010 may attach a longer operator run +later, and this plan does not promise one. diff --git a/plans/implementation/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md b/plans/implementation/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md new file mode 100644 index 00000000..f982c966 --- /dev/null +++ b/plans/implementation/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md @@ -0,0 +1,294 @@ +# TLS, Proxy, and Protocols Milestone 010 — Ordinary H3 Graduation Decision + +Status: closed + +Repository baseline: `f11a46b28df88f43e923d5211f82985784daaf40` + +Source roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-10--ordinary-h3-graduation-decision` + +Long-term requirements: + +- `plans/000-long-term-specification.md` §3 (a production HTTP/3 stack exists only when the evidence gate closes) +- `plans/001-terminology-and-domain-model.md` §6–§7 +- `plans/002-long-term-roadmap.md` Phase 4 item 2 + +Applicable ADRs: + +- `plans/adrs/ADR-0001-single-engine-thin-adapters.md` +- `plans/adrs/ADR-0003-exact-sha-stage-c-binding.md` +- `plans/adrs/ADR-0007-caller-owned-h3-datagram-routing.md` +- `plans/adrs/ADR-0008-uncompiled-protocol-request-semantics.md` + +Primary class: capability + +## 1. Objective + +Decide whether ordinary HTTP/3 request/response operation can be described +as supported, using the gate already written in +`docs/architecture/core-tls-proxy-protocols.md` and +`plans/http3-production-qualification-program.md`. + +Supported, if the gate passes, means the ordinary client path only. The +decision is evidence-backed. A retained experimental label is a valid close +when any required row is missing. + +## 2. Why this milestone is ready + +It is not ready to execute. Hard predecessors: + +- M006 closed, so server-controlled corpus cases can be run and cannot be + counted as passes while `unsupported`; +- M007 closed, so the impairment coordinator has a real runner; +- M008 closed, so the upstream ledger matches the pins under test; +- M009 closed, so the soak and the platform table exist before this + decision extends them. + +Operational predecessors, supplied by the operator and not by those +milestones: + +- two pinned non-Quinn servers; +- one of them able to induce GOAWAY or an equivalent graceful drain, + stream reset, and a restart; +- three public origins on unrelated operators or CDNs; +- a privileged Linux run of the impairment matrix; +- any extra OS row that the support claim will name. + +Do not start this milestone by editing the experimental wording. + +## 3. Current implementation evidence + +The September 2026 decision retained experimental. Its ledger is +historical and its SHA is not this tree. The current blockers, until this +milestone replaces them with a new run, are: + +- zero independent non-Quinn passes; +- no independent GOAWAY/drain evidence; +- an empty public-origin ledger; +- an impairment matrix left `unsupported`; +- h3 #338 open, with no eggfetch workaround on the response-header path; +- runtime evidence recorded for Linux aarch64 only, on that older freeze. + +M006 through M009 prepare harnesses and local evidence. Their closure +records are not this decision. + +## 4. Invariants that must not regress + +- Missing evidence is not a pass. `unsupported`, an empty ledger, and a + skipped public host do not satisfy a gate row. +- `Http3Only` never falls back. Auto fallback stays pre-commit and + replayable-only. +- No second H3 stack, no vendored h3, and no default `allow_http3: true`. +- Caller-owned datagram routing stays experimental even if ordinary H3 + graduates. +- 0-RTT, WebTransport, application datagrams, MASQUE, and connection + migration stay experimental or unimplemented. +- CLI and FFI default features do not gain `http3`. ADR-0008 still applies: + a strict HTTP/3 request on a build without the feature fails closed. +- The Stage C binding is renewed only when this milestone changes + executable inputs. A documentation decision does not invalidate it. A + product fix discovered here does not land inside this plan. + +## 5. Scope + +### In scope + +- One evidence run on the post-M008 pins, using the M006 and M007 tools. +- A public-origin ledger with the fields already specified in + `plans/http3-public-origin-spot-check-ledger.json`. +- A written decision: supported ordinary client, or experimental retained, + with the failing rows named. +- Documentation edits that match that decision and nothing broader. + +### Explicitly out of scope + +- Implementing the harness, the netem runner, the soak, or the dependency + audit. Those are M006–M009. +- Enabling H3 discovery by default, or compiling `http3` into the default + CLI or FFI build. +- Graduating datagram routing or any advanced QUIC feature. +- New CI, a new evidence schema, or a new workflow. +- Fixing a product defect found during the run. Stop and open a corrective + plan. Re-freeze afterwards. Do not promote on a tree that still has the + defect. + +## 6. Required production changes + +None on the decision path. Documentation changes follow the decision in +§7. Production code changes are a stop condition. + +## 7. Ordered work packages + +1. Confirm M006, M007, and M008 closures exist and that the checkout SHA + contains them. Read `qualification/http3/upstream-risk-ledger.json`. If + #338 is still a graduation blocker, the decision is already "experimental + retained" for that row. Continue the other evidence runs so the record + is complete, and do not clear the upstream row by argument. +2. Independent servers. Copy `qualification/http3/servers.example.json` to + an untracked private manifest. Fill at least two implementations that + are not Quinn/h3, chosen from ngtcp2/nghttp3, quiche, quic-go, or + MsQuic. Each entry needs a version and a `source_revision` or + `image_digest`. Run: + + ```bash + python scripts/h3_qualification.py --manifest --output target/h3-qualification.json + ``` + + At least two servers must pass the generic cases. At least one must + pass `goaway_reconnect` through its control URL. Reset and graceful + close on that server are required when the server can induce them; + `unsupported` does not fill the independent-drain row. Store the + manifest outside git if it contains local endpoints. Commit only a + redacted result that keeps implementation, version, identity, case + status, and SHA. +3. Impairment. On a Linux host that can create a namespace, run: + + ```bash + python scripts/h3_impairment.py --runner scripts/h3_impairment_netem.py --output target/h3-impairment.json + ``` + + Every required scenario is `pass`, or the decision stays experimental + and lists the ids that are `fail` or `unsupported`. A Quinn peer is + acceptable for this row. It is not acceptable for the independent-server + row. +4. Public origins. Follow the manual procedure in + `docs/architecture/core-tls-proxy-protocols.md`. Record at least three + successful origins from unrelated operators or CDNs in a new file + `qualification/http3/public-origin-ledger.json`, using the entry fields + from the historical ledger schema: time, hostname only, operator or CDN, + authenticated Alt-Svc category, whether a later request used H3, body + integrity, address family, UDP-unavailable fallback, and whether any + failure was transient. Transient Internet failure does not fail the + deterministic suites and does not count as a success. Do not put host + names into Rust tests. Do not edit the historical empty ledger. +5. Platform scope. Start from the M009 table. Add a row only for a host + that ran the deterministic H3 suites on this SHA. Name IPv4 and IPv6 + only where those cases actually ran. Leave every other OS unexecuted. +6. Decide. Ordinary HTTP/3 may be described as supported only when all of + the following are true on this SHA: + - deterministic hardening, Alt-Svc, fallback, lifecycle, and soak suites + are green; + - two independent non-Quinn servers passed the required corpus; + - one independent server demonstrated drain and reconnect; + - the public ledger has three successful current origins; + - the impairment matrix is pass on the required invariants; + - the upstream ledger has no open issue that corrupts an ordinary + successful response, and #361 is either fixed or explicitly outside + the supported cancellation claim; + - the platform table matches the wording of the support claim; + - Tier 1 is green. Tier 2, Tier 3, and both HTTPX profiles are green on + this SHA if this milestone, or an unclosed predecessor, changed + executable inputs since the last binding. +7. Write the decision. Add a new dated section in + `docs/architecture/core-tls-proxy-protocols.md`. Do not rewrite the + 2026-09-11 section. + - If the gate passes: call ordinary request/response supported and list + the scope in §1. Update the feature-flag page, the Rust and Python + guides, the README line, the compatibility tables, and the + troubleshooting page so they use that scope. Keep datagram routing, + 0-RTT, WebTransport, MASQUE, and migration marked experimental or + absent. Leave `allow_http3: false` as the default. + - If the gate fails: keep every experimental label. Name the open rows + in the new section and in `plans/registry.md`. + +## 8. Failure, cancellation, timeout, and pool semantics + +This milestone does not change them. Evidence runs use the client as M006 +and M007 left it. A failure that shows a deadline, replay, or pool-permit +bug stops the decision. The corrective plan owns the fix. + +## 9. Compatibility and migration (incl. feature-profile effects) + +Graduation does not add `http3` to a profile that lacks it. Python +`http3=True` remains opt-in. The CLI `--http3` flag remains available only +on a build that compiled the feature, and still fails closed otherwise. + +A docs-only decision keeps the current Stage C SHA. Say that in the closure. +Any executable change means this milestone stops; the corrective plan owns +the requalification. + +H3 support and HTTPX Stage C stay separate sentences in the docs. A green +compat suite is not an H3 pass. + +## 10. Required tests + +No new product tests. The evidence commands in §7 are the tests. Deterministic +suites are re-run on the decision SHA: + +```bash +cargo test -p eggfetch-core --all-features --test h3_hardening --test h3_alt_svc_discovery --test h3_interop_qualification --test h3_datagram_route --test h3_impairment_scenarios -- --test-threads=1 +``` + +`h3_impairment_scenarios` without the netem environment must skip rather +than pass the matrix. The matrix result comes only from the coordinator +JSON. + +## 11. Required verification commands + +The §7 commands, plus `./scripts/check.sh` on the decision SHA. Extended +and package tiers run when the binding has to move. No new CI. + +## 12. Documentation updates + +Listed in §7.6–§7.7. Also update the TLS/protocols roadmap status row and +`plans/registry.md` gated-future line so they match the decision. + +Do not edit `plans/000-long-term-specification.md`, +`plans/001-terminology-and-domain-model.md`, or +`plans/002-long-term-roadmap.md` in this milestone. On a passing gate, the +closure record asks the maintainer to amend §3 of the long-term +specification in its own architecture edit. The architecture doc carries +the operational decision until that edit lands. On a retained-experimental +close, leave the long-term documents untouched. + +## 13. Acceptance criteria + +- One new decision section, dated, with either a supported ordinary-client + scope or a blocker list. +- Machine-readable results for the corpus run and the impairment run, and + a public ledger with three successes or an explicit shortfall. +- The upstream ledger SHA matches the decision SHA. +- No historical evidence file was overwritten. +- Datagram routing and advanced QUIC features are still not described as + supported. +- The default version policy is still `Auto { allow_http3: false }`. + +## 14. Stop conditions + +- Stop on a product defect. Open a corrective plan. Do not promote. +- Stop if the only way to fill a row is to treat `unsupported` as pass, to + reuse the September 2026 JSON, or to run public hosts from Tier 1. +- Stop if promotion would require a fork of h3 or Quinn. +- Stop if the support wording would cover a platform, an address family, or + a QUIC feature the evidence did not run. +- Stop before editing `plans/000-long-term-specification.md`, + `plans/001-terminology-and-domain-model.md`, or + `plans/002-long-term-roadmap.md`. + +## 15. Closure evidence required + +- Closure record under + `plans/closure/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md` + with the requirement-to-evidence matrix for every gate row. +- Paths or attached redacted JSON for the corpus, impairment, public + ledger, upstream ledger, and platform table. +- The decision SHA. +- Recommendation: closed with ordinary H3 supported, or closed with + experimental retained. Both need the matrix. A missing predecessor is + not a close; leave this plan blocked. + +## 16. Handoff notes + +This plan becomes the handoff only after M006, M007, and M008 are closed. +M009 should be closed as well so the platform table and soak exist; if +M009 is still open, do not invent a parallel soak here. + +Private manifests and public host lists stay out of git unless they are +redacted to hostname, implementation identity, and pass/fail. No +credentials, no query strings, no raw diagnostic dumps that contain +cookies or authorization headers. + +The canonical gate text remains the architecture doc plus the historical +program's graduation-gate section. This plan sequences the run. It does +not replace that gate with a weaker one. diff --git a/plans/implementation/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md b/plans/implementation/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md new file mode 100644 index 00000000..7e75c166 --- /dev/null +++ b/plans/implementation/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md @@ -0,0 +1,195 @@ +# TLS, Proxy, and Protocols Milestone 011 — H3 Dial-Error Sanitization and Datagram Recv Trust + +Status: closed + +Repository baseline: `8af32d7ca4f1140e266875798522f5da09c17850` + +Closure: `plans/closure/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md` + +Source roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-11--h3-dial-error-sanitization-and-datagram-recv-trust` + +Long-term requirements: + +- `plans/000-long-term-specification.md` §3, §5, §8 +- `plans/001-terminology-and-domain-model.md` §6–§7 +- `plans/002-long-term-roadmap.md` Phase 4 item 2 + +Applicable ADRs: + +- `plans/adrs/ADR-0001-single-engine-thin-adapters.md` +- `plans/adrs/ADR-0003-exact-sha-stage-c-binding.md` +- `plans/adrs/ADR-0007-caller-owned-h3-datagram-routing.md` + +Primary class: invariant + +## 1. Objective + +Close two security-audit gaps on the experimental caller-owned H3 datagram +path so eggfetch matches its own threat-model and ADR-0007 redaction rules: + +1. **Dial-path error text:** `Error::H3Connect` must not embed raw + `DialError::message()` (or other provider-controlled strings) for + connection-kind failures. Terminal route I/O already uses fixed + `ROUTE_IO_TEXT`; connect mapping must be consistent. +2. **Recv source trust:** the private Quinn bridge must not blindly trust + provider datagrams as coming from `peer_addr()`. Reject or drop datagrams + whose reported peer does not match the fixed route peer (defense in depth + beyond AEAD), without changing the public `DatagramDialer` / + `DatagramRoute` shapes. + +This milestone does **not** address upstream h3 #338 (already a graduation +blocker under M008/M010). It does not graduate H3 or expose datagram routing +beyond Rust. + +## 2. Why this milestone is ready + +M004 is closed. A post-M010 security audit of +`feat/h3-caller-owned-datagram-routing` recorded: + +- High: `route_dial_error` / `route_error_override` embed + `failure.message()` into `Error::H3Connect` for + `DialErrorKind::Connection`, contradicting the threat-model claim that + provider messages are not re-exposed and that classification uses typed + `DialErrorKind` only. +- Medium: the bridge tags `RecvMeta.addr` as `self.peer` without validating + what the provider delivered, so a compromised provider can inject off-path + UDP into the QUIC stack (mostly dropped by AEAD; still a DoS / contract + gap). + +Dependencies and interfaces exist. No upstream crate release is required. + +## 3. Current implementation evidence + +- `crates/eggfetch-core/src/transport/http3.rs` — `route_dial_error` and the + connect-path override format `QUIC handshake failed: {}` with + `failure.message()` for Connection; Authentication / Rejected / Other map + to `Error::CustomTransport` preserving the dial error (same as stream + `Dialer`). +- `crates/eggfetch-core/src/transport/datagram.rs` — `try_send` refuses + foreign destinations; Quinn-facing I/O uses fixed `ROUTE_IO_TEXT`; + `recv_worker` does not compare provider source addresses to `peer_addr()`. +- `docs/architecture/threat-model.md` § Malicious Datagram Route documents + fixed Quinn I/O text and typed classification. + +## 4. Invariants that must not regress + +- Public `DatagramDialer` / `DatagramRoute` shapes stay frozen; no new public + helpers beside the existing dialer surface. +- Direct H3 (no datagram dialer) behavior unchanged. +- `Http3Only` still fails closed when a dialer is set and the route fails; + no silent direct-UDP fallback. +- Authentication / Rejected / Other kinds may still surface as + `CustomTransport` with provider text (embedder evidence path), matching + stream `Dialer` — document that consciously; do not silently broaden + redaction of those kinds without a paired Dialer change. +- Bounded queues, fixed peer, SNI/cert on logical origin unchanged. +- H3 remains experimental; no Python/CLI/FFI/Node exposure of the dialer. +- Workspace `unsafe_code = forbid` in core. + +## 5. Scope + +### In scope + +- Sanitize Connection-kind (and any other kind currently mapped into + `H3Connect` with provider text) to fixed, non-provider strings; keep + typed kind / metrics behavior. +- Enforce fixed-peer recv: datagrams not from `peer_addr()` are rejected + without feeding Quinn (log/metrics only if an existing counter fits; + no new public metric required). +- Unit/integration tests under `http3` proving (a) malicious/careless + Connection messages never appear in `H3Connect` Display/Debug, and + (b) off-peer recv is dropped and the client stays usable or fails closed + without panic. +- Threat-model and ADR-0007 cross-check prose if wording drifts. + +### Explicitly out of scope + +- Fixing or working around h3 #338 / #339. +- Changing `CustomTransport` / stream `Dialer` redaction policy. +- Graduating H3; enabling datagram dialer on non-Rust adapters. +- Ledger/lockfile hygiene (M012). +- New CI jobs or Stage C schema changes. + +## 6. Required production changes + +Expected in `eggfetch-core` only (`transport/http3.rs`, +`transport/datagram.rs`, and tests). No `ResponseBody` change. No public +API oracle delta unless an existing error string is part of a frozen +contract (prefer fixed strings already used elsewhere). + +## 7. Ordered work packages + +1. Inventory every path that builds `Error::H3Connect` from dialer failures; + replace provider message interpolation with fixed text keyed by + `DialErrorKind` where Connection (and siblings on that path) apply. +2. Add bridge-side recv peer check before enqueue/to-Quinn; define behavior + on mismatch (drop + continue vs terminate route) and stick to one. +3. Tests: provider that returns Connection with a credential-like message; + provider that yields foreign-source datagrams. +4. Align threat-model wording with the chosen CustomTransport exception. +5. Tier 1; renew exact-SHA Stage C because executable inputs change. + +## 8. Failure, cancellation, timeout, and pool semantics + +Dial failures remain non-retryable at the transport layer unless existing +classification already says otherwise. Recv drops must not hang the route +worker or leak queue capacity. Pool/cache caps stay at 64. + +## 9. Compatibility and migration (incl. feature-profile effects) + +Rust-only, `http3` feature. Callers that parsed `H3Connect` strings for +provider diagnostics will see fixed text — that is intentional. HTTPX +facades unchanged. Profile default features unchanged. + +## 10. Required tests + +- Connection-kind dial error with embedded secret/URL never appears in + `format!("{e}")` / `Debug` for `H3Connect`. +- Foreign-peer recv never reaches a successful QUIC accept of attacker + plaintext; route remains bounded. +- Existing `h3_datagram_route` / hardening suites still pass. + +## 11. Required verification commands + +```bash +./scripts/check.sh +cargo test -p eggfetch-core --all-features --test h3_datagram_route -- --test-threads=1 +cargo test -p eggfetch-core --all-features http3 -- --test-threads=1 +# After freeze: Tier 2/3 + ./scripts/check_security.sh and Stage C rebind +``` + +## 12. Documentation updates + +- `docs/architecture/threat-model.md` § Malicious Datagram Route if needed. +- Architecture H3 datagram section only if behavior notes change. +- No Stage C SHA hardcoding outside canonical qualification records. + +## 13. Acceptance criteria + +- Audit High (H3Connect provider text) and Medium (recv source) closed with + tests. +- Threat model and implementation agree on what is and is not redacted. +- Stage C rebound after the executable change. +- H3 still experimental. + +## 14. Stop conditions + +- Any change that requires exposing Quinn types or widening the public + dialer surface. +- Discovery that fixing recv check breaks a supported embedder contract + that relied on lying about peer (document and escalate; do not silently + waive). + +## 15. Closure evidence required + +- Requirement-to-evidence matrix for both findings. +- Tier 1 green; exact-SHA Stage C renewal recorded in the live ledger. +- Closure record under `plans/closure/tls-proxy-protocols/`. + +## 16. Handoff notes + +Security audit was report-only; this plan is the authorized corrective +work. Do not bundle M012 lockfile/ledger edits into this change set unless +they are docs-only on the same freeze (prefer separate commits). diff --git a/plans/implementation/tls-proxy-protocols/012-h3-qualification-security-hygiene.md b/plans/implementation/tls-proxy-protocols/012-h3-qualification-security-hygiene.md new file mode 100644 index 00000000..a483aec6 --- /dev/null +++ b/plans/implementation/tls-proxy-protocols/012-h3-qualification-security-hygiene.md @@ -0,0 +1,175 @@ +# TLS, Proxy, and Protocols Milestone 012 — H3 Qualification Security Hygiene + +Status: closed + +Repository baseline: `8af32d7ca4f1140e266875798522f5da09c17850` + +Closure: `plans/closure/tls-proxy-protocols/012-h3-qualification-security-hygiene.md` + +Source roadmap: + +- `plans/subsystems/tls-proxy-protocols-roadmap.md#milestone-12--h3-qualification-security-hygiene` + +Long-term requirements: + +- `plans/000-long-term-specification.md` §3, §6 +- `plans/001-terminology-and-domain-model.md` §10–§11 +- `plans/002-long-term-roadmap.md` Phase 4 item 2 + +Applicable ADRs: + +- `plans/adrs/ADR-0003-exact-sha-stage-c-binding.md` +- `plans/adrs/ADR-0007-caller-owned-h3-datagram-routing.md` + +Primary class: infrastructure + +## 1. Objective + +Align H3 qualification artifacts and operator-facing harnesses with the +post-Quinn-advisory lockfile and with safe-by-default qualification +hygiene, closing Medium/Low findings from the post-M010 security audit +that are not production dial-path defects (those are M011). + +Deliverables: + +1. Refresh `qualification/http3/upstream-risk-ledger.json` so resolved Quinn + pins and advisory reachability match workspace `Cargo.lock` after the + RUSTSEC-2026-0523 / 0524 / 0538 bump (and any later same-semver patches). +2. Refresh or clearly mark + `qualification/embedded/reqwest-json/Cargo.lock` and + `qualification/embedded/reqwest-min/Cargo.lock` so security evidence + never cites pre-bump Quinn as current. +3. Harden qualification-only shell/cert surfaces: validate `scenario_id` + before shell interpolation in the netem runner; keep cert-bypass + opt-in and reinforce “not public evidence” in runner help and architecture + docs. + +Upstream h3 #338 remains a graduation blocker (M008/M010); this milestone +does not attempt a workaround. + +## 2. Why this milestone is ready + +The Stage C freeze that cleared Quinn advisories updated workspace +`Cargo.lock` but left the M008 risk ledger and embedded qualification +lockfiles on older Quinn versions. Operators reading those files can draw +wrong advisory conclusions. Netem and interop harnesses are qualification +only; small hygiene fixes reduce misuse risk without changing product +behavior. + +## 3. Current implementation evidence + +- Ledger `resolved_versions` still lists quinn **0.11.11** / + quinn-proto **0.11.18** / quinn-udp **0.5.15** while workspace lock has + **0.11.12** / **0.11.19** / **0.5.16**. +- Embedded reqwest qualification locks still resolve pre-bump Quinn. +- `scripts/h3_impairment_netem.py` embeds `scenario_id` in `bash -lc` after + matrix validation in `main()`, but a direct call with untrusted argv is + unsafe. +- `EGGFETCH_H3_INTEROP_DANGER_ACCEPT_INVALID_CERTS` / + `--danger-accept-invalid-certs` are documented opt-in; reinforce + boundaries only. + +## 4. Invariants that must not regress + +- Qualification fixtures stay non–Tier-1 gates (runner self-test only in + Tier 1). +- No new CI job, matrix, or evidence schema. +- No production TLS bypass; danger flags remain off by default. +- M008 no-upgrade decision for h3 0.0.8 / #338 unchanged unless a published + fix appears (that would be a new M008-style re-audit, not this milestone). +- `scripts/check_security.sh` continues to scan the workspace root lock; + document that embedded locks are separate evidence trees. + +## 5. Scope + +### In scope + +- Ledger pin/advisory refresh (and `git_revision` / notes for the bump). +- Embedded lock refresh via the existing embed qualification update path, + or an explicit “stale / not security-scanned” banner in the embed README + if a full refresh is deferred — prefer refresh. +- Netem `scenario_id` allowlist before any shell use (reject metacharacters + even on direct invocation). +- Doc/help reinforcement for cert-bypass and operator-supplied interop URLs. + +### Explicitly out of scope + +- M011 dial-error / recv-trust production fixes. +- Expanding `check_security.sh` to scan every nested lock without an + explicit verification-policy change (MAY add a note or optional path; + MUST NOT silently expand CI scope). +- Publishing or graduating H3. +- Changing rustix / RUSTSEC-2026-0486 policy (informational allow stays). + +## 6. Required production changes + +None expected in `eggfetch-core` runtime. Changes are under +`qualification/`, `scripts/h3_*.py`, and documentation. If a script change +is treated as an executable input under the exact-SHA rule, renew Stage C. + +## 7. Ordered work packages + +1. Diff ledger `resolved_versions` + advisories against current + `Cargo.lock`; rewrite ledger fields; record that Quinn bump does not + clear #338. +2. Refresh embedded reqwest locks (or document non-authority clearly). +3. Fail closed on `scenario_id` charset before `bash -lc`. +4. Audit help strings / architecture notes for danger-accept-invalid-certs. +5. Self-tests for runner validation; Tier 1 runner self-test still green. + +## 8. Failure, cancellation, timeout, and pool semantics + +N/A (qualification tooling). + +## 9. Compatibility and migration (incl. feature-profile effects) + +No facade or feature-profile change. Consumers of the ledger JSON must +tolerate added advisory entries for the Quinn bump. + +## 10. Required tests + +- `python scripts/test_h3_qualification.py` (and any new validation cases + for scenario_id). +- Optional: focused netem argparse unit checks without requiring netem. + +## 11. Required verification commands + +```bash +python scripts/test_h3_qualification.py +./scripts/check.sh +./scripts/check_security.sh +# If scripts/ or lockfiles under qualification affect executable-input +# policy for Stage C, renew exact-SHA binding after freeze. +``` + +## 12. Documentation updates + +- Ledger + embed README notes. +- Short note in `docs/architecture/core-tls-proxy-protocols.md` or + qualification README that nested locks are not covered by root + `check_security.sh` unless refreshed for a named evidence run. + +## 13. Acceptance criteria + +- Ledger Quinn pins match workspace lock (or explicitly document a newer + intentional pin with advisory disposition). +- Embedded locks refreshed or marked non-authoritative for advisory claims. +- Untrusted `scenario_id` cannot reach the shell. +- Cert-bypass remains opt-in with explicit non-evidence warning. + +## 14. Stop conditions + +- Pressure to enable danger-accept-invalid-certs in CI or Tier 1. +- Attempts to waive #338 via ledger wording. + +## 15. Closure evidence required + +- Before/after ledger pin table. +- Commands run and outcomes. +- Closure record under `plans/closure/tls-proxy-protocols/`. + +## 16. Handoff notes + +Pair with M011 when scheduling; prefer M012 first if only docs/locks/scripts +are needed for an upcoming security citation. #338 stays on the gated-future +list until a published h3 release lands. diff --git a/plans/registry.md b/plans/registry.md index 64d1432e..f86466f6 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -44,20 +44,48 @@ normative policy is `docs/verification-policy.md`. |---|---|---|---| | Core transport and request policy | active | `plans/subsystems/core-transport-policy-roadmap.md` | No implementation milestone is registered. | | Python bindings and HTTPX compatibility | active | `plans/subsystems/python-httpx-compat-roadmap.md` | No implementation milestone is registered. HTTPX 1.0 remains gated on its upstream trigger. | -| TLS, proxy, and protocols | active | `plans/subsystems/tls-proxy-protocols-roadmap.md` | No implementation milestone is registered. H3 graduation remains separately gated. | +| TLS, proxy, and protocols | active | `plans/subsystems/tls-proxy-protocols-roadmap.md` | M006–M012 closed (H3 experimental retained). Stage C renewed on `cef0e7aa5c23ef92f4a378f370516d9dfbaa466d`. | | Release and verification | active | `plans/subsystems/release-verification-roadmap.md` | 0.3.0 publication is closed. | | Performance and footprint | closed | `plans/subsystems/performance-footprint-roadmap.md` | Completed campaigns and repaired fixtures. | -No implementation plan is ready or active. Register new work in this file and -its subsystem roadmap before handing off a plan. Closed plans are historical -evidence, not active requirements or release gates. +Closed plans are historical evidence, not active requirements or release gates. + +## Dependency-ready implementation plans + +| Plan | Status | Notes | +|---|---|---| +| _(none)_ | — | No ready plans in this subsystem | + +No new plan for upstream h3 #338 — remains a gated graduation blocker (M008/M010). + +## Conditionally closed implementation plans + +| Plan | Status | Condition | +|---|---|---| +| `plans/implementation/tls-proxy-protocols/006-h3-server-controlled-corpus.md` | closed | Stage C rebound on `cef0e7aa5c23ef92f4a378f370516d9dfbaa466d` | +| `plans/implementation/tls-proxy-protocols/007-h3-impairment-runner.md` | closed | Stage C rebound; privileged Linux matrix remains operational evidence for graduation | +| `plans/implementation/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md` | closed | Stage C rebound; Darwin + ubuntu-latest CI Linux soak rows recorded | + +## Recently closed implementation plans + +| Plan | Status | Closure | +|---|---|---| +| `plans/implementation/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md` | closed | `plans/closure/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md` | +| `plans/implementation/tls-proxy-protocols/012-h3-qualification-security-hygiene.md` | closed | `plans/closure/tls-proxy-protocols/012-h3-qualification-security-hygiene.md` | +| `plans/implementation/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md` | closed | `plans/closure/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md` | +| `plans/implementation/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md` | closed (experimental retained) | `plans/closure/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md` | + +## Blocked implementation plans + +None. ## Gated futures - **HTTPX 1.0:** wait for an upstream release candidate or stable release with a frozen API, then perform a fresh delta review. -- **H3 graduation:** requires independent interoperability, drain, impairment, - public-origin, and upstream-risk evidence. H3 remains experimental. +- **H3 graduation:** M010 closed with experimental retained. Ordinary HTTP/3 + stays experimental until a later decision fills independent-server, + impairment, public-origin, and upstream (#338) rows on one post-audit SHA. - **Node.js maturation:** requires an explicit scope decision. None of these is unblocked by the closed milestones. @@ -68,17 +96,18 @@ None of these is unblocked by the closed milestones. |---|---|---|---| | 2 | Decide whether CLI work gets its own subsystem roadmap or belongs under an existing roadmap. | Project maintainers | `plans/implementation/release-verification/007-planning-and-documentation-hygiene.md` §5 | | 6 | Decide whether the IPv6 pool-key divergence needs its own milestone. The high-level and native paths currently produce different keys for the same IPv6 origin. | Project maintainers | `plans/closure/core-transport-policy/010-core-duplicate-helper-consolidation.md` §10 | +| H3 | Supply two non-Quinn servers, a privileged Linux impairment pass, and three public-origin checks before any future support decision. | Project maintainers | M010 closure | ## Operational blockers | Area | Blocker | |---|---| | HTTPX qualification | HTTPX 1.0 has not met its upstream trigger. | -| H3 | Graduation evidence is independent of the existing H3 qualification and remains outstanding. | +| H3 | Experimental retained (M010). Open rows: independent non-Quinn servers, privileged impairment, public origins, upstream h3 #338. M011–M012 closed. Stage C rebound on `cef0e7aa5c23ef92f4a378f370516d9dfbaa466d`. | | Tier 2 downstream fixtures | The gate requires `target/downstream-qualification/artifact-manifest.json` and fails closed if it is absent. | Closure records hold milestone-specific evidence and decisions. The live binding is recorded in the ledger, profiles, and canonical compatibility pages: `docs/residual-differences.md`, `docs/reference/compatibility.md`, and `docs/reference/compatibility-stage-decision.md`. Other planning documents -should link to these records rather than duplicate SHA values. +must not invent a second live SHA. diff --git a/plans/subsystems/tls-proxy-protocols-roadmap.md b/plans/subsystems/tls-proxy-protocols-roadmap.md index dd90218f..4ee28e83 100644 --- a/plans/subsystems/tls-proxy-protocols-roadmap.md +++ b/plans/subsystems/tls-proxy-protocols-roadmap.md @@ -1,6 +1,6 @@ # TLS, Proxy, and Protocols Roadmap -Status: active — M005 closed. H3 graduation remains separately gated +Status: active — M005–M012 closed (H3 experimental retained). Stage C renewed on `cef0e7aa5c23ef92f4a378f370516d9dfbaa466d` after M011–M012. Long-term references: @@ -53,9 +53,11 @@ semantics, publication, a parallel connection pool, downstream route policy. ## 3. Non-goals -- H3 graduation (gated); 0-RTT, WebTransport, H3 application datagrams, - MASQUE, QUIC migration; automatic H3-by-default; environment-proxy - activation; upstream proxy helpers where eggfetch contracts would regress. +- Removing the experimental label except by the M010 decision after the + full evidence gate. 0-RTT, WebTransport, H3 application datagrams, + MASQUE, QUIC migration, and automatic H3-by-default stay out of M006–M010. + Environment-proxy activation and upstream proxy helpers where eggfetch + contracts would regress stay out of this roadmap. - M004 permits only fixed-target transport datagrams beneath origin QUIC; it does not expose QUIC DATAGRAM or an application datagram API. @@ -71,13 +73,15 @@ reopened narrowly by ADR-0007/M004 so embedders can supply a fixed-target physical datagram route without becoming QUIC/H3 owners. That seam is now implemented and closed: `ClientBuilder::datagram_dialer` routes every H3 generation over one caller-owned fixed-target route, with direct H3 unchanged -when unset. +when unset. Ordinary H3 graduation is registered as M006–M010 and has not +started. ## 5. Target architecture -Invariants permanent. H3 graduates only through the gated program with fresh -executable freeze + full requalification; until then every H3 change keeps -the experimental label and must not convert missing evidence into a pass. +Invariants permanent. H3 graduates only through M010, on a fresh executable +freeze, after M006–M009 have landed and the external evidence rows are +actually pass. Until that decision, every H3 change keeps the experimental +label and must not convert missing evidence into a pass. M004 adds one client-scoped datagram-routing contract below QUIC while keeping origin QUIC/TLS/H3 in Eggfetch and preserving the direct-H3 path when unset. @@ -93,14 +97,26 @@ M001 proxy Hyper pooling + upstream reuse (hard predecessor for M002) | `--> M004 caller-owned H3 datagram routing (hard: M003; interface: ADR-0007 + Quinn 0.11.11 abstract socket) + +M006 server-controlled corpus (closed; Stage C rebound) +M007 impairment runner (closed; Stage C rebound; Linux netem operational for graduation) +M008 upstream risk re-audit (closed; #338 remains graduation blocker) +M009 resource soak + platform table (closed; Stage C rebound; Darwin row only) + | + `--> M010 ordinary H3 graduation decision + (closed 2026-11-16: experimental retained) + (open rows: independent servers, public origins, privileged Linux impairment, #338) ``` M001–M003 are closed. M004 is closed under accepted ADR-0007: implementation and every Tier 2 gate pass, including the full pinned HTTPX compatibility suite and the API-manifest comparison, which are green on `ubuntu-latest` / Python 3.12.14 at run `37511735210` (1934 passed / 0 failed; both facades 0 unexplained, 0 stale). -H3 graduation remains a separate gated future and was -not an M004 exit condition. +H3 graduation was not an M004 exit condition. The M006–M010 sequence has +closure records: all closed, with Stage C rebound on +`6b571028767dde4b0a78f36e6ecef525c6d68482`; M008 retains the no-upgrade/#338 +path and M010 retains experimental. Ordinary HTTP/3 remains experimental +until a later decision fills the open operational and upstream rows. ## 7. Milestones @@ -224,10 +240,203 @@ native-caller downgrade contract unchanged; the default CLI feature set unchanged and the new features opt-in; public API oracle unchanged; Tier 1/2/3 green with renewed exact-SHA Stage C binding for both profiles. -Deferred: H3 graduation, which remains separately gated; enabling `http2` or +Deferred: H3 graduation, which is M010 and remains blocked; enabling `http2` or `http3` in the CLI by default, which is a separate capability decision; the FFI's missing non-protocol capabilities. +### Milestone 6 — Server-controlled H3 corpus + +Class: infrastructure. Status: ready. + +Implementation: +`plans/implementation/tls-proxy-protocols/006-h3-server-controlled-corpus.md`. + +Objective: make every ordinary-client corpus case executable locally, and +make server-controlled cases executable against an optional external +manifest, with unsupported kept distinct from pass. + +Dependencies: + +- hard: none; +- soft: M008, because a later dependency bump requires the new tests to be + re-run before M010 cites them. + +Deliverable boundary: local Quinn fixtures and the qualification coordinator +cover the corpus ids that the client or the in-process server can induce. +External control URLs exist for reset, graceful close, GOAWAY reconnect, and +alternative-port discovery. No independent server is claimed. + +User or operator value: a later qualification run can exercise GOAWAY, reset, +and cancellation instead of recording those cases unsupported by construction. + +Exit conditions: local coordinator maps each inducible corpus id to a named +passing test; manifest hygiene tests reject credentials and do not count a +missing control URL as a pass; Tier 1 is green; Stage C is renewed because +Rust tests and a Tier 1 script change; HTTP/3 stays experimental. + +Deferred: running ngtcp2, quiche, or quic-go; the impairment matrix; the +experimental-label decision. + +### Milestone 7 — H3 impairment runner + +Class: infrastructure. Status: ready. + +Implementation: +`plans/implementation/tls-proxy-protocols/007-h3-impairment-runner.md`. + +Objective: supply the Linux namespace/netem runner that +`scripts/h3_impairment.py` already calls, so each matrix scenario is pass, +fail, or unsupported for a real reason. + +Dependencies: + +- hard: none; +- soft: M008, same re-run rule as M006; +- operational: a privileged Linux namespace, which is required for a pass + of the matrix and is not required to land the runner. + +Deliverable boundary: one opt-in runner and one `http3` scenario test +target. Tier 1 does not impair the network. An unprivileged host records +unsupported and does not satisfy M010. + +User or operator value: loss, reordering, jitter, duplication, MTU, and +address-family failures can be executed without adding them to CI. + +Exit conditions: the existing coordinator accepts the runner's JSON; the +unprivileged contract self-test passes; Stage C is renewed because a Rust +test target is added; HTTP/3 stays experimental. + +Deferred: independent-server impairment; a CI job for netem. + +### Milestone 8 — H3 upstream risk re-audit + +Class: invariant. Status: ready. + +Implementation: +`plans/implementation/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md`. + +Objective: write a current Quinn/h3 risk ledger and upgrade only if a +published release closes the buffered-data-on-close defect. + +Dependencies: + +- hard: none; +- this milestone is a hard predecessor of any evidence M010 cites. + +Deliverable boundary: `qualification/http3/upstream-risk-ledger.json` plus +either an unchanged lockfile with #338 still blocking, or a published +upgrade, drain tests, and a renewed Stage C binding. No fork and no vendored +patch. + +User or operator value: graduation cannot proceed on a stale September 2026 +dependency story, and it cannot proceed by forking h3. + +Exit conditions: every audited issue has one disposition; the architecture +dependency section matches the ledger; the experimental label remains. + +Deferred: clearing the experimental label; fixing #361 inside eggfetch when +the published crates still defer STOP_SENDING. + +### Milestone 9 — H3 resource soak and platform scope + +Class: infrastructure. Status: ready. + +Implementation: +`plans/implementation/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md`. + +Objective: add a bounded H3 reuse and churn soak, and a platform table that +records only executions that happened. + +Dependencies: + +- hard: none; +- soft: M008, so the soak that M010 quotes is the post-audit one. + +Deliverable boundary: longer loopback cycles with an envelope rather than an +exact RSS figure, plus one filled platform row for the host that ran them. +Other operating systems stay "not executed". + +User or operator value: resource growth and the support boundary are +visible before anyone writes a support claim. + +Exit conditions: cache and diagnostic caps still hold; the table does not +infer runtime support from a package build; Stage C is renewed; HTTP/3 stays +experimental. + +Deferred: multi-OS execution, which M010 may attach when those hosts are +actually run. + +### Milestone 10 — Ordinary H3 graduation decision + +Class: capability. Status: blocked. + +Implementation: +`plans/implementation/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md`. + +Objective: run the existing graduation gate on the post-audit tree and +either describe ordinary request/response HTTP/3 as supported or retain the +experimental label with the open rows named. + +Dependencies: + +- hard: M006, M007, M008, and M009 closed; +- operational: two pinned non-Quinn servers, one independent drain source, + three public origins, and a privileged Linux impairment run. + +Deliverable boundary: a new dated decision section and redacted evidence. +The supported scope, if the gate passes, is ordinary client operation only. +Discovery stays off by default. Datagram routing and advanced QUIC features +stay experimental. Long-term specification files are not edited here. + +User or operator value: the experimental label matches current evidence +instead of the September 2026 freeze. + +Exit conditions: every gate row is pass on one SHA, or the decision records +the failing rows and leaves the label in place. A product defect stops the +milestone and opens a corrective plan. + +Deferred: H3-by-default, CLI/FFI default `http3`, 0-RTT, WebTransport, +MASQUE, migration, and graduating the datagram dialer. + +### Milestone 11 — H3 dial-error sanitization and datagram recv trust + +Class: invariant. Status: ready. + +Implementation: +`plans/implementation/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md`. + +Objective: close the post-M010 audit High/Medium gaps on the experimental +datagram path — stop embedding provider `DialError` text into +`Error::H3Connect`, and enforce fixed-peer recv checks in the private Quinn +bridge — without changing public dialer shapes or graduating H3. + +Dependencies: M004 closed; audit findings recorded. + +Deliverable boundary: core transport + tests + threat-model alignment. +Upstream h3 #338 is out of scope (remains a graduation blocker). + +Exit conditions: both findings closed with tests; Stage C rebound after the +executable change; H3 still experimental. + +### Milestone 12 — H3 qualification security hygiene + +Class: infrastructure. Status: ready. + +Implementation: +`plans/implementation/tls-proxy-protocols/012-h3-qualification-security-hygiene.md`. + +Objective: refresh the upstream-risk ledger and embedded qualification +lockfiles to the post-advisory Quinn pins, harden netem `scenario_id` +handling, and reinforce opt-in cert-bypass / operator-URL boundaries. + +Dependencies: M008 ledger exists; Quinn advisory bump on the workspace lock. + +Deliverable boundary: `qualification/`, H3 scripts, docs. No H3 graduation. +No new CI job. + +Exit conditions: ledger/locks not stale vs workspace authority; shell and +cert-bypass hygiene accepted; Tier 1 runner self-test green. + ## 8. Cross-cutting requirements Trust construction explicit per profile; `Proxy(headers=…)` rides the proxy @@ -237,13 +446,19 @@ boundary; `crypto_provider()` per-config. ## 9. Verification strategy Proxy/TLS/route matrices; H3 deterministic loopback controls in the normal -suite; independent-server/impairment/public-origin evidence manual and -opt-in, never routine gates; Tier 2 + oracles on any executable change. +suite; independent-server, impairment, and public-origin evidence manual and +opt-in, never routine gates. M006 and M007 add harness code only. M010 is +the evidence run. Tier 2 and the HTTPX oracles renew on any milestone that +changes executable inputs. No new CI job or matrix. ## 10. Risks and decision points -Risk: silent H3 capability growth. Control: graduation gate + experimental -label rule; any promotion attempt is a new gated milestone, not a corrective. +Risk: silent H3 capability growth. Control: M006–M009 keep the experimental +label, and M010 is the only milestone allowed to change it, and only when +every gate row is pass. A failed row is a recorded blocker, not a waiver. + +Risk: citing the September 2026 freeze after the lockfile moved. Control: +M008 writes a new ledger, and M010 cites only the post-audit SHA. ## 11. Completion definition @@ -275,6 +490,13 @@ to `closed` there. The closure authorizes neither H3 graduation nor publication, and the maintainer decision on a strict-HTTP/3 FFI policy value remains open. +The ordinary-H3 graduation sequence registered on 2026-11-16 now has closure +records. M006–M010 are closed; Stage C is rebound on +`6b571028767dde4b0a78f36e6ecef525c6d68482`. M008 retains the #338 blocker and +M010 retains experimental. A future support decision still needs independent +servers, privileged impairment, public origins, and a published fix for h3 +#338. + ## 12. Milestone status | Milestone | Status | Implementation plan | Closure record | Blockers | @@ -284,3 +506,10 @@ remains open. | M003 H3 retained-experimental | closed | legacy program §7 | legacy + evidence ledger | Graduation evidence (gated future) | | M004 caller-owned H3 datagram routing | closed | `implementation/tls-proxy-protocols/004-caller-owned-h3-datagram-routing.md` | `closure/tls-proxy-protocols/004-caller-owned-h3-datagram-routing.md` | ADR-0007 accepted; Tier 1/2/3 green including full compat suite (1934 passed) + API manifests on `ubuntu-latest`/3.12.14, run `37511735210`; H3 stays experimental | | M005 uncompiled-protocol fail-closed | closed | `implementation/tls-proxy-protocols/005-uncompiled-protocol-fail-closed.md` | `closure/tls-proxy-protocols/005-uncompiled-protocol-fail-closed.md` | ADR-0008 accepted; closed on bound SHA `26fa619299fb8d447f25cbcb5eb713a1f537a30c` with the Stage C binding renewed there; maintainer decision on a strict-HTTP/3 FFI policy value | +| M006 server-controlled H3 corpus | closed | `implementation/tls-proxy-protocols/006-h3-server-controlled-corpus.md` | `closure/tls-proxy-protocols/006-h3-server-controlled-corpus.md` | Stage C rebound on `6b571028…` | +| M007 H3 impairment runner | closed | `implementation/tls-proxy-protocols/007-h3-impairment-runner.md` | `closure/tls-proxy-protocols/007-h3-impairment-runner.md` | Privileged Linux matrix still operational for graduation | +| M008 H3 upstream risk re-audit | closed | `implementation/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md` | `closure/tls-proxy-protocols/008-h3-upstream-risk-re-audit.md` | No-upgrade; #338 blocker | +| M009 H3 resource soak and platform scope | closed | `implementation/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md` | `closure/tls-proxy-protocols/009-h3-resource-soak-and-platform-scope.md` | Darwin row only; Stage C rebound | +| M010 ordinary H3 graduation decision | closed (experimental retained) | `implementation/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md` | `closure/tls-proxy-protocols/010-ordinary-h3-graduation-decision.md` | Gate failed on independent servers, impairment, public origins, #338 | +| M011 dial-error sanitization + datagram recv trust | closed | `implementation/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md` | `closure/tls-proxy-protocols/011-h3-dial-error-sanitization-and-datagram-recv-trust.md` | Fixed-text H3Connect; recv source check; Stage C on `cef0e7aa…` | +| M012 H3 qualification security hygiene | closed | `implementation/tls-proxy-protocols/012-h3-qualification-security-hygiene.md` | `closure/tls-proxy-protocols/012-h3-qualification-security-hygiene.md` | Ledger/embed Quinn pins; netem charset; Stage C on `cef0e7aa…` | diff --git a/qualification/embedded/README.md b/qualification/embedded/README.md index 51fcab77..34a7e4da 100644 --- a/qualification/embedded/README.md +++ b/qualification/embedded/README.md @@ -4,6 +4,12 @@ Manual, bounded downstream-size qualification for `eggfetch-core`. Not a CI gate. Run at release/architecture review points; copy headline numbers into `docs/architecture/embedded-footprint.md`. +**Security scanning:** each fixture has its own `[workspace]` and +`Cargo.lock`. `scripts/check_security.sh` scans the **repository root** +lock only. Nested embed locks are separate evidence trees — refresh them +when citing advisory reachability for an embed run (M012), and do not treat +a root preflight as covering these graphs. + ## Fixtures Tiny downstream-style binaries under this directory. Each has its own diff --git a/qualification/embedded/reqwest-json/Cargo.lock b/qualification/embedded/reqwest-json/Cargo.lock index 5d445318..43271c03 100644 --- a/qualification/embedded/reqwest-json/Cargo.lock +++ b/qualification/embedded/reqwest-json/Cargo.lock @@ -514,9 +514,9 @@ dependencies = [ [[package]] name = "quinn" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", "cfg_aliases", @@ -534,9 +534,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.17" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", "getrandom 0.4.3", @@ -556,9 +556,9 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", diff --git a/qualification/embedded/reqwest-min/Cargo.lock b/qualification/embedded/reqwest-min/Cargo.lock index f248d994..ada5f8d9 100644 --- a/qualification/embedded/reqwest-min/Cargo.lock +++ b/qualification/embedded/reqwest-min/Cargo.lock @@ -514,9 +514,9 @@ dependencies = [ [[package]] name = "quinn" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", "cfg_aliases", @@ -534,9 +534,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.17" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", "getrandom 0.4.3", @@ -556,9 +556,9 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", diff --git a/qualification/http3/impairment-matrix.json b/qualification/http3/impairment-matrix.json index c47b7134..697bf183 100644 --- a/qualification/http3/impairment-matrix.json +++ b/qualification/http3/impairment-matrix.json @@ -1,7 +1,7 @@ { "schema_version": 1, "name": "eggfetch-http3-impairment-matrix", - "description": "Qualification-only adverse-network scenarios. A runner must report pass, fail, or unsupported for every scenario.", + "description": "Qualification-only adverse-network scenarios. A runner must report pass, fail, or unsupported for every scenario. Linux execution: scripts/h3_impairment_netem.py via scripts/h3_impairment.py --runner.", "scenarios": [ {"id": "udp_blackhole", "required": true, "invariants": ["bounded_connect_or_total_deadline", "Http3Only_does_not_fallback", "resources_released"]}, {"id": "udp_rejected", "required": true, "invariants": ["bounded_connect_or_total_deadline", "safe_auto_fallback_only_pre_commit", "resources_released"]}, diff --git a/qualification/http3/public-origin-ledger.json b/qualification/http3/public-origin-ledger.json new file mode 100644 index 00000000..30ad5b5c --- /dev/null +++ b/qualification/http3/public-origin-ledger.json @@ -0,0 +1,22 @@ +{ + "schema_version": 1, + "program": "http3-ordinary-h3-graduation-decision", + "status": "shortfall", + "decision_sha_note": "Filled during M010 on the post-M008 tree; no public-origin checks were executed.", + "successful_origins": 0, + "required_successful_origins": 3, + "entries": [], + "entry_schema": { + "date_time_utc": "ISO-8601 UTC timestamp", + "hostname": "hostname only; no credentials, paths, or query strings", + "operator_or_cdn": "unrelated operator/CDN classification", + "h1_h2_discovery_status": "status code and authenticated Alt-Svc category/value", + "h3_used": "boolean plus observed route/protocol", + "body_integrity": "endpoint-appropriate integrity check", + "remote_address_family": "ipv4, ipv6, or unavailable", + "udp_unavailable_fallback": "pass, fail, or unsupported", + "transient_failure": "boolean", + "notes": "diagnostic notes without secrets" + }, + "notes": "M010 retained the experimental label. An empty public-origin ledger is an explicit gate shortfall, not evidence of support. Do not treat the historical plans/http3-public-origin-spot-check-ledger.json as current." +} diff --git a/qualification/http3/servers.example.json b/qualification/http3/servers.example.json index 1891a70c..f9a4bb75 100644 --- a/qualification/http3/servers.example.json +++ b/qualification/http3/servers.example.json @@ -8,7 +8,7 @@ "identity": {"source_revision": "record-full-commit-or-image-digest"}, "endpoint": "https://h3.example.invalid/", "capabilities": ["get", "head", "buffered_post", "streaming_upload", "large_streaming_download", "multiplexed_requests", "connection_reuse"], - "notes": "Use an authenticated certificate and a fixture endpoint implementing the declared cases. Do not use credentials or query strings in endpoint URLs." + "notes": "Use an authenticated certificate and a fixture endpoint implementing the declared cases. Do not use credentials or query strings in endpoint URLs. Optional controls (template placeholders on h3.example.invalid, not evidence): stream_reset, graceful_connection_close, goaway_reconnect, alternative_port — each an https URL on the same authority without query or credentials." }, { "implementation": "quiche", diff --git a/qualification/http3/upstream-risk-ledger.json b/qualification/http3/upstream-risk-ledger.json new file mode 100644 index 00000000..e3312aed --- /dev/null +++ b/qualification/http3/upstream-risk-ledger.json @@ -0,0 +1,136 @@ +{ + "schema_version": 1, + "program": "http3-upstream-risk-re-audit", + "audited_at": "2026-11-16", + "git_revision": "cef0e7aa5c23ef92f4a378f370516d9dfbaa466d", + "decision": "no-upgrade", + "decision_summary": "crates.io still has no h3 newer than 0.0.8 and no h3-quinn newer than 0.0.10. PR #339 remains open and unreleased, so #338 stays a graduation blocker. Workspace Quinn pins were refreshed after RUSTSEC-2026-0523 / 0524 / 0538; that bump does not clear #338.", + "resolved_versions": { + "h3": "0.0.8", + "h3_features": [ + "i-implement-a-third-party-backend-and-opt-into-breaking-changes" + ], + "h3-quinn": "0.0.10", + "quinn": "0.11.12", + "quinn-proto": "0.11.19", + "quinn-udp": "0.5.16", + "rustls": "0.23.46", + "tokio-rustls": "0.26.4", + "tokio": "1.53.3" + }, + "crates_io_observed": { + "fetched_at": "2026-11-16", + "h3_newest": "0.0.8", + "h3-quinn_newest": "0.0.10", + "quinn_newest": "0.11.12", + "quinn-proto_newest": "0.11.19", + "quinn-udp_newest": "0.6.3", + "notes": "A Quinn-only bump does not fix h3 #338. No h3/h3-quinn upgrade is taken in this hygiene refresh." + }, + "advisories": [ + { + "id": "GHSA-6xvm-j4wr-6v98", + "aliases": ["CVE-2026-31812", "RUSTSEC-2026-0037"], + "package": "quinn-proto", + "affected": "< 0.11.14", + "fixed": "0.11.14", + "resolved_version": "0.11.19", + "disposition": "proven not reachable", + "notes": "Resolved quinn-proto 0.11.19 is past the patched floor." + }, + { + "id": "GHSA-53rm-773f-4q8c", + "aliases": ["RUSTSEC-2026-0523"], + "package": "quinn-proto", + "affected": "< 0.11.19", + "fixed": "0.11.19", + "resolved_version": "0.11.19", + "disposition": "proven not reachable", + "notes": "MAX_STREAM_DATA stream-limit OOM; patched floor is 0.11.19. Workspace pin matches." + }, + { + "id": "GHSA-wppq-2f6r-wfvm", + "aliases": ["RUSTSEC-2026-0524"], + "package": "quinn-proto", + "affected": "< 0.11.19", + "fixed": "0.11.19", + "resolved_version": "0.11.19", + "disposition": "proven not reachable", + "notes": "Long Retry token panic/OOM on clients; patched floor is 0.11.19. Workspace pin matches." + }, + { + "id": "GHSA-6pp4-4cxf-xf88", + "aliases": ["RUSTSEC-2026-0538"], + "package": "quinn-udp", + "affected": "< 0.5.16, >= 0.6.0 < 0.6.3", + "fixed": "0.5.16 / 0.6.3", + "resolved_version": "0.5.16", + "disposition": "proven not reachable", + "notes": "Truncated-datagram receive spin on some platforms; patched floors include 0.5.16. Workspace pin matches." + } + ], + "issues": [ + { + "reference": "https://github.com/hyperium/h3/issues/338", + "title": "FrameStream discards buffered bytes when QUIC connection error arrives in the same recv batch", + "state_on_audit": "open", + "pr": "https://github.com/hyperium/h3/pull/339", + "pr_state_on_audit": "open", + "affected_versions": ["h3 0.0.8"], + "eggfetch_paths": ["recv_response", "recv_data"], + "impact_on_successful_response": "A complete response can surface as a connection error when STREAM data and CONNECTION_CLOSE coalesce. No eggfetch workaround exists on the response-header path because only h3 holds the buffered frames.", + "existing_tests": "Local early-close / graceful-close suites distinguish EOF from error but do not reliably reproduce the coalesced-batch race.", + "disposition": "graduation blocker" + }, + { + "reference": "https://github.com/hyperium/h3/pull/339", + "title": "frame: drain buffered bytes before propagating QUIC connection error", + "state_on_audit": "open", + "affected_versions": ["unreleased; not on crates.io"], + "eggfetch_paths": ["would fix #338 on published h3"], + "impact_on_successful_response": "Unreleased fix. Cannot be adopted without a published crate or a forbidden fork/vendor.", + "existing_tests": "n/a", + "disposition": "graduation blocker" + }, + { + "reference": "https://github.com/hyperium/h3/issues/361", + "title": "h3-quinn stop_sending during outstanding read deferred; peer may see STOP_SENDING(0)", + "state_on_audit": "open", + "affected_versions": ["h3-quinn 0.0.10", "h3 0.0.8"], + "eggfetch_paths": ["cancellation / stop_sending during pending recv_data"], + "impact_on_successful_response": "Does not corrupt ordinary successful responses. Cancellation remains usable in eggfetch tests; conformant STOP_SENDING wire codes during a pending read are not claimed.", + "existing_tests": "h3_hardening / h3_interop cancellation suites assert prompt return and a usable client afterwards, not wire codes.", + "disposition": "graduation blocker", + "graduation_scope": "blocks any claim of conformant STOP_SENDING wire codes during a pending read; does not by itself corrupt an ordinary successful response body" + }, + { + "reference": "https://github.com/hyperium/h3/issues/352", + "title": "Request reset cannot be observed independently while body polling is paused", + "state_on_audit": "open", + "affected_versions": ["h3 0.0.8", "h3-quinn 0.0.10"], + "eggfetch_paths": ["server-side observation of client RESET while application backpressure pauses poll_data; ordinary client GET/POST recv path still polls"], + "impact_on_successful_response": "Does not turn a complete client response into an error by itself. Affects reset observability under backpressure.", + "existing_tests": "Local stream_reset / early-close recovery tests; no independent reset-poll API in eggfetch.", + "disposition": "proven not reachable" + }, + { + "reference": "https://github.com/hyperium/h3/issues/353", + "title": "AsyncWrite reduces typed stream failures to io::ErrorKind::Other", + "state_on_audit": "open", + "affected_versions": ["h3 0.0.8"], + "eggfetch_paths": ["eggfetch uses typed h3 poll paths, not the AsyncWrite adapter, for ordinary H3 request/response"], + "impact_on_successful_response": "None on the ordinary eggfetch client path.", + "existing_tests": "n/a for AsyncWrite adapter", + "disposition": "proven not reachable" + } + ], + "drain_api": { + "crate": "h3", + "version": "0.0.8", + "methods": ["ConnectionState::is_closing()", "is_h3_no_error()"], + "feature": "i-implement-a-third-party-backend-and-opt-into-breaking-changes", + "notes": "Still required for GOAWAY draining in transport/http3.rs. Re-audit on any h3 bump." + }, + "m010_implication": "M010 cannot clear the upstream graduation row while #338/#339 remain unreleased. #361 remains an open cancellation wire-code limitation outside any supported cancellation claim. M012 hygiene refresh aligns Quinn pins with workspace Cargo.lock only.", + "m012_notes": "Nested qualification/embedded/*/Cargo.lock trees are separate evidence graphs; scripts/check_security.sh scans the workspace root lock only unless an operator runs a named embed evidence refresh." +} diff --git a/scripts/h3_impairment_netem.py b/scripts/h3_impairment_netem.py new file mode 100755 index 00000000..19e7b970 --- /dev/null +++ b/scripts/h3_impairment_netem.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +"""Linux netem runner for the HTTP/3 impairment matrix. + +Invoked by ``scripts/h3_impairment.py`` as ``--runner``. Qualification-only; +not used from Tier 1 CI. +""" + +from __future__ import annotations + +import json +import os +import platform +import re +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +MATRIX = ROOT / "qualification" / "http3" / "impairment-matrix.json" +STATUSES = {"pass", "fail", "unsupported"} + +# Recorded in JSON for packet-loss scenarios (plan §7). +PACKET_LOSS_LOW_RATE = "1%" +PACKET_LOSS_HIGH_RATE = "20%" + +NETEM_REQUIRED = frozenset( + { + "packet_loss_low", + "packet_loss_high", + "latency_jitter", + "packet_reordering", + "packet_duplication", + "reduced_mtu_pmtu_blackhole", + "path_loss_after_headers", + "path_loss_during_upload", + } +) + +# Scenario IDs are interpolated into `bash -lc` on the privileged netem path. +# Reject anything outside a strict identifier charset before any shell use, +# including direct argv invocation that bypasses matrix lookup. +_SCENARIO_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") + + +def validate_scenario_id(scenario_id: str) -> str: + """Fail closed on shell-unsafe or empty scenario identifiers.""" + if not isinstance(scenario_id, str) or not _SCENARIO_ID_RE.fullmatch(scenario_id): + raise ValueError( + "scenario_id must be 1–64 chars of [A-Za-z0-9_-] starting with alphanumeric" + ) + return scenario_id + + +def load_matrix(path: Path = MATRIX) -> dict: + with path.open(encoding="utf-8") as handle: + value = json.load(handle) + if not isinstance(value, dict) or value.get("schema_version") != 1: + raise ValueError("unsupported impairment matrix schema") + return value + + +def scenario_row(matrix: dict, scenario_id: str) -> dict: + validate_scenario_id(scenario_id) + for scenario in matrix["scenarios"]: + if scenario["id"] == scenario_id: + return scenario + raise ValueError(f"unknown impairment scenario {scenario_id}") + + +def invariant_map(scenario_id: str, status: str = "unsupported", matrix: dict | None = None) -> dict[str, str]: + matrix = matrix or load_matrix() + row = scenario_row(matrix, scenario_id) + return {name: status for name in row["invariants"]} + + +def write_runner_result( + output_path: Path, + scenario_id: str, + status: str, + invariants: dict[str, str], + **extra: object, +) -> None: + if status not in STATUSES: + raise ValueError(f"invalid status {status!r}") + payload: dict[str, object] = { + "status": status, + "scenario": scenario_id, + "invariants": invariants, + } + payload.update(extra) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + + +def validate_runner_result(observed: dict, scenario: dict) -> dict: + """Match ``scripts/h3_impairment.py`` ``execute`` acceptance rules.""" + scenario_id = scenario["id"] + if not isinstance(observed, dict) or observed.get("status") not in STATUSES: + return { + "scenario": scenario_id, + "status": "fail", + "error": "runner result must be an object with pass/fail/unsupported status", + } + invariants = observed.get("invariants") + required_invariants = set(scenario["invariants"]) + if not isinstance(invariants, dict) or not required_invariants.issubset(invariants): + return { + "scenario": scenario_id, + "status": "fail", + "error": "runner result must report every scenario invariant", + } + if observed["status"] == "pass" and any( + invariants[name] != "pass" for name in required_invariants + ): + observed = dict(observed) + observed["status"] = "fail" + observed["error"] = "overall pass conflicts with invariant result" + observed.setdefault("scenario", scenario_id) + return observed + + +def linux_netem_capabilities() -> tuple[bool, str]: + if platform.system() != "Linux": + return False, f"unsupported OS {platform.system()}" + for tool in ("unshare", "ip"): + if shutil.which(tool) is None: + return False, f"missing {tool}" + if shutil.which("tc") is None: + return False, "missing tc" + return True, "" + + +def _tc_netem_args(scenario_id: str) -> list[str]: + validate_scenario_id(scenario_id) + if scenario_id == "packet_loss_low": + return ["loss", PACKET_LOSS_LOW_RATE] + if scenario_id == "packet_loss_high": + return ["loss", PACKET_LOSS_HIGH_RATE] + if scenario_id == "latency_jitter": + return ["delay", "200ms", "50ms"] + if scenario_id == "packet_reordering": + return ["reorder", "25%", "50%"] + if scenario_id == "packet_duplication": + return ["duplicate", "10%"] + if scenario_id == "reduced_mtu_pmtu_blackhole": + return ["loss", "5%", "mtu", "576"] + if scenario_id in {"path_loss_after_headers", "path_loss_during_upload"}: + return ["loss", "80%"] + if scenario_id == "udp_blackhole": + return ["loss", "100%"] + return [] + + +def apply_netem_on_loopback(scenario_id: str) -> list[str]: + """Return tc netem argument tail for ``tc qdisc replace dev lo root netem ...``.""" + return _tc_netem_args(scenario_id) + + +def run_impairment_cargo_test( + scenario_id: str, + *, + netem_active: bool, + cwd: Path = ROOT, +) -> subprocess.CompletedProcess[str]: + validate_scenario_id(scenario_id) + env = dict(os.environ) + env["EGGFETCH_H3_IMPAIRMENT_SCENARIO"] = scenario_id + if netem_active: + env["EGGFETCH_H3_IMPAIRMENT_NETEM_ACTIVE"] = "1" + cmd = [ + "cargo", + "test", + "-p", + "eggfetch-core", + "--all-features", + "--test", + "h3_impairment_scenarios", + scenario_id, + "--", + "--test-threads=1", + "--exact", + "--nocapture", + ] + return subprocess.run( + cmd, + cwd=cwd, + env=env, + capture_output=True, + text=True, + check=False, + ) + + +def run_in_netns(scenario_id: str, output_path: Path) -> None: + """Linux privileged path: netem on lo inside a network namespace, then cargo test.""" + validate_scenario_id(scenario_id) + netem_args = apply_netem_on_loopback(scenario_id) + setup = ( + "set -e; " + "ip link set lo up; " + f"tc qdisc del dev lo root 2>/dev/null || true; " + ) + if netem_args: + setup += "tc qdisc replace dev lo root netem " + " ".join(netem_args) + "; " + setup += "exec env EGGFETCH_H3_IMPAIRMENT_OUTPUT=" + json.dumps(str(output_path)) + " " + setup += "EGGFETCH_H3_IMPAIRMENT_SCENARIO=" + json.dumps(scenario_id) + " " + setup += "EGGFETCH_H3_IMPAIRMENT_NETEM_ACTIVE=1 " + setup += "cargo test -p eggfetch-core --all-features --test h3_impairment_scenarios " + setup += scenario_id + " -- --test-threads=1 --exact --nocapture" + + unshare_cmd = [ + "unshare", + "--net", + "--", + "bash", + "-lc", + setup, + ] + subprocess.run(unshare_cmd, cwd=ROOT, check=False) + + +def main(argv: list[str] | None = None) -> int: + argv = list(sys.argv[1:] if argv is None else argv) + if len(argv) < 2: + print("usage: h3_impairment_netem.py SCENARIO_ID OUTPUT_JSON", file=sys.stderr) + return 2 + output_path = Path(argv[1]) + + matrix = load_matrix() + try: + scenario_id = validate_scenario_id(argv[0]) + row = scenario_row(matrix, scenario_id) + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 2 + + env = dict(os.environ) + env.setdefault("EGGFETCH_H3_IMPAIRMENT_SCENARIO", scenario_id) + env.setdefault("EGGFETCH_H3_IMPAIRMENT_OUTPUT", str(output_path)) + os.environ.update(env) + + ok, reason = linux_netem_capabilities() + needs_netem = scenario_id in NETEM_REQUIRED + + if needs_netem and not ok: + write_runner_result( + output_path, + scenario_id, + "unsupported", + invariant_map(scenario_id, "unsupported", matrix), + reason=reason or "netem runner unavailable", + ) + return 0 + + if needs_netem and ok: + try: + run_in_netns(scenario_id, output_path) + except OSError as exc: + write_runner_result( + output_path, + scenario_id, + "unsupported", + invariant_map(scenario_id, "unsupported", matrix), + reason=str(exc), + ) + return 0 + if output_path.exists(): + return 0 + write_runner_result( + output_path, + scenario_id, + "unsupported", + invariant_map(scenario_id, "unsupported", matrix), + reason="netem execution did not produce a result artifact", + ) + return 0 + + # Local scenarios: cargo test without netem (runner may still be invoked on macOS). + output_path.parent.mkdir(parents=True, exist_ok=True) + os.environ["EGGFETCH_H3_IMPAIRMENT_OUTPUT"] = str(output_path) + completed = run_impairment_cargo_test(scenario_id, netem_active=False) + if output_path.exists(): + return 0 + if completed.returncode == 0: + write_runner_result( + output_path, + scenario_id, + "fail", + invariant_map(scenario_id, "fail", matrix), + reason="cargo test succeeded but wrote no impairment artifact", + ) + else: + write_runner_result( + output_path, + scenario_id, + "fail", + invariant_map(scenario_id, "fail", matrix), + reason="cargo test failed", + output_tail=(completed.stdout + "\n" + completed.stderr).strip()[-4000:], + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) \ No newline at end of file diff --git a/scripts/h3_qualification.py b/scripts/h3_qualification.py index 544f1e80..145b695d 100644 --- a/scripts/h3_qualification.py +++ b/scripts/h3_qualification.py @@ -13,6 +13,7 @@ import argparse import json import os +import re import subprocess import sys from datetime import datetime, timezone @@ -32,6 +33,25 @@ "multiplexed_requests", "connection_reuse", } +CLIENT_DRIVEN_CASES = { + "cancellation_before_headers", + "cancellation_during_upload", + "cancellation_during_download", +} +SERVER_CONTROLLED_CASES = { + "stream_reset", + "graceful_connection_close", + "goaway_reconnect", + "alternative_port", +} +CONTROL_ENV_KEYS = { + "stream_reset": "EGGFETCH_H3_INTEROP_CONTROL_STREAM_RESET", + "graceful_connection_close": "EGGFETCH_H3_INTEROP_CONTROL_GRACEFUL_CONNECTION_CLOSE", + "goaway_reconnect": "EGGFETCH_H3_INTEROP_CONTROL_GOAWAY_RECONNECT", + "alternative_port": "EGGFETCH_H3_INTEROP_CONTROL_ALTERNATIVE_PORT", +} +KNOWN_CONTROL_KEYS = frozenset(CONTROL_ENV_KEYS) +CORPUS_CASE_LINE = re.compile(r"^H3_CORPUS_CASE (\w+)=(\w+)") STATUSES = {"pass", "fail", "unsupported", "not_run", "skip"} @@ -85,6 +105,25 @@ def validate_corpus(corpus: dict) -> list[dict]: return cases +def validate_controls(server: dict, index: int, capabilities: list[str]) -> dict[str, str]: + if "controls" not in server: + return {} + controls = server["controls"] + if not isinstance(controls, dict): + raise ManifestError(f"server {index} controls must be an object when present") + capability_set = set(capabilities) + validated: dict[str, str] = {} + for key, url in controls.items(): + if key not in KNOWN_CONTROL_KEYS: + raise ManifestError(f"server {index} declares unknown control key: {key!r}") + if key not in capability_set: + raise ManifestError( + f"server {index} control {key!r} is present but {key} is not in capabilities" + ) + validated[key] = validate_endpoint(url) + return validated + + def validate_server_manifest(manifest: dict, corpus: list[dict]) -> list[dict]: if manifest.get("schema_version") != 1: raise ManifestError("unsupported server manifest schema_version") @@ -122,7 +161,10 @@ def validate_server_manifest(manifest: dict, corpus: list[dict]) -> list[dict]: validate_endpoint(server["endpoint"]) if not isinstance(server.get("notes", ""), str): raise ManifestError(f"server {index} notes must be a string") - validated.append(server) + controls = validate_controls(server, index, capabilities) + server_entry = dict(server) + server_entry["validated_controls"] = controls + validated.append(server_entry) return validated @@ -153,6 +195,30 @@ def local_test_passed(output: str, test_name: str) -> bool: ) +def parse_corpus_case_lines(output: str) -> dict[str, str]: + observed: dict[str, str] = {} + for line in output.splitlines(): + match = CORPUS_CASE_LINE.match(line.strip()) + if match is None: + continue + case_id, status = match.group(1), match.group(2) + observed[case_id] = status + return observed + + +def attempted_cases_for_server(server: dict) -> list[str]: + capabilities = server["capabilities"] + controls = server.get("validated_controls") or {} + attempted: list[str] = [] + for case_id in capabilities: + if case_id in ALLOWED_CASES or case_id in CLIENT_DRIVEN_CASES: + attempted.append(case_id) + elif case_id in SERVER_CONTROLLED_CASES: + if controls.get(case_id): + attempted.append(case_id) + return sorted(attempted) + + def run_local(cases: list[dict], env: dict[str, str]) -> dict: command = [ "cargo", @@ -169,18 +235,27 @@ def run_local(cases: list[dict], env: dict[str, str]) -> dict: child_env.pop("EGGFETCH_H3_INTEROP_URLS", None) child_env.pop("EGGFETCH_H3_INTEROP_ENDPOINT", None) child_env.pop("EGGFETCH_H3_INTEROP_CASES", None) + for key in CONTROL_ENV_KEYS.values(): + child_env.pop(key, None) return_code, output = run_command(command, child_env, ROOT) known_local = { "get": "local_quinn_self_interop_get_and_body", "head": "h3_head_method_succeeds", "buffered_post": "h3_post_with_buffered_body_succeeds", + "streaming_upload": "h3_streaming_upload_succeeds", "large_streaming_download": "h3_large_streaming_download", "multiplexed_requests": "h3_concurrent_multiplexed_requests", "response_trailers": "h3_response_trailers_surface_after_eof", "cancellation_before_headers": "cancellation_during_h3_connect_is_prompt", + "cancellation_during_upload": "h3_cancellation_during_upload_is_prompt", + "cancellation_during_download": "h3_cancellation_during_download_is_prompt", "stream_reset": "h3_early_close_terminates_and_client_recovers", + "graceful_connection_close": "h3_graceful_connection_close_reconnects", + "goaway_reconnect": "h3_goaway_reconnect_observes_metrics", + "alternative_port": "h3_alternative_port_via_altsvc", "connection_reuse": "hundred_sequential_requests_on_reused_h3_connection", "server_restart": "server_restart_reconnects_on_next_request", + "ipv4": "h3_ipv4_loopback_get_succeeds", "ipv6": "ipv6_availability_is_detected_not_assumed", } results = [] @@ -205,14 +280,20 @@ def run_local(cases: list[dict], env: dict[str, str]) -> dict: def run_server(server: dict, corpus: list[dict], env: dict[str, str]) -> dict: capabilities = set(server["capabilities"]) - attempted = sorted(capabilities & ALLOWED_CASES) - results = [] + controls = server.get("validated_controls") or {} + attempted = attempted_cases_for_server(server) + results: list[dict] = [] for case in corpus: case_id = case["id"] if case_id not in capabilities: - results.append(case_result(case_id, "unsupported", reason="adapter did not declare capability")) + results.append( + case_result(case_id, "unsupported", reason="adapter did not declare capability") + ) elif case_id not in attempted: - results.append(case_result(case_id, "unsupported", reason="requires adapter-specific control")) + reason = "requires adapter-specific control" + if case_id in SERVER_CONTROLLED_CASES and not controls.get(case_id): + reason = "server-controlled case missing control URL" + results.append(case_result(case_id, "unsupported", reason=reason)) if not attempted: return { "implementation": server["implementation"], @@ -221,12 +302,16 @@ def run_server(server: dict, corpus: list[dict], env: dict[str, str]) -> dict: "endpoint": server["endpoint"], "status": "unsupported", "cases": results, - "notes": "No currently executable generic endpoint cases were declared.", + "notes": "No executable cases were declared (missing control URLs or generic cases).", } child_env = dict(env) child_env["EGGFETCH_H3_INTEROP_ENDPOINT"] = server["endpoint"] child_env["EGGFETCH_H3_INTEROP_CASES"] = ",".join(attempted) child_env.pop("EGGFETCH_H3_INTEROP_URLS", None) + for case_id, env_key in CONTROL_ENV_KEYS.items(): + child_env.pop(env_key, None) + for case_id, url in controls.items(): + child_env[CONTROL_ENV_KEYS[case_id]] = url command = [ "cargo", "test", @@ -242,19 +327,38 @@ def run_server(server: dict, corpus: list[dict], env: dict[str, str]) -> dict: "--test-threads=1", ] return_code, output = run_command(command, child_env, ROOT) - results.extend( - case_result(case_id, "pass" if return_code == 0 else "fail", implementation_test=True) - for case_id in attempted - ) + observed = parse_corpus_case_lines(output) + attempted_set = set(attempted) + results_by_case = {entry["case"]: entry for entry in results} + for case_id in attempted: + line_status = observed.get(case_id) + if line_status == "pass": + status = "pass" + reason = None + else: + status = "fail" + reason = ( + "external test did not print H3_CORPUS_CASE pass" + if return_code == 0 + else "external interop test failed" + ) + extra: dict[str, object] = {"implementation_test": True} + if reason is not None: + extra["reason"] = reason + if return_code != 0 and status == "fail": + extra["output"] = output + results_by_case[case_id] = case_result(case_id, status, **extra) + merged_cases = [results_by_case[case["id"]] for case in corpus if case["id"] in results_by_case] + any_fail = any(entry["status"] == "fail" for entry in merged_cases if entry["case"] in attempted_set) return { "implementation": server["implementation"], "version": server["version"], "identity": server["identity"], "endpoint": server["endpoint"], - "status": "pass" if return_code == 0 else "fail", + "status": "fail" if return_code != 0 or any_fail else "pass", "command": command, "return_code": return_code, - "cases": results, + "cases": merged_cases, "output_tail": output, } @@ -309,7 +413,11 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument( "--danger-accept-invalid-certs", action="store_true", - help="qualification-only opt-in for local adapter certificates; never use for public evidence", + help=( + "qualification-only opt-in that disables TLS certificate validation " + "(also via EGGFETCH_H3_INTEROP_DANGER_ACCEPT_INVALID_CERTS=1); " + "off by default; never enable for public/CI evidence or untrusted endpoints" + ), ) args = parser.parse_args(argv) try: @@ -336,9 +444,14 @@ def main(argv: list[str] | None = None) -> int: print(f"h3 qualification failed closed: {exc}", file=sys.stderr) return 2 print(json.dumps(result, indent=2)) + local_ok = result["deterministic_local"]["status"] == "pass" + if args.local_only: + # Local-only acceptance is the deterministic corpus. Independent + # servers stay blocked in the JSON and are never counted as passes. + return 0 if local_ok else 1 external_ok = result["independent_servers"]["status"] == "pass" - return 0 if result["deterministic_local"]["status"] == "pass" and external_ok else 1 + return 0 if local_ok and external_ok else 1 if __name__ == "__main__": - raise SystemExit(main()) + raise SystemExit(main()) \ No newline at end of file diff --git a/scripts/test_h3_qualification.py b/scripts/test_h3_qualification.py index 647cb08a..9f3a6ea9 100644 --- a/scripts/test_h3_qualification.py +++ b/scripts/test_h3_qualification.py @@ -16,6 +16,18 @@ MODULE = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(MODULE) +IMPAIRMENT_SCRIPT = Path(__file__).with_name("h3_impairment.py") +IMPAIRMENT_SPEC = importlib.util.spec_from_file_location("h3_impairment", IMPAIRMENT_SCRIPT) +assert IMPAIRMENT_SPEC and IMPAIRMENT_SPEC.loader +IMPAIRMENT = importlib.util.module_from_spec(IMPAIRMENT_SPEC) +IMPAIRMENT_SPEC.loader.exec_module(IMPAIRMENT) + +NETEM_SCRIPT = Path(__file__).with_name("h3_impairment_netem.py") +NETEM_SPEC = importlib.util.spec_from_file_location("h3_impairment_netem", NETEM_SCRIPT) +assert NETEM_SPEC and NETEM_SPEC.loader +NETEM = importlib.util.module_from_spec(NETEM_SPEC) +NETEM_SPEC.loader.exec_module(NETEM) + class QualificationManifestTests(unittest.TestCase): def setUp(self) -> None: @@ -63,6 +75,154 @@ def test_output_parent_can_be_created(self) -> None: output.write_text("{}\n", encoding="utf-8") self.assertTrue(output.exists()) + def test_control_urls_reject_credentials_and_queries(self) -> None: + manifest = { + "schema_version": 1, + "servers": [ + { + "implementation": "test", + "version": "1", + "identity": {"source_revision": "abc"}, + "endpoint": "https://example.test/", + "capabilities": ["goaway_reconnect"], + "controls": { + "goaway_reconnect": "https://user:pass@example.test/control", + }, + } + ], + } + with self.assertRaises(MODULE.ManifestError): + MODULE.validate_server_manifest(manifest, self.cases) + + def test_server_controlled_capability_without_control_is_not_executable(self) -> None: + server = { + "implementation": "test", + "version": "1", + "identity": {"source_revision": "abc"}, + "endpoint": "https://example.test/", + "capabilities": ["goaway_reconnect", "get"], + "validated_controls": {}, + } + attempted = MODULE.attempted_cases_for_server(server) + self.assertIn("get", attempted) + self.assertNotIn("goaway_reconnect", attempted) + + def test_unknown_control_key_is_rejected(self) -> None: + manifest = { + "schema_version": 1, + "servers": [ + { + "implementation": "test", + "version": "1", + "identity": {"source_revision": "abc"}, + "endpoint": "https://example.test/", + "capabilities": ["get"], + "controls": {"not_a_real_control": "https://example.test/x"}, + } + ], + } + with self.assertRaises(MODULE.ManifestError): + MODULE.validate_server_manifest(manifest, self.cases) + + def test_control_without_capability_is_rejected(self) -> None: + manifest = { + "schema_version": 1, + "servers": [ + { + "implementation": "test", + "version": "1", + "identity": {"source_revision": "abc"}, + "endpoint": "https://example.test/", + "capabilities": ["get"], + "controls": { + "goaway_reconnect": "https://example.test/goaway", + }, + } + ], + } + with self.assertRaises(MODULE.ManifestError): + MODULE.validate_server_manifest(manifest, self.cases) + + def test_parse_corpus_case_lines(self) -> None: + output = "\n".join( + [ + "running 1 test", + "H3_CORPUS_CASE get=pass endpoint=https://example.test/", + "H3_CORPUS_CASE goaway_reconnect=pass endpoint=https://example.test/", + ] + ) + observed = MODULE.parse_corpus_case_lines(output) + self.assertEqual(observed["get"], "pass") + self.assertEqual(observed["goaway_reconnect"], "pass") + + +class H3ImpairmentContractTests(unittest.TestCase): + def setUp(self) -> None: + self.matrix = NETEM.load_matrix() + + def test_missing_privileges_writes_all_invariants_unsupported(self) -> None: + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "packet_loss_low.json" + NETEM.write_runner_result( + output, + "packet_loss_low", + "unsupported", + NETEM.invariant_map("packet_loss_low", "unsupported", self.matrix), + reason="unit test: no netem", + packet_loss_rate=NETEM.PACKET_LOSS_LOW_RATE, + ) + with output.open(encoding="utf-8") as handle: + observed = json.load(handle) + row = NETEM.scenario_row(self.matrix, "packet_loss_low") + normalized = NETEM.validate_runner_result(observed, row) + self.assertEqual(normalized["status"], "unsupported") + for name in row["invariants"]: + self.assertEqual(observed["invariants"][name], "unsupported") + + def test_pass_with_failed_invariant_is_rejected(self) -> None: + row = NETEM.scenario_row(self.matrix, "udp_blackhole") + observed = { + "status": "pass", + "scenario": "udp_blackhole", + "invariants": { + "bounded_connect_or_total_deadline": "pass", + "Http3Only_does_not_fallback": "fail", + "resources_released": "pass", + }, + } + normalized = NETEM.validate_runner_result(observed, row) + self.assertEqual(normalized["status"], "fail") + self.assertIn("error", normalized) + + def test_unknown_scenario_id_rejected_by_matrix_load(self) -> None: + with self.assertRaises(ValueError): + NETEM.scenario_row(self.matrix, "not_a_real_scenario") + + def test_scenario_id_charset_rejected_before_shell_use(self) -> None: + for bad in ( + "packet_loss_low; rm -rf /", + "$(evil)", + "../escape", + "has space", + "", + "-leading-dash", + ): + with self.assertRaises(ValueError): + NETEM.validate_scenario_id(bad) + with self.assertRaises(ValueError): + NETEM.scenario_row(self.matrix, bad) + self.assertEqual(NETEM.validate_scenario_id("packet_loss_low"), "packet_loss_low") + + def test_coordinator_rejects_incomplete_invariants(self) -> None: + row = NETEM.scenario_row(self.matrix, "latency_jitter") + observed = { + "status": "pass", + "scenario": "latency_jitter", + "invariants": {"bounded_total_deadline": "pass"}, + } + normalized = NETEM.validate_runner_result(observed, row) + self.assertEqual(normalized["status"], "fail") + if __name__ == "__main__": unittest.main()