diff --git a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs index 96aca4a2e..0a04442ee 100644 --- a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs +++ b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs @@ -1,4 +1,9 @@ -//! Test-only source-bound proxy and verified TLS ingress. No response is collected here. +//! Test-only loopback proxy and verified TLS ingress. No response is collected here. +//! +//! Every proxy socket is on 127.0.0.1, the IPv4 loopback address every platform has, so the +//! server's direct peer is always a real 127.0.0.1 socket. An appending proxy writes the +//! predecessor it is given rather than its own socket peer: the server only sees that hop as +//! header text, and a real 127.0.0.1 predecessor would collide with the trusted peer. #![expect( clippy::arbitrary_source_item_ordering, reason = "fixture ownership precedes bounded relay helpers" @@ -27,18 +32,31 @@ use super::tests::reserve_or_spawn; const MAX_HEAD: usize = 0x8000; const RELAY_BUFFER: usize = 0x4000; +#[derive(Clone, Copy)] +pub(crate) struct Hop { + predecessor: IpAddr, + host: &'static str, + scheme: &'static str, +} + +impl Hop { + #[must_use] + #[inline] + pub(crate) const fn new(predecessor: IpAddr, host: &'static str, scheme: &'static str) -> Self { + Self { + predecessor, + host, + scheme, + } + } +} + #[derive(Clone, Copy)] pub(crate) enum Assertions { /// Keep deliberate malformed/gap inputs unchanged while preserving a real owned peer. Preserve, - AppendForwarded { - host: &'static str, - scheme: &'static str, - }, - AppendXForwarded { - host: &'static str, - scheme: &'static str, - }, + AppendForwarded(Hop), + AppendXForwarded(Hop), ReplaceForwarded { client: IpAddr, host: &'static str, @@ -61,12 +79,7 @@ impl LocalProxy { #[must_use] #[inline] - pub(crate) fn start( - upstream: SocketAddr, - source: Ipv4Addr, - assertions: Assertions, - tls: bool, - ) -> Self { + pub(crate) fn start(upstream: SocketAddr, assertions: Assertions, tls: bool) -> Self { let std_listener = { let _reserving = reserve_or_spawn(); StdTcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("proxy listener") @@ -93,13 +106,13 @@ impl LocalProxy { finished.map_err(io::Error::other)??; }, accepted = listener.accept(), if tasks.len() < 64 => { - let (socket, peer) = accepted?; + let (socket, _peer) = accepted?; let task_acceptor = tls_acceptor.clone(); tasks.spawn(async move { let operation = async { if let Some(acceptor) = task_acceptor { match acceptor.accept(socket).await { - Ok(mut client) => relay(&mut client, peer, upstream, source, assertions).await, + Ok(mut client) => relay(&mut client, upstream, assertions).await, // The wrong-name client sends this alert before any HTTP request. // Its test checks the exact certificate verification error separately. Err(error) if rejected_certificate(&error) => Ok(()), @@ -107,7 +120,7 @@ impl LocalProxy { } } else { let mut client = socket; - relay(&mut client, peer, upstream, source, assertions).await + relay(&mut client, upstream, assertions).await } }; timeout(Duration::from_secs(5), operation) @@ -203,7 +216,14 @@ where } } -fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result { +fn forwarded_node(address: IpAddr) -> String { + match address { + IpAddr::V4(ip) => ip.to_string(), + IpAddr::V6(ip) => format!("\"[{ip}]\""), + } +} + +fn rewrite(head: &str, assertions: Assertions) -> io::Result { let mut lines = head.split("\r\n"); let request = lines .next() @@ -214,13 +234,13 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result ip.to_string(), - IpAddr::V6(ip) => format!("\"[{ip}]\""), - }; match assertions { Assertions::Preserve => {} - Assertions::AppendForwarded { host, scheme } => { + Assertions::AppendForwarded(Hop { + predecessor, + host, + scheme, + }) => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("forwarded")) @@ -228,7 +248,8 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result>() .join(","); headers.retain(|(name, _)| !name.eq_ignore_ascii_case("forwarded")); - let assertion = format!("for={predecessor};host=\"{host}\";proto={scheme}"); + let node = forwarded_node(predecessor); + let assertion = format!("for={node};host=\"{host}\";proto={scheme}"); headers.push(( "Forwarded".into(), if previous.is_empty() { @@ -238,7 +259,11 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result { + Assertions::AppendXForwarded(Hop { + predecessor, + host, + scheme, + }) => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("x-forwarded-for")) @@ -246,7 +271,7 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result>() .join(","); headers.retain(|(name, _)| !name.to_ascii_lowercase().starts_with("x-forwarded-")); - let node = peer.ip().to_string(); + let node = predecessor.to_string(); headers.push(( "X-Forwarded-For".into(), if previous.is_empty() { @@ -269,10 +294,7 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result ip.to_string(), - IpAddr::V6(ip) => format!("\"[{ip}]\""), - }; + let node = forwarded_node(client); headers.push(( "Forwarded".into(), format!("for={node};host=\"{host}\";proto={scheme}"), @@ -293,20 +315,18 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result( client: &mut Client, - peer: SocketAddr, upstream: SocketAddr, - source: Ipv4Addr, assertions: Assertions, ) -> io::Result<()> where Client: AsyncRead + AsyncWrite + Unpin, { let (head, body_prefix) = read_head(client).await?; - let rewritten = rewrite(&head, peer, assertions)?; + let rewritten = rewrite(&head, assertions)?; let socket = { let _reserving = reserve_or_spawn(); let socket = TcpSocket::new_v4()?; - socket.bind(SocketAddr::new(IpAddr::V4(source), 0))?; + socket.bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0))?; socket }; let mut origin = socket.connect(upstream).await?; diff --git a/crates/edgezero-adapter-axum/tests/native_aws_startup.rs b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs index 8dd6478e1..a48713e86 100644 --- a/crates/edgezero-adapter-axum/tests/native_aws_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs @@ -4,17 +4,13 @@ //! They exercise the public runner and real pinned SDK, not a provider seam. No AWS account, //! DNS hostname, external socket, image, or real cloud credential is used. -#[cfg(test)] -#[path = "fixtures/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] #[expect( clippy::arbitrary_source_item_ordering, reason = "loopback fixture helpers remain grouped before startup scenarios" )] mod tests { - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::fmt::Write as _; use std::fs; use std::io::{self, ErrorKind, Read, Write as _}; diff --git a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs index 93174c07c..96cfd2849 100644 --- a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs @@ -10,6 +10,7 @@ #[cfg(test)] mod tests { + use edgezero_core::test_net::accept_blocking; use std::fs; use std::io::{ErrorKind, Read, Write as _}; use std::net::{SocketAddr, TcpListener, TcpStream}; @@ -72,7 +73,7 @@ mod tests { let worker_stop = Arc::clone(&stop); thread::spawn(move || { while !worker_stop.load(Ordering::Relaxed) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback()); stream diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index 88038d6cc..9198f8f58 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -11,7 +11,7 @@ mod native_proxy; reason = "subprocess fixtures group setup, process ownership and acceptance scenarios" )] mod tests { - use super::native_proxy::{Assertions, LocalProxy, verified_tls_request}; + use super::native_proxy::{Assertions, Hop, LocalProxy, verified_tls_request}; use std::collections::HashSet; use std::ffi::{OsStr, OsString}; use std::fs; @@ -32,11 +32,13 @@ mod tests { const WAIT: Duration = Duration::from_secs(5); const STARTUP_PROBE_TIMEOUT: Duration = Duration::from_millis(50); const BIND_IN_USE: &str = "startup bind: listener: address in use"; - const PROXY_SOURCE: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 2); - const INGRESS_SOURCE: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 3); /// Launch attempts before a host that keeps losing its released port fails the test. const SPAWN_ATTEMPTS: usize = 3; + /// The visitor address an appending test proxy reports as its predecessor. It lies outside + /// every trusted range, so a chain walk that accepts it stopped at the proxy's assertion. + const VISITOR: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)); + struct Roots { config: TempDir, cwd: TempDir, @@ -102,7 +104,7 @@ mod tests { let _reserving = reserve_or_spawn(); let socket = TcpSocket::new_v4().expect("port reservation socket"); socket - .bind(SocketAddr::from(([127, 0, 0, 1], 0))) + .bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))) .expect("port reservation"); let addr = socket.local_addr().expect("reserved address"); (addr, socket) @@ -578,13 +580,18 @@ mod tests { assert!(id.bytes().all(|byte| byte.is_ascii_hexdigit())); } - fn assert_peer_ip(value: &Value, expected: Ipv4Addr) { + fn assert_peer_ip(value: &Value, expected: Ipv4Addr, listener: SocketAddr) { let peer: SocketAddr = value["handler"]["peer"] .as_str() .expect("owned peer") .parse() .expect("socket peer"); assert_eq!(peer.ip(), IpAddr::V4(expected)); + assert_ne!( + peer.port(), + listener.port(), + "accepted peer must not be the listener" + ); } fn assert_no_diagnostic_headers(response: &str) { @@ -617,31 +624,6 @@ mod tests { launch } - fn require_proxy_sources(test: &str, sources: &[Ipv4Addr]) -> bool { - let mut available = true; - for &source in sources { - let _reserving = reserve_or_spawn(); - let socket = TcpSocket::new_v4().expect("proxy source probe socket"); - match socket.bind(SocketAddr::from((source, 0))) { - Ok(()) => {} - Err(error) - if cfg!(target_os = "macos") - && error.kind() == io::ErrorKind::AddrNotAvailable => - { - // Write directly to stderr so libtest does not capture a passing skip. - writeln!( - io::stderr().lock(), - "skipping {test}: cannot bind {source}; run `sudo ifconfig lo0 alias {source} up` and rerun" - ) - .expect("proxy skip notice"); - available = false; - } - Err(error) => panic!("{test} requires binding {source}: {error}"), - } - } - available - } - fn assert_final_zero(server: &Server) { let snapshots = captured_json(&server.log(), "FINAL_SNAPSHOT "); assert_eq!( @@ -735,7 +717,7 @@ mod tests { for field in ["client_source", "host_source", "scheme_source"] { assert_eq!(value["handler"][field], "direct"); } - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); let expected_bytes = request .split("\r\n") .skip(1) @@ -763,15 +745,14 @@ mod tests { } #[test] - fn native_source_bound_single_proxy_and_mapped_cidr_match_only_owned_peers() { - if !require_proxy_sources("native single-proxy test", &[PROXY_SOURCE]) { - return; - } + fn native_single_loopback_proxy_requires_matching_peer_cidr() { + // The mapped /127 truncates to 127.0.0.0/31, so 127.0.0.0/32 is the sibling of the + // peer inside that range and the one listed network that does not own it. for networks in [ - "127.0.0.2/32", - "::ffff:127.0.0.2/128", - "::ffff:127.0.0.2/127", - "127.0.0.3/32", + "127.0.0.1/32", + "::ffff:127.0.0.1/128", + "::ffff:127.0.0.1/127", + "127.0.0.0/32", ] { let roots = Roots::new(); let addr = address(); @@ -782,11 +763,7 @@ mod tests { server.ready(); let proxy = LocalProxy::start( server.addr(), - PROXY_SOURCE, - Assertions::AppendForwarded { - host: "public.example", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "public.example", "https")), false, ); let response = raw_request( @@ -796,10 +773,10 @@ mod tests { ), ); let value = response_json(&response); - let trusted = networks != "127.0.0.3/32"; + let trusted = networks != "127.0.0.0/32"; assert_metadata( &value, - Some(if trusted { "127.0.0.1" } else { "127.0.0.2" }), + Some(if trusted { "192.0.2.1" } else { "127.0.0.1" }), if trusted { "public.example" } else { @@ -812,7 +789,7 @@ mod tests { "untrusted_peer" }, ); - assert_peer_ip(&value, PROXY_SOURCE); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); assert_no_diagnostic_headers(&response); server.signal("TERM"); assert!(server.wait().success()); @@ -822,12 +799,13 @@ mod tests { #[test] fn native_two_proxy_chain_stops_at_untrusted_hop_and_gateway_replaces_prefix() { - if !require_proxy_sources("native two-proxy test", &[PROXY_SOURCE, INGRESS_SOURCE]) { - return; - } + // The ingress is the server's real 127.0.0.1 peer. It reports the first proxy as + // 192.0.2.2, and the first proxy reports the visitor, so the chain has three + // distinct hops: 198.51.100.99 (visitor-supplied), 192.0.2.1, then 192.0.2.2. + let first_proxy = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2)); for (networks, boundary) in [ - ("127.0.0.2/32,127.0.0.3/32", "127.0.0.1"), - ("127.0.0.3/32", "127.0.0.2"), + ("127.0.0.1/32,192.0.2.2/32", "192.0.2.1"), + ("127.0.0.1/32", "192.0.2.2"), ] { let roots = Roots::new(); let addr = address(); @@ -838,20 +816,12 @@ mod tests { server.ready(); let ingress = LocalProxy::start( server.addr(), - INGRESS_SOURCE, - Assertions::AppendForwarded { - host: "final.example", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(first_proxy, "final.example", "https")), false, ); let first = LocalProxy::start( ingress.addr(), - PROXY_SOURCE, - Assertions::AppendForwarded { - host: "earlier.example", - scheme: "http", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "earlier.example", "http")), false, ); let value = response_json(&raw_request( @@ -862,7 +832,7 @@ mod tests { )); assert_metadata(&value, Some(boundary), "final.example", "https", "accepted"); assert_eq!(value["handler"]["host_source"], "trusted_forwarded"); - assert_peer_ip(&value, INGRESS_SOURCE); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); server.signal("TERM"); assert!(server.wait().success()); assert_final_zero(&server); @@ -870,13 +840,12 @@ mod tests { let roots = Roots::new(); let addr = address(); let mut server = Server::spawn( - native_command("diagnostics", &roots, addr, "127.0.0.3/32", "forwarded"), + native_command("diagnostics", &roots, addr, "127.0.0.1/32", "forwarded"), addr, ); server.ready(); let gateway = LocalProxy::start( server.addr(), - INGRESS_SOURCE, Assertions::ReplaceForwarded { client: "203.0.113.7".parse().expect("verified gateway client"), host: "gateway.example", @@ -903,17 +872,17 @@ mod tests { } fn assert_missing_unresolved_and_duplicate_family(addr: SocketAddr, family: &str) { - // This source-bound relay preserves deliberate bad inputs rather than sanitizing them. - let gateway = LocalProxy::start(addr, PROXY_SOURCE, Assertions::Preserve, false); + // This trusted relay preserves deliberate bad inputs rather than sanitizing them. + let gateway = LocalProxy::start(addr, Assertions::Preserve, false); let absent = response_json(&raw_request(gateway.addr(), &metadata_request(""))); assert_metadata( &absent, - Some("127.0.0.2"), + Some("127.0.0.1"), "direct.example:8080", "http", "absent", ); - assert_peer_ip(&absent, PROXY_SOURCE); + assert_peer_ip(&absent, Ipv4Addr::LOCALHOST, addr); assert_eq!(absent["handler"]["client_source"], "direct"); let without_address = if family == "forwarded" { @@ -930,7 +899,7 @@ mod tests { if family == "forwarded" { None } else { - Some("127.0.0.2") + Some("127.0.0.1") }, "partial.example", "https", @@ -940,22 +909,23 @@ mod tests { "partial" }, ); - assert_peer_ip(&missing_client, PROXY_SOURCE); + assert_peer_ip(&missing_client, Ipv4Addr::LOCALHOST, addr); for headers in [ if family == "forwarded" { "Forwarded: for=unknown;host=gap.example;proto=https\r\n" } else { "X-Forwarded-For: unknown\r\nX-Forwarded-Host: gap.example\r\nX-Forwarded-Proto: https\r\n" }, + // The only hop is the trusted peer itself, so the walk exhausts the chain. if family == "forwarded" { - "Forwarded: for=127.0.0.2;host=gap.example;proto=https\r\n" + "Forwarded: for=127.0.0.1;host=gap.example;proto=https\r\n" } else { - "X-Forwarded-For: 127.0.0.2\r\nX-Forwarded-Host: gap.example\r\nX-Forwarded-Proto: https\r\n" + "X-Forwarded-For: 127.0.0.1\r\nX-Forwarded-Host: gap.example\r\nX-Forwarded-Proto: https\r\n" }, ] { let value = response_json(&raw_request(gateway.addr(), &metadata_request(headers))); assert_metadata(&value, None, "gap.example", "https", "unresolved_chain"); - assert_peer_ip(&value, PROXY_SOURCE); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, addr); let source = if family == "forwarded" { "trusted_forwarded" } else { @@ -978,39 +948,31 @@ mod tests { "http", "malformed", ); - assert_peer_ip(&malformed_duplicate, PROXY_SOURCE); + assert_peer_ip(&malformed_duplicate, Ipv4Addr::LOCALHOST, addr); } #[test] fn native_selected_families_conflicts_malformed_sets_gaps_and_exhaustion() { - if !require_proxy_sources("native forwarding-family test", &[PROXY_SOURCE]) { - return; - } for family in ["forwarded", "x-forwarded"] { let roots = Roots::new(); let addr = address(); let mut server = Server::spawn( - native_command("diagnostics", &roots, addr, "127.0.0.2/32", family), + native_command("diagnostics", &roots, addr, "127.0.0.1/32", family), addr, ); server.ready(); + let hop = Hop::new(VISITOR, "selected.example", "https"); let assertions = if family == "forwarded" { - Assertions::AppendForwarded { - host: "selected.example", - scheme: "https", - } + Assertions::AppendForwarded(hop) } else { - Assertions::AppendXForwarded { - host: "selected.example", - scheme: "https", - } + Assertions::AppendXForwarded(hop) }; - let proxy = LocalProxy::start(server.addr(), PROXY_SOURCE, assertions, false); + let proxy = LocalProxy::start(server.addr(), assertions, false); for (prefix, expected_result, client, host, scheme) in [ ( "Forwarded: for=198.51.100.1;host=wrong.example;proto=http\r\nX-Forwarded-For: 203.0.113.1\r\nX-Forwarded-Host: wrong.example\r\nX-Forwarded-Proto: http\r\n", "accepted", - Some("127.0.0.1"), + Some("192.0.2.1"), "selected.example", "https", ), @@ -1022,7 +984,7 @@ mod tests { "X-Forwarded-For: bad-address\r\n" }, "accepted", - Some("127.0.0.1"), + Some("192.0.2.1"), "selected.example", "https", ), @@ -1033,14 +995,14 @@ mod tests { "X-Forwarded-For: unknown\r\n" }, "accepted", - Some("127.0.0.1"), + Some("192.0.2.1"), "selected.example", "https", ), ] { let value = response_json(&raw_request(proxy.addr(), &metadata_request(prefix))); assert_metadata(&value, client, host, scheme, expected_result); - assert_peer_ip(&value, PROXY_SOURCE); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); } assert_missing_unresolved_and_duplicate_family(server.addr(), family); server.signal("TERM"); @@ -1062,23 +1024,16 @@ mod tests { #[test] fn native_verified_tls_ingress_overwrites_public_assertions_and_rejects_wrong_name() { - if !require_proxy_sources("native verified TLS test", &[PROXY_SOURCE]) { - return; - } let roots = Roots::new(); let addr = address(); let mut server = Server::spawn( - native_command("diagnostics", &roots, addr, "127.0.0.2/32", "forwarded"), + native_command("diagnostics", &roots, addr, "127.0.0.1/32", "forwarded"), addr, ); server.ready(); let proxy = LocalProxy::start( server.addr(), - PROXY_SOURCE, - Assertions::AppendForwarded { - host: "native-proxy.test", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "native-proxy.test", "https")), true, ); let request = metadata_request( @@ -1089,7 +1044,7 @@ mod tests { let value = response_json(&response); assert_metadata( &value, - Some("127.0.0.1"), + Some("192.0.2.1"), "native-proxy.test", "https", "accepted", @@ -1958,7 +1913,7 @@ mod tests { "https", "accepted", ); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); server.signal(shutdown); assert!(server.wait().success(), "{}", server.log()); diff --git a/crates/edgezero-cli/tests/celld_generated_proof.rs b/crates/edgezero-cli/tests/celld_generated_proof.rs index 61e913d54..5d286a4ab 100644 --- a/crates/edgezero-cli/tests/celld_generated_proof.rs +++ b/crates/edgezero-cli/tests/celld_generated_proof.rs @@ -14,6 +14,7 @@ mod tests { reason = "keep fixture ownership, generated source and proof steps together" )] + use edgezero_core::test_net::accept_blocking; use std::collections::BTreeMap; use std::env; #[cfg(target_os = "linux")] @@ -82,7 +83,7 @@ mod tests { ); let worker = thread::spawn(move || { while !worker_stop.load(Ordering::Relaxed) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback()); stream diff --git a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs index 2e264f082..e2e649672 100644 --- a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs +++ b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs @@ -7,11 +7,6 @@ //! fixture with dummy credentials and a cleared child environment. Serialize builds that share //! `EDGEZERO_GENERATED_TEST_TARGET_DIR`. -#[cfg(test)] -#[cfg(unix)] -#[path = "support/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] mod tests { #[cfg(unix)] @@ -21,7 +16,7 @@ mod tests { reason = "group test fixture types and their protocol helpers by responsibility" )] - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::collections::BTreeMap; use std::env; use std::fs; diff --git a/crates/edgezero-cli/tests/native_store_generated_proof.rs b/crates/edgezero-cli/tests/native_store_generated_proof.rs index e2d09a7f0..384d61cc3 100644 --- a/crates/edgezero-cli/tests/native_store_generated_proof.rs +++ b/crates/edgezero-cli/tests/native_store_generated_proof.rs @@ -20,15 +20,10 @@ //! `EDGEZERO_GENERATED_TEST_TARGET_DIR` can select a shared target directory; otherwise builds //! use the generated project's `target/`. Serialize builds that share a target directory. -#[cfg(test)] -#[cfg(unix)] -#[path = "support/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] #[cfg(unix)] mod tests { - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::env::var_os; use std::fs; use std::io::{ErrorKind, Read as _, Write as _}; diff --git a/crates/edgezero-cli/tests/support/blocking_accept.rs b/crates/edgezero-cli/tests/support/blocking_accept.rs deleted file mode 100644 index 2eb24b00c..000000000 --- a/crates/edgezero-cli/tests/support/blocking_accept.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Accept helper for test fixtures that poll a non-blocking std listener. - -use std::io; -use std::net::{SocketAddr, TcpListener, TcpStream}; - -/// Accepts one connection and returns its stream in blocking mode. -/// -/// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop -/// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a -/// read on the returned stream would otherwise fail with `WouldBlock` at once instead of -/// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. -#[inline] -pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { - let (stream, peer) = listener.accept()?; - stream.set_nonblocking(false)?; - Ok((stream, peer)) -} - -#[cfg(test)] -mod tests { - use super::accept_blocking; - use std::io::{ErrorKind, Read as _}; - use std::net::{TcpListener, TcpStream}; - use std::thread; - use std::time::{Duration, Instant}; - - #[test] - fn stream_accepted_from_nonblocking_listener_waits_for_read_timeout() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); - listener - .set_nonblocking(true) - .expect("nonblocking listener"); - let address = listener.local_addr().expect("listener address"); - let _client = TcpStream::connect(address).expect("connect loopback client"); - let deadline = Instant::now() - .checked_add(Duration::from_secs(2)) - .expect("deadline fits the monotonic clock"); - let (mut stream, _peer) = loop { - match accept_blocking(&listener) { - Ok(accepted) => break accepted, - Err(error) if error.kind() == ErrorKind::WouldBlock => { - assert!( - Instant::now() < deadline, - "loopback connection was not queued" - ); - thread::sleep(Duration::from_millis(5)); - } - Err(error) => panic!("accept failed: {error}"), - } - }; - stream - .set_read_timeout(Some(Duration::from_millis(200))) - .expect("read timeout"); - let started = Instant::now(); - let error = stream - .read(&mut [0_u8; 1]) - .expect_err("the client sent nothing"); - let waited = started.elapsed(); - assert!( - matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut), - "unexpected read error: {error}" - ); - assert!( - waited >= Duration::from_millis(150), - "read returned after {waited:?}, before its 200 ms timeout" - ); - } -} diff --git a/crates/edgezero-core/src/lib.rs b/crates/edgezero-core/src/lib.rs index 5be4dcfb9..5bff38cf9 100644 --- a/crates/edgezero-core/src/lib.rs +++ b/crates/edgezero-core/src/lib.rs @@ -54,6 +54,9 @@ pub mod store_registry; /// module docs. Enable via the `test-utils` feature in `[dev-dependencies]`. #[cfg(any(test, feature = "test-utils"))] pub mod test_env; +/// Native socket helpers for cross-crate test fixtures. +#[cfg(all(not(target_arch = "wasm32"), any(test, feature = "test-utils")))] +pub mod test_net; pub mod time; pub use body::{Body, BodyPayload, BodyStream}; diff --git a/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs b/crates/edgezero-core/src/test_net.rs similarity index 93% rename from crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs rename to crates/edgezero-core/src/test_net.rs index 2eb24b00c..e36c5b3aa 100644 --- a/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs +++ b/crates/edgezero-core/src/test_net.rs @@ -5,12 +5,16 @@ use std::net::{SocketAddr, TcpListener, TcpStream}; /// Accepts one connection and returns its stream in blocking mode. /// +/// # Errors +/// +/// Returns the listener accept error or an error restoring blocking mode. +/// /// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop /// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a /// read on the returned stream would otherwise fail with `WouldBlock` at once instead of /// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. #[inline] -pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { +pub fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { let (stream, peer) = listener.accept()?; stream.set_nonblocking(false)?; Ok((stream, peer)) diff --git a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs index 5138b58a5..7d26d2361 100644 --- a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs @@ -10,6 +10,7 @@ use super::*; use crate::dynamodb_kv::sdk_tests::{active_table, loopback_client, read_request}; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits}; use edgezero_core::record_store::{RecordKeyLayout, contract}; +use edgezero_core::test_net::accept_blocking; use edgezero_core::time::MonotonicClock; use serde_json::{Value, json}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; @@ -77,7 +78,7 @@ impl Fixture { let worker_stopped = Arc::clone(&stopped); let worker = thread::spawn(move || { while !worker_stopped.load(Ordering::Acquire) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, _)) => { stream .set_read_timeout(Some(Duration::from_secs(3))) diff --git a/crates/edgezero-store-aws/src/dynamodb_tests.rs b/crates/edgezero-store-aws/src/dynamodb_tests.rs index 037e2113d..7e28caec4 100644 --- a/crates/edgezero-store-aws/src/dynamodb_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_tests.rs @@ -12,6 +12,7 @@ use super::*; use crate::preparation::AwsPreparation; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits, DynamoDbKvSettings}; +use edgezero_core::test_net::accept_blocking; use edgezero_core::time::MonotonicClock; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::io::{ErrorKind, Read as _, Write as _}; @@ -144,7 +145,7 @@ impl DynamoFixture { let worker_accepted = Arc::clone(&accepted); let worker = thread::spawn(move || { while !worker_stopped.load(Ordering::Acquire) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, _)) => { worker_accepted.fetch_add(1, Ordering::Relaxed); stream.set_nonblocking(false).expect("blocking stream"); diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index eeba4009a..b98bc4dbc 100644 --- a/crates/edgezero-store-aws/src/secrets_manager.rs +++ b/crates/edgezero-store-aws/src/secrets_manager.rs @@ -148,10 +148,16 @@ impl AwsPreparation { .operation_timeout(operation_budget) .operation_attempt_timeout(attempt_budget) .build(); + let customized_request = request.customize(); + #[cfg(test)] + #[expect( + clippy::shadow_reuse, + reason = "test-only instrumentation keeps the production request path included in test builds" + )] + let customized_request = customized_request.interceptor(tests::SdkExecutionProbe); let result = timeout( operation_budget, - request - .customize() + customized_request .config_override( aws_sdk_secretsmanager::Config::builder().timeout_config(per_operation), ) @@ -197,6 +203,8 @@ impl AwsPreparation { } fn classify_operation_error(error: &SdkError) -> PreparationError { + #[cfg(test)] + tests::record_attempt_timeout(error); if matches!(error, SdkError::TimeoutError(_)) || matches!(error, SdkError::DispatchFailure(failure) if failure.is_timeout()) { @@ -307,16 +315,53 @@ mod tests { use aws_sdk_secretsmanager::operation::get_secret_value::GetSecretValueOutput; use aws_sdk_secretsmanager::primitives::Blob; use bytes::Bytes; + use edgezero_core::test_net::accept_blocking; use std::io::{Error as IoError, ErrorKind}; use std::io::{Read as _, Write as _}; use std::net::{TcpListener, TcpStream}; use std::process::{Command, Stdio}; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::thread; use std::time::{Duration, Instant}; + /// How long the holding fixture waits for the client to abandon an unanswered attempt. + /// This bounds the fixture read after accept; it does not identify the client's timeout + /// cause, since an attempt may already have ended before the fixture accepts it. + const HOLD_BOUND: Duration = Duration::from_secs(5); + const TEST_ARN: &str = "arn:aws:secretsmanager:us-east-1:111122223333:secret:fixture-AbCdEf"; static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + static SDK_EXECUTIONS: AtomicU64 = AtomicU64::new(0); + static OBSERVED_ATTEMPT_TIMEOUT: AtomicBool = AtomicBool::new(false); + + #[derive(Debug)] + pub(super) struct SdkExecutionProbe; + + #[expect( + clippy::missing_trait_methods, + reason = "the execution observer must retain the SDK defaults for every other pipeline hook" + )] + impl aws_sdk_secretsmanager::config::Intercept for SdkExecutionProbe { + fn name(&self) -> &'static str { + "test-sdk-execution-count" + } + + fn read_before_execution( + &self, + _context: &aws_sdk_secretsmanager::config::interceptors::BeforeSerializationInterceptorContextRef<'_>, + _config: &mut aws_sdk_secretsmanager::config::ConfigBag, + ) -> Result<(), aws_smithy_runtime_api::box_error::BoxError> { + SDK_EXECUTIONS.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + } + + /// One connection the SDK opened against `holding_fixture`. + struct HeldConnection { + /// The client closed the connection within `HOLD_BOUND`. + closed_by_client: bool, + } struct LoopbackFixture { listener: TcpListener, @@ -338,7 +383,6 @@ mod tests { #[derive(Clone)] enum FixtureResponse { Decryption, - Delay(Duration), Denied, InternalError, InvalidRequest, @@ -348,6 +392,44 @@ mod tests { Success, } + pub(super) fn record_attempt_timeout( + error: &SdkError, + ) { + if !matches!(error, SdkError::TimeoutError(_)) { + return; + } + // aws-smithy-runtime 1.16.0 exposes no typed kind/duration accessor for its private + // MaybeTimeoutError. Recheck this exact comparison when upgrading the pinned SDK. + // Source text is compared locally and never printed or retained. + let mut source: Option<&dyn std::error::Error> = Some(error); + while let Some(source_error) = source { + if source_error.to_string() + == "operation attempt timeout (single attempt) occurred after 100ms" + { + OBSERVED_ATTEMPT_TIMEOUT.store(true, Ordering::Relaxed); + } + source = source_error.source(); + } + } + + #[expect( + clippy::print_stdout, + reason = "only fixed verified timeout markers reach the parent fixture" + )] + fn report_timeout_evidence() { + assert_eq!( + SDK_EXECUTIONS.load(Ordering::Relaxed), + 1, + "preparation must issue one SDK send; the SDK alone owns retries" + ); + assert!( + OBSERVED_ATTEMPT_TIMEOUT.load(Ordering::Relaxed), + "the pinned SDK must report the exact 100 ms attempt timeout before sanitization" + ); + println!("sdk-executions: 1"); + println!("sdk-attempt-timeout: 100ms"); + } + fn assert_sdk_fixture_scope() { let endpoint = std::env::var("AWS_ENDPOINT_URL_SECRETS_MANAGER").expect("fixture endpoint required"); @@ -364,58 +446,84 @@ mod tests { ); } - fn respond(mut stream: TcpStream, response: FixtureResponse) -> (String, String) { - stream - .set_read_timeout(Some(Duration::from_secs(3))) - .expect("request read timeout"); - let mut request = Vec::new(); - let mut chunk = [0_u8; 4096]; - let header_end = loop { - let read = stream.read(&mut chunk).expect("read request headers"); - assert_ne!(read, 0, "SDK closed before request headers"); - request.extend_from_slice(&chunk[..read]); - if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") { - break end - .checked_add(4) - .expect("header terminator offset fits request"); - } - assert!(request.len() < 64 * 1024, "bounded fixture request headers"); - }; - let headers = String::from_utf8_lossy(&request[..header_end]).to_ascii_lowercase(); - let content_length = headers + /// Decode and validate complete SDK requests; timeout attempts may close before completion. + #[expect( + clippy::unwrap_in_result, + reason = "None means incomplete; malformed fixture requests must fail rather than look incomplete" + )] + fn decode_request(received: &[u8]) -> Option<(String, String)> { + let header_end = received + .windows(4) + .position(|bytes| bytes == b"\r\n\r\n")? + .checked_add(4) + .expect("header offset fits request"); + let headers = String::from_utf8_lossy(&received[..header_end]).to_ascii_lowercase(); + let length = headers .lines() .find_map(|line| line.strip_prefix("content-length:").map(str::trim)) .and_then(|value| value.parse::().ok()) .expect("SDK content length"); let body_end = header_end - .checked_add(content_length) + .checked_add(length) .expect("bounded request body end fits usize"); - while request.len() < body_end { - let read = stream.read(&mut chunk).expect("read request body"); - assert_ne!(read, 0, "SDK closed before request body"); - request.extend_from_slice(&chunk[..read]); - } - let body = String::from_utf8_lossy(&request[header_end..body_end]).into_owned(); + let body = String::from_utf8_lossy(received.get(header_end..body_end)?).into_owned(); assert!(headers.contains("x-amz-target: secretsmanager.getsecretvalue")); assert!( body.contains(TEST_ARN), - "request must contain only the fictional fixture ARN" + "request must contain the fictional fixture ARN" ); - if let FixtureResponse::Delay(delay) = response { - thread::sleep(delay); - let payload = b"{\"SecretString\":\"VALUE_SENTINEL\"}"; - let _header_write = write!( - stream, - "HTTP/1.1 200 OK\r\nContent-Type: application/x-amz-json-1.1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", - payload.len() - ); - let _body_write = stream.write_all(payload); - return (headers, body); - } + Some((headers, body)) + } + + #[test] + fn fixture_decoder_waits_for_complete_headers_and_body() { + let body = serde_json::json!({"SecretId": TEST_ARN}).to_string(); + let head = format!( + "POST / HTTP/1.1\r\nX-Amz-Target: secretsmanager.GetSecretValue\r\nContent-Length: {}\r\n\r\n", + body.len() + ); + assert!(decode_request(b"POST / HTTP/1.1\r\n").is_none()); + assert!(decode_request(head.as_bytes()).is_none()); + let request = format!("{head}{body}"); + let (headers, decoded) = decode_request(request.as_bytes()).expect("complete request"); + assert!(headers.contains("x-amz-target: secretsmanager.getsecretvalue")); + assert_eq!(decoded, body); + } + + #[test] + #[should_panic(expected = "SDK closed before the complete request")] + fn scripted_fixture_rejects_incomplete_request() { + let listener = TcpListener::bind("127.0.0.1:0").expect("fixture listener"); + let mut client = + TcpStream::connect(listener.local_addr().expect("address")).expect("client"); + client + .write_all(b"POST / HTTP/1.1\r\n") + .expect("partial headers"); + client + .shutdown(std::net::Shutdown::Write) + .expect("close incomplete request"); + let (stream, _) = accept_blocking(&listener).expect("accept"); + let _response = respond(stream, FixtureResponse::Success); + } + + fn respond(mut stream: TcpStream, response: FixtureResponse) -> (String, String) { + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("request read timeout"); + let mut request = Vec::new(); + let mut chunk = [0_u8; 4096]; + let (headers, body) = loop { + if let Some(decoded) = decode_request(&request) { + break decoded; + } + let read = stream.read(&mut chunk).expect("read complete SDK request"); + assert_ne!(read, 0, "SDK closed before the complete request"); + request.extend_from_slice(&chunk[..read]); + assert!(request.len() < 64 * 1024, "bounded fixture request"); + }; let (status, code, payload) = match response { FixtureResponse::Decryption => (400_u16, "Bad Request", r#"{"__type":"DecryptionFailure","message":"VALUE_SENTINEL"}"#.to_owned()), FixtureResponse::Denied => (400_u16, "Bad Request", r#"{"__type":"AccessDeniedException","message":"ARN_SENTINEL CREDENTIAL_SENTINEL"}"#.to_owned()), - FixtureResponse::Delay(_) => return (headers, body), FixtureResponse::InternalError => (500_u16, "Internal Server Error", r#"{"__type":"InternalServiceError","message":"SDK_ERROR_SENTINEL"}"#.to_owned()), FixtureResponse::InvalidRequest => (400_u16, "Bad Request", r#"{"__type":"InvalidRequestException","message":"ARN_SENTINEL is scheduled for deletion"}"#.to_owned()), FixtureResponse::Json(payload) => (200_u16, "OK", payload), @@ -431,6 +539,82 @@ mod tests { (headers, body) } + /// Accepts every connection the SDK opens and never answers, so the client's attempt + /// deadline is the only thing that ends each attempt. The deadline runs from the start of + /// the attempt, so a descheduled child can abandon a connection before writing its request; + /// that is recorded as a client-side close, not treated as a fixture failure. + fn holding_fixture() -> ( + String, + Arc, + thread::JoinHandle>, + ) { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind literal loopback only"); + listener + .set_nonblocking(true) + .expect("nonblocking listener"); + let endpoint = format!( + "http://{}", + listener.local_addr().expect("loopback address") + ); + let stop = Arc::new(AtomicBool::new(false)); + let worker_stop = Arc::clone(&stop); + let worker = thread::spawn(move || { + let deadline = Instant::now() + .checked_add(Duration::from_secs(30)) + .expect("fixture deadline fits the monotonic clock"); + let mut held = Vec::new(); + loop { + // Read the flag before accepting: once the child has exited, every connection it + // opened is already queued, so draining until `WouldBlock` counts all of them. + let stopping = worker_stop.load(Ordering::Acquire); + match accept_blocking(&listener) { + Ok((stream, peer)) => { + assert!(peer.ip().is_loopback(), "fixture peer must be loopback"); + held.push(hold(stream)); + } + Err(error) if error.kind() == ErrorKind::WouldBlock => { + if stopping { + break; + } + assert!(Instant::now() < deadline, "SDK child did not finish"); + thread::sleep(Duration::from_millis(5)); + } + Err(error) => panic!("fixture accept failed: {error}"), + } + } + held + }); + (endpoint, stop, worker) + } + + fn hold(mut stream: TcpStream) -> HeldConnection { + stream + .set_read_timeout(Some(HOLD_BOUND)) + .expect("held connection bound"); + let mut received = Vec::new(); + let mut chunk = [0_u8; 4096]; + let closed_by_client = loop { + match stream.read(&mut chunk) { + Ok(0) => break true, + Ok(read) => { + received.extend_from_slice(&chunk[..read]); + assert!(received.len() < 64 * 1024, "bounded held request"); + } + Err(error) if error.kind() == ErrorKind::ConnectionReset => break true, + Err(error) + if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => + { + break false; + } + Err(error) => panic!("held connection read failed: {error}"), + } + }; + // Complete requests are validated identically to scripted responses; an attempt + // that times out before writing its full request remains legitimate. + let _request = decode_request(&received); + HeldConnection { closed_by_client } + } + fn loopback_fixture(responses: Vec) -> (String, LoopbackFixture) { let listener = TcpListener::bind("127.0.0.1:0").expect("bind literal loopback only"); listener @@ -447,7 +631,7 @@ mod tests { let mut bodies = Vec::new(); for response in responses { let stream = loop { - match worker_listener.accept() { + match accept_blocking(&worker_listener) { Ok((stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture peer must be loopback"); break stream; @@ -788,19 +972,32 @@ mod tests { #[test] fn real_sdk_attempt_timeout_is_observed_without_an_outer_retry_loop() { - let (endpoint, fixture) = - loopback_fixture(vec![FixtureResponse::Delay(Duration::from_millis(350))]); + let (endpoint, stop, fixture) = holding_fixture(); let child = isolated_sdk_child(&endpoint, "timeout"); - let requests = fixture.join().expect("fixture thread"); + stop.store(true, Ordering::Release); + let held = fixture.join().expect("fixture thread"); assert!( child.status.success(), "timeout child failed: {}", String::from_utf8_lossy(&child.stderr) ); - assert_eq!( - requests.len(), - 1, - "SDK timeout behavior is inside the one provider operation" + let output = String::from_utf8_lossy(&child.stdout); + assert!( + output.contains("sdk-executions: 1\n"), + "exactly one SDK send is required" + ); + assert!( + output.contains("sdk-attempt-timeout: 100ms\n"), + "the SDK must identify the configured 100 ms attempt timeout" + ); + assert!( + (1..=3).contains(&held.len()), + "only the SDK's own attempts (at most 3) reach the fixture: {} connections", + held.len() + ); + assert!( + held.iter().all(|connection| connection.closed_by_client), + "the SDK must abandon every unanswered fixture connection" ); } @@ -813,6 +1010,10 @@ mod tests { clippy::print_stdout, reason = "the child reports its closed error category to the parent fixture" )] + #[expect( + clippy::too_many_lines, + reason = "one child entry point maps every scripted SDK scenario to its expected outcome" + )] #[tokio::test] async fn sdk_child_entry() { let Ok(scenario) = std::env::var("EDGEZERO_SECRETS_SCENARIO") else { @@ -836,8 +1037,10 @@ mod tests { crate::settings::AwsPreparationLimits { connect_timeout_ms: 50, attempt_timeout_ms: 100, - operation_timeout_ms: 500, - preparation_timeout_ms: 2_000, + // Far beyond the attempt deadline, so only the attempt deadline can end an + // unanswered attempt. + operation_timeout_ms: 10_000, + preparation_timeout_ms: 12_000, ..crate::settings::AwsPreparationLimits::default() } } else { @@ -849,6 +1052,9 @@ mod tests { ) .expect("valid session"); let result = session.prepare_secrets(&settings, "runtime").await; + if scenario == "timeout" { + report_timeout_evidence(); + } match scenario.as_str() { "retry" | "current" | "stage" | "version" | "dedup" => { let handle = result.expect("fixture-backed mapped secret prepares"); diff --git a/crates/edgezero-test-harness/src/main.rs b/crates/edgezero-test-harness/src/main.rs index 25a6514b8..ab4889422 100644 --- a/crates/edgezero-test-harness/src/main.rs +++ b/crates/edgezero-test-harness/src/main.rs @@ -1487,11 +1487,17 @@ mod process_tests { return; }; let path = PathBuf::from(std::env::var_os("EDGEZERO_PROCESS_TEST_DIR").unwrap()); - if mode == "static-check" { + if matches!(mode.as_str(), "static-check" | "cargo-cancellation") { let arguments = serde_json::from_str(&std::env::var("EDGEZERO_STATIC_CHECK_ARGS").unwrap()) .unwrap(); - exit_result(run(arguments)); + let result = if mode == "cargo-cancellation" { + // Supervisor fixtures exercise fake Cargo, not source/compiler fingerprinting. + startup::with_fixture_build_id(TEST_BUILD_ID, || run(arguments)) + } else { + run(arguments) + }; + exit_result(result); } if mode == "acceptance-blocked-git" { let ready = path.join("git-started"); @@ -1879,6 +1885,13 @@ case "$1" in esac "#).unwrap(); fs::set_permissions(&cargo, fs::Permissions::from_mode(0o700)).unwrap(); + let compiler = fixture.0.join("rustc"); + fs::write( + &compiler, + "#!/bin/sh\ncase \"$1\" in\n --version) printf 'rustc process-fixture\\n' ;;\n *) exit 64 ;;\nesac\n", + ) + .unwrap(); + fs::set_permissions(&compiler, fs::Permissions::from_mode(0o700)).unwrap(); let viceroy = fixture.0.join("viceroy"); let pins = fs::read_to_string(repository_root().join(".tool-versions")).unwrap(); let version = pins @@ -1894,13 +1907,14 @@ esac let output = fixture.0.join("evidence"); let mut command = static_check_command(&fixture, "--help"); command + .env("EDGEZERO_PROCESS_TEST_MODE", "cargo-cancellation") .env( "EDGEZERO_STATIC_CHECK_ARGS", json!(["--adapter", adapter, "--suite", suite, "--output", output,]).to_string(), ) .env("EDGEZERO_TEST_HELPER", std::env::current_exe().unwrap()) .env("CARGO", &cargo) - .env("RUSTC", executable("RUSTC", "rustc").unwrap()) + .env("RUSTC", &compiler) .env("WRANGLER_BIN", &cargo) .env("WORKER_BUILD_BIN", &cargo); command.env("VICEROY_BIN", &viceroy); @@ -1961,6 +1975,9 @@ esac descendant_closed, "{adapter}: Cargo descendant retained its socket" ); + let events = fs::read_to_string(output.join("events.jsonl")).unwrap(); + let run: serde_json::Value = serde_json::from_str(events.lines().next().unwrap()).unwrap(); + assert_eq!(run["fixture_build_id"], TEST_BUILD_ID); } #[test] diff --git a/crates/edgezero-test-harness/src/startup.rs b/crates/edgezero-test-harness/src/startup.rs index 018bec708..ca0298fa7 100644 --- a/crates/edgezero-test-harness/src/startup.rs +++ b/crates/edgezero-test-harness/src/startup.rs @@ -26,6 +26,8 @@ const UNATTESTED_FAULT_PATHS: &[&str] = &[ static LAUNCHES: Mutex>>> = Mutex::new(Vec::new()); thread_local! { static CURRENT: RefCell>>> = const { RefCell::new(None) }; + #[cfg(test)] + static FIXTURE_BUILD_ID: RefCell> = const { RefCell::new(None) }; } #[derive(Clone)] @@ -61,9 +63,25 @@ pub struct Launch { } pub fn build_id() -> Result { + #[cfg(test)] + if let Some(identity) = FIXTURE_BUILD_ID.with_borrow(|identity| *identity) { + return Ok(identity.to_owned()); + } build_identity::current() } +#[cfg(test)] +pub(crate) fn with_fixture_build_id(identity: &'static str, run: impl FnOnce() -> T) -> T { + struct Restore(Option<&'static str>); + impl Drop for Restore { + fn drop(&mut self) { + FIXTURE_BUILD_ID.with_borrow_mut(|identity| *identity = self.0); + } + } + let _restore = Restore(FIXTURE_BUILD_ID.with_borrow_mut(|id| id.replace(identity))); + run() +} + pub fn owned_process_group(port: u16) -> Result { let registered = find(port).ok_or("no owned runtime for this port")?; let mut launch = registered.lock().unwrap(); @@ -318,6 +336,23 @@ pub fn remaining(port: u16, budget: Duration) -> Result { mod identity_tests { use super::*; + #[test] + fn fixture_identity_restores_real_capture_after_nested_unwind() { + let real = build_id().unwrap(); + with_fixture_build_id("outer-fixture", || { + assert_eq!(build_id().unwrap(), "outer-fixture"); + let failed = std::panic::catch_unwind(|| { + with_fixture_build_id("inner-fixture", || { + assert_eq!(build_id().unwrap(), "inner-fixture"); + panic!("controlled fixture unwind"); + }); + }); + assert!(failed.is_err()); + assert_eq!(build_id().unwrap(), "outer-fixture"); + }); + assert_eq!(build_id().unwrap(), real); + } + #[test] fn unchanged_build_identity_keeps_each_launch_nonce_fresh() { let mut first = Command::new("unused-test-command");