From 450122063e89ef6c8905d306e68482f855417ca0 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 15:13:47 +0530 Subject: [PATCH 1/8] test: restore blocking mode on streams accepted by std fixtures Fixtures that poll a non-blocking std TcpListener read the accepted stream with set_read_timeout. macOS accept(2) copies O_NONBLOCK to the accepted socket (Linux does not), so those reads failed with WouldBlock at once and tests failed at random on macOS under parallel load. Add a small accept_blocking helper per crate (store-aws, adapter-axum tests, cli tests) that restores blocking mode, route all nine accept sites through it, and cover it with a test that fails on macOS when the accepted stream does not wait for its read timeout. --- .../tests/fixtures/blocking_accept.rs | 68 +++++++++++++++++++ .../tests/native_aws_startup.rs | 7 +- .../tests/native_celld_startup.rs | 7 +- .../tests/celld_generated_proof.rs | 8 ++- .../tests/dynamodb_generated_proof.rs | 8 ++- .../tests/native_store_generated_proof.rs | 10 ++- .../tests/support/blocking_accept.rs | 68 +++++++++++++++++++ .../src/dynamodb_records_tests.rs | 3 +- .../edgezero-store-aws/src/dynamodb_tests.rs | 3 +- crates/edgezero-store-aws/src/lib.rs | 6 ++ .../edgezero-store-aws/src/secrets_manager.rs | 3 +- crates/edgezero-store-aws/src/test_net.rs | 68 +++++++++++++++++++ 12 files changed, 250 insertions(+), 9 deletions(-) create mode 100644 crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs create mode 100644 crates/edgezero-cli/tests/support/blocking_accept.rs create mode 100644 crates/edgezero-store-aws/src/test_net.rs diff --git a/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs b/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs new file mode 100644 index 000000000..2eb24b00c --- /dev/null +++ b/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs @@ -0,0 +1,68 @@ +//! 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-adapter-axum/tests/native_aws_startup.rs b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs index a0b6283ce..849f268c8 100644 --- a/crates/edgezero-adapter-axum/tests/native_aws_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs @@ -4,12 +4,17 @@ //! 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 std::fmt::Write as _; use std::fs; use std::io::{ErrorKind, Read, Write as _}; @@ -83,7 +88,7 @@ mod tests { .checked_add(watch) .expect("fixture deadline fits the monotonic clock"); loop { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture peer was not loopback"); stream diff --git a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs index a9dbe9c54..8d057f909 100644 --- a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs @@ -8,8 +8,13 @@ reason = "fixture helpers precede startup scenarios" )] +#[cfg(test)] +#[path = "fixtures/blocking_accept.rs"] +mod blocking_accept; + #[cfg(test)] mod tests { + use crate::blocking_accept::accept_blocking; use std::fs; use std::io::{ErrorKind, Read, Write as _}; use std::net::{SocketAddr, TcpListener, TcpStream}; @@ -47,7 +52,7 @@ mod tests { thread::spawn(move || { let deadline = Instant::now().checked_add(WAIT).expect("fixture deadline"); while !worker_stop.load(Ordering::Relaxed) && Instant::now() < deadline { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback()); stream diff --git a/crates/edgezero-cli/tests/celld_generated_proof.rs b/crates/edgezero-cli/tests/celld_generated_proof.rs index 8b96613bd..fcfd83537 100644 --- a/crates/edgezero-cli/tests/celld_generated_proof.rs +++ b/crates/edgezero-cli/tests/celld_generated_proof.rs @@ -4,6 +4,11 @@ //! `EDGEZERO_CELLD_STORE_SERVICE`, Node.js and OpenSSL; missing tools are //! failures, not skips. +#[cfg(test)] +#[cfg(unix)] +#[path = "support/blocking_accept.rs"] +mod blocking_accept; + #[cfg(test)] #[cfg(unix)] mod tests { @@ -12,6 +17,7 @@ mod tests { reason = "keep fixture ownership, generated source and proof steps together" )] + use crate::blocking_accept::accept_blocking; use std::collections::BTreeMap; use std::env; use std::fmt::Write as _; @@ -76,7 +82,7 @@ mod tests { let worker = thread::spawn(move || { let end = deadline(Duration::from_mins(10)); while !worker_stop.load(Ordering::Relaxed) && Instant::now() < end { - 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 3cadaabdf..aa13389d3 100644 --- a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs +++ b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs @@ -7,6 +7,11 @@ //! 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)] @@ -16,6 +21,7 @@ mod tests { reason = "group test fixture types and their protocol helpers by responsibility" )] + use crate::blocking_accept::accept_blocking; use std::collections::BTreeMap; use std::env; use std::fs; @@ -64,7 +70,7 @@ mod tests { let worker = thread::spawn(move || { let deadline = deadline_after(Duration::from_mins(3)); while !worker_stop.load(Ordering::Relaxed) && Instant::now() < deadline { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture accepts loopback only"); stream diff --git a/crates/edgezero-cli/tests/native_store_generated_proof.rs b/crates/edgezero-cli/tests/native_store_generated_proof.rs index 8675e585a..c15981573 100644 --- a/crates/edgezero-cli/tests/native_store_generated_proof.rs +++ b/crates/edgezero-cli/tests/native_store_generated_proof.rs @@ -20,10 +20,16 @@ //! `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 std::env::var_os; use std::fs; use std::io::{ErrorKind, Read as _, Write as _}; @@ -114,7 +120,7 @@ mod tests { let mut extra = Vec::new(); let deadline = deadline_after(SERVICE_GRACE); while Instant::now() < deadline { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut extra_stream, peer)) => { assert!(peer.ip().is_loopback(), "only literal loopback peers"); extra_stream @@ -304,7 +310,7 @@ mod tests { fn accept_before(listener: &TcpListener, deadline: Instant) -> (TcpStream, SocketAddr) { loop { - match listener.accept() { + match accept_blocking(listener) { Ok((stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture peer must be loopback"); return (stream, peer); diff --git a/crates/edgezero-cli/tests/support/blocking_accept.rs b/crates/edgezero-cli/tests/support/blocking_accept.rs new file mode 100644 index 000000000..2eb24b00c --- /dev/null +++ b/crates/edgezero-cli/tests/support/blocking_accept.rs @@ -0,0 +1,68 @@ +//! 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-store-aws/src/dynamodb_records_tests.rs b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs index 93e431f6a..738c845c1 100644 --- a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs @@ -9,6 +9,7 @@ use super::*; use crate::dynamodb_kv::sdk_tests::{active_table, loopback_client, read_request}; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits}; +use crate::test_net::accept_blocking; use edgezero_core::record_store::{RecordKeyLayout, contract}; use edgezero_core::time::MonotonicClock; use serde_json::{Value, json}; @@ -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 861d054cb..522c9d8e9 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 crate::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 diff --git a/crates/edgezero-store-aws/src/lib.rs b/crates/edgezero-store-aws/src/lib.rs index c4df04a63..24c7e3e56 100644 --- a/crates/edgezero-store-aws/src/lib.rs +++ b/crates/edgezero-store-aws/src/lib.rs @@ -53,6 +53,12 @@ mod secrets_manager; #[cfg(test)] #[cfg(all(not(target_arch = "wasm32"), feature = "secrets-manager"))] mod snapshot_tests; +#[cfg(test)] +#[cfg(all( + not(target_arch = "wasm32"), + any(feature = "secrets-manager", feature = "dynamodb-kv") +))] +mod test_net; #[cfg(all( not(target_arch = "wasm32"), any( diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index d5fcd961e..6fe0b06bd 100644 --- a/crates/edgezero-store-aws/src/secrets_manager.rs +++ b/crates/edgezero-store-aws/src/secrets_manager.rs @@ -323,6 +323,7 @@ fn classify_sdk_error( mod tests { use super::{classify_operation_error, materialize_payload}; use crate::PreparationError; + use crate::test_net::accept_blocking; use aws_sdk_secretsmanager::error::{ConnectorError, SdkError}; use aws_sdk_secretsmanager::operation::get_secret_value::GetSecretValueOutput; use aws_sdk_secretsmanager::primitives::Blob; @@ -465,7 +466,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; diff --git a/crates/edgezero-store-aws/src/test_net.rs b/crates/edgezero-store-aws/src/test_net.rs new file mode 100644 index 000000000..2eb24b00c --- /dev/null +++ b/crates/edgezero-store-aws/src/test_net.rs @@ -0,0 +1,68 @@ +//! 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" + ); + } +} From 6ac23fb7e01c80cfcb66a10488a70c16bfec90e6 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 15:13:47 +0530 Subject: [PATCH 2/8] test: run source-bound proxy hosting tests only on Linux by default Four production_hosting tests drive the native proxy fixture, which binds its upstream socket to 127.0.0.2 or 127.0.0.3 so the server sees distinct peers. Linux routes all of 127.0.0.0/8 to lo; macOS lo0 has only 127.0.0.1, so the bind fails with EADDRNOTAVAIL, the relay drops the connection, and the tests see an empty response or TLS UnexpectedEof. Ignore them off Linux with a reason that gives the lo0 alias commands needed to run them with --ignored. --- .../tests/production_hosting.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index c74a86c0f..c0e2bd8c2 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -567,6 +567,10 @@ mod tests { } #[test] + #[cfg_attr( + not(target_os = "linux"), + ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" + )] fn native_source_bound_single_proxy_and_mapped_cidr_match_only_owned_peers() { for networks in [ "127.0.0.2/32", @@ -627,6 +631,10 @@ mod tests { } #[test] + #[cfg_attr( + not(target_os = "linux"), + ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" + )] fn native_two_proxy_chain_stops_at_untrusted_hop_and_gateway_replaces_prefix() { for (networks, boundary) in [ ("127.0.0.2/32,127.0.0.3/32", "127.0.0.1"), @@ -773,6 +781,10 @@ mod tests { } #[test] + #[cfg_attr( + not(target_os = "linux"), + ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" + )] fn native_selected_families_conflicts_malformed_sets_gaps_and_exhaustion() { for family in ["forwarded", "x-forwarded"] { let roots = Roots::new(); @@ -847,6 +859,10 @@ mod tests { } #[test] + #[cfg_attr( + not(target_os = "linux"), + ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" + )] fn native_verified_tls_ingress_overwrites_public_assertions_and_rejects_wrong_name() { let roots = Roots::new(); let addr = address(); From ce8421a947b67299bcb092c0736801f34227e042 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 19:03:36 +0530 Subject: [PATCH 3/8] test: make the Secrets Manager attempt-timeout proof deterministic The SDK's 100 ms attempt deadline runs from the start of the attempt. Under parallel load the child can be descheduled between the TCP connect and the request write, so the SDK correctly abandons the connection before sending anything. The fixture treated that as fatal ("SDK closed before request headers"), which failed the test about once in 20 full store-aws runs on macOS. The test now uses a fixture that accepts every attempt and never answers, recording whether the client closed each connection itself. The operation budget is 10 s, so only the attempt deadline can close a held connection within the 5 s bound. The test asserts that every attempt was closed that way, that the SDK made 1 to 3 attempts, and that any full request named the fixture ARN. Removing the attempt timeout from the provider makes the test fail. --- .../edgezero-store-aws/src/secrets_manager.rs | 146 +++++++++++++++--- 1 file changed, 123 insertions(+), 23 deletions(-) diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index 6fe0b06bd..4ac8358e2 100644 --- a/crates/edgezero-store-aws/src/secrets_manager.rs +++ b/crates/edgezero-store-aws/src/secrets_manager.rs @@ -332,13 +332,27 @@ mod tests { 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. + /// The timeout child's attempt deadline is 100 ms and its operation budget is 10 s, so only + /// the attempt deadline can close a held connection inside this bound. + 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); + /// One connection the SDK opened against `holding_fixture`. + struct HeldConnection { + /// The client closed the connection within `HOLD_BOUND`. + closed_by_client: bool, + /// Lowercased request head and body, when the complete request arrived first. + request: Option<(String, String)>, + } + struct LoopbackFixture { listener: TcpListener, worker: thread::JoinHandle>, @@ -359,7 +373,6 @@ mod tests { #[derive(Clone)] enum FixtureResponse { Decryption, - Delay(Duration), Denied, InternalError, Json(String), @@ -421,21 +434,9 @@ mod tests { body.contains(TEST_ARN), "request must contain only 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); - } 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::Json(payload) => (200_u16, "OK", payload), FixtureResponse::Missing => (400_u16, "Bad Request", r#"{"__type":"ResourceNotFoundException","message":"ARN_SENTINEL"}"#.to_owned()), @@ -450,6 +451,89 @@ 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(); + while !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 => { + 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}"), + } + }; + let request = received + .windows(4) + .position(|bytes| bytes == b"\r\n\r\n") + .and_then(|end| { + let head = String::from_utf8_lossy(&received[..end]).to_ascii_lowercase(); + let length = head + .lines() + .find_map(|line| line.strip_prefix("content-length:").map(str::trim)) + .and_then(|value| value.parse::().ok())?; + let body = received.get(end.checked_add(4)?..)?; + (body.len() >= length) + .then(|| (head, String::from_utf8_lossy(&body[..length]).into_owned())) + }); + HeldConnection { + closed_by_client, + request, + } + } + fn loopback_fixture(responses: Vec) -> (String, LoopbackFixture) { let listener = TcpListener::bind("127.0.0.1:0").expect("bind literal loopback only"); listener @@ -773,20 +857,34 @@ 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" + 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 attempt deadline, not the 10 s operation budget, ends every unanswered attempt" ); + for (head, body) in held + .iter() + .filter_map(|connection| connection.request.as_ref()) + { + assert!(head.contains("x-amz-target: secretsmanager.getsecretvalue")); + assert!( + body.contains(TEST_ARN), + "request must name only the fixture ARN" + ); + } } /// Invoked only by an env-cleared child process launched by the parent fixture. @@ -821,8 +919,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 { From 09b09d9ee51da6e9953d3c8722f1640036740738 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 19:12:36 +0530 Subject: [PATCH 4/8] test: keep hosting port reservations from leaking into fixture processes macOS marks a new socket close-on-exec only after socket() returns. When a parallel test spawned a fixture process in that gap, the child inherited another test's port reservation and kept it bound after the test released it. That test's fixture server then failed to bind (AddrInUse); lsof showed another fixture process holding the port as a CLOSED socket. Separately, a released reservation could be served by another test's server during a "nothing answers" check. Together these failed 6 of 20 macOS runs. Reservations and fixture spawns now hold one lock, so they never overlap. Tests that assert nothing answers keep their reservation bound, but not listening, until the check is done. --- .../tests/production_hosting.rs | 84 ++++++++++++------- 1 file changed, 55 insertions(+), 29 deletions(-) diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index c0e2bd8c2..1c50aaef9 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -20,13 +20,14 @@ mod tests { use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _, symlink}; use std::os::unix::process::ExitStatusExt as _; use std::process::{Child, Command, ExitStatus, Stdio}; - use std::sync::{Arc, Mutex, mpsc}; + use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; use edgezero_core::blob_envelope::BlobEnvelope; use serde_json::{Value, json}; use tempfile::TempDir; + use tokio::net::TcpSocket; const WAIT: Duration = Duration::from_secs(5); @@ -64,11 +65,34 @@ mod tests { .expect("envelope") } + /// macOS marks a new socket close-on-exec only after `socket()` returns, so a fixture + /// process spawned by a parallel test in that gap inherits it. An inherited reservation + /// stays bound in that process, and the fixture server that later binds the port fails + /// with `AddrInUse`. Reservations and spawns hold this lock so they never overlap. + static RESERVE_OR_SPAWN: Mutex<()> = Mutex::new(()); + + fn reserve_or_spawn() -> MutexGuard<'static, ()> { + RESERVE_OR_SPAWN + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + /// Reserves a loopback port for a fixture server that binds it itself. fn address() -> SocketAddr { - TcpListener::bind("127.0.0.1:0") - .expect("port reservation") - .local_addr() - .expect("address") + reserved_address().0 + } + + /// Reserves a loopback port and keeps it bound, but not listening, until the holder drops. + /// No parallel test can bind the port meanwhile and nothing accepts a connection to it, so + /// a "nothing answers" check cannot reach a server that reused a released reservation. + fn reserved_address() -> (SocketAddr, TcpSocket) { + let _reserving = reserve_or_spawn(); + let socket = TcpSocket::new_v4().expect("port reservation socket"); + socket + .bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))) + .expect("port reservation"); + let addr = socket.local_addr().expect("reserved address"); + (addr, socket) } fn command(mode: &str, roots: &Roots, addr: SocketAddr) -> Command { @@ -101,11 +125,13 @@ mod tests { impl Server { fn spawn(mut command: Command, addr: SocketAddr) -> Self { + let spawning = reserve_or_spawn(); let mut child = command .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("fixture process"); + drop(spawning); let output = Arc::new(Mutex::new(String::new())); let (sender, events) = mpsc::channel(); let stdout = child.stdout.take().expect("stdout"); @@ -173,14 +199,14 @@ mod tests { } fn signal(&self, name: &str) { - assert!( - Command::new("kill") - .arg(format!("-{name}")) - .arg(self.child.id().to_string()) - .status() - .expect("send signal") - .success() - ); + let spawning = reserve_or_spawn(); + let status = Command::new("kill") + .arg(format!("-{name}")) + .arg(self.child.id().to_string()) + .status() + .expect("send signal"); + drop(spawning); + assert!(status.success()); } fn socket(&self) -> io::Result { @@ -1660,7 +1686,7 @@ mod tests { (None, None, Some("RECORDS_SENTINEL"), "REQUEST_RECORDS"), (None, None, Some("FALSE"), "REQUEST_RECORDS"), ] { - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut launch = command("diagnostics", &roots, addr); if let Some(value) = networks { launch.env("EDGEZERO__ADAPTER__TRUSTED_PROXY_CIDRS", value); @@ -1701,7 +1727,7 @@ mod tests { ), ("EDGEZERO__LOGGING__REQUEST_RECORDS", "REQUEST_RECORDS"), ] { - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut launch = command("diagnostics", &roots, addr); let mut raw = b"NON_UNICODE_SENTINEL".to_vec(); raw.push(0xff); @@ -1844,7 +1870,7 @@ mod tests { OsString::from_vec(vec![0xff]), ] { let roots = Roots::new(); - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut launch = command(mode, &roots, addr); launch.env("EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES", value); let log = failed(launch, addr, "JSON_BODY_LIMIT_BYTES"); @@ -1948,7 +1974,7 @@ mod tests { #[test] fn stop_during_startup_never_binds_or_becomes_ready() { let roots = Roots::new(); - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut server = Server::spawn(command("starting", &roots, addr), addr); server.wait_line("INITIALIZING"); TcpStream::connect_timeout(&addr, Duration::from_millis(50)) @@ -1982,7 +2008,7 @@ mod tests { "settings", ), ] { - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut cmd = command("initialized", &roots, addr); cmd.env(key, value); failed(cmd, addr, category); @@ -1991,15 +2017,15 @@ mod tests { ("hook-error", "application configuration"), ("initializer-error", "initializer"), ] { - let addr = address(); + let (addr, _addr_held) = reserved_address(); failed(command(mode, &roots, addr), addr, category); } - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut cmd = command("initialized", &roots, addr); cmd.env_remove("EDGEZERO__ADAPTER__CONFIG_DIR"); failed(cmd, addr, "CONFIG_DIR"); let missing = roots.cwd.path().join("missing-data-SENTINEL"); - let missing_addr = address(); + let (missing_addr, _missing_addr_held) = reserved_address(); let mut missing_cmd = command("initialized", &roots, missing_addr); missing_cmd.env("EDGEZERO__ADAPTER__DATA_DIR", &missing); failed(missing_cmd, missing_addr, "DATA_DIR"); @@ -2022,10 +2048,10 @@ mod tests { let roots = Roots::new(); let file = roots.config.path().join("local-config-settings.json"); fs::remove_file(&file).expect("missing file fixture"); - let addr = address(); + let (addr, _addr_held) = reserved_address(); failed(command("initialized", &roots, addr), addr, "missing"); fs::create_dir_all(&file).expect("non-regular fixture"); - let directory_addr = address(); + let (directory_addr, _directory_addr_held) = reserved_address(); failed( command("initialized", &roots, directory_addr), directory_addr, @@ -2033,7 +2059,7 @@ mod tests { ); fs::remove_dir(&file).expect("remove fixture directory"); roots.map(&json!({"settings": {"CONFIG_SENTINEL": true}})); - let malformed_addr = address(); + let (malformed_addr, _malformed_addr_held) = reserved_address(); failed( command("initialized", &roots, malformed_addr), malformed_addr, @@ -2052,7 +2078,7 @@ mod tests { ), ] { roots.map(&map); - let typed_addr = address(); + let (typed_addr, _typed_addr_held) = reserved_address(); failed( command("initialized", &roots, typed_addr), typed_addr, @@ -2063,7 +2089,7 @@ mod tests { serde_json::from_str(&blob("valid-greeting", "fixture_token")).expect("envelope"); envelope["data"]["greeting"] = json!("CHANGED_CONFIG_SENTINEL"); roots.map(&json!({"settings": serde_json::to_string(&envelope).expect("envelope")})); - let integrity_addr = address(); + let (integrity_addr, _integrity_addr_held) = reserved_address(); failed( command("initialized", &roots, integrity_addr), integrity_addr, @@ -2137,7 +2163,7 @@ mod tests { .expect("snapshot") .ends_with("selected-greeting") ); - let second_addr = address(); + let (second_addr, _second_addr_held) = reserved_address(); failed( command("initialized", &roots, second_addr), second_addr, @@ -2289,7 +2315,7 @@ mod tests { #[cfg(not(feature = "geo-cloudfront"))] fn geo_hosting_rejects_unavailable_cloudfront() { let cwd = tempfile::tempdir().expect("unrelated cwd"); - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut server = Server::spawn(geo_command("geo-cloudfront", &cwd, addr), addr); assert!(!server.wait().success()); let log = server.log(); @@ -2365,7 +2391,7 @@ mod tests { #[test] fn geo_hosting_invalid_policy_never_initializes_or_listens() { let cwd = tempfile::tempdir().expect("unrelated cwd"); - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut server = Server::spawn(geo_command("geo-invalid-policy", &cwd, addr), addr); assert!(!server.wait().success()); assert!(!server.log().contains("INITIALIZED")); From d86a5d326c92607c33d627533368c47c1a6c8184 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 19:28:17 +0530 Subject: [PATCH 5/8] test: close remaining gaps in the macOS hosting and timeout fixtures production_hosting: client streams from Server::socket and raw_request also take the reservation/spawn lock, so a concurrently spawned fixture cannot inherit one and keep the connection open after the test drops it. Because a held reservation always refuses connections, "nothing answers" checks now also assert that the server never reached its listener bind. Secrets Manager: the holding fixture drains every queued connection after the child exits before counting attempts, so a starved fixture thread cannot undercount them. --- .../tests/production_hosting.rs | 29 ++++++++++++++++--- .../edgezero-store-aws/src/secrets_manager.rs | 8 ++++- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index 1c50aaef9..2bf70337f 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -67,8 +67,9 @@ mod tests { /// macOS marks a new socket close-on-exec only after `socket()` returns, so a fixture /// process spawned by a parallel test in that gap inherits it. An inherited reservation - /// stays bound in that process, and the fixture server that later binds the port fails - /// with `AddrInUse`. Reservations and spawns hold this lock so they never overlap. + /// stays bound in that process, so the fixture server that later binds the port fails with + /// `AddrInUse`, and an inherited client stream stays open after the test drops it. Port + /// reservations, client streams and spawns hold this lock so they never overlap. static RESERVE_OR_SPAWN: Mutex<()> = Mutex::new(()); fn reserve_or_spawn() -> MutexGuard<'static, ()> { @@ -77,6 +78,12 @@ mod tests { .unwrap_or_else(PoisonError::into_inner) } + /// Opens a client stream without letting a concurrently spawned fixture inherit it. + fn connect(addr: SocketAddr, timeout: Duration) -> io::Result { + let _connecting = reserve_or_spawn(); + TcpStream::connect_timeout(&addr, timeout) + } + /// Reserves a loopback port for a fixture server that binds it itself. fn address() -> SocketAddr { reserved_address().0 @@ -85,6 +92,8 @@ mod tests { /// Reserves a loopback port and keeps it bound, but not listening, until the holder drops. /// No parallel test can bind the port meanwhile and nothing accepts a connection to it, so /// a "nothing answers" check cannot reach a server that reused a released reservation. + /// While held, the check cannot fail by itself: callers also assert that the server never + /// reached its listener bind. fn reserved_address() -> (SocketAddr, TcpSocket) { let _reserving = reserve_or_spawn(); let socket = TcpSocket::new_v4().expect("port reservation socket"); @@ -210,7 +219,7 @@ mod tests { } fn socket(&self) -> io::Result { - let socket = TcpStream::connect_timeout(&self.addr, Duration::from_millis(50))?; + let socket = connect(self.addr, Duration::from_millis(50))?; socket.set_read_timeout(Some(WAIT))?; socket.set_write_timeout(Some(WAIT))?; Ok(socket) @@ -272,6 +281,10 @@ mod tests { "startup diagnostic leaked fixture contents: {log}" ); assert!(!log.contains("INITIALIZED")); + assert!( + !log.contains("startup bind"), + "failed startup reached bind: {log}" + ); TcpStream::connect_timeout(&addr, Duration::from_millis(50)) .expect_err("failed startup never accepts connections"); log @@ -403,7 +416,7 @@ mod tests { } fn raw_request(addr: SocketAddr, request: &str) -> String { - let mut socket = TcpStream::connect_timeout(&addr, WAIT).expect("wire connection"); + let mut socket = connect(addr, WAIT).expect("wire connection"); socket.set_read_timeout(Some(WAIT)).expect("read timeout"); socket.set_write_timeout(Some(WAIT)).expect("write timeout"); socket.write_all(request.as_bytes()).expect("wire request"); @@ -2323,6 +2336,10 @@ mod tests { assert!(!log.contains("INITIALIZED")); assert!(!log.contains("HOOK_ENTERED")); assert!(!log.contains("ready")); + assert!( + !log.contains("startup bind"), + "unavailable implementation reached bind" + ); TcpStream::connect_timeout(&addr, Duration::from_millis(50)) .expect_err("unavailable implementation never binds"); assert_eq!(fs::read_dir(cwd.path()).expect("unrelated cwd").count(), 0); @@ -2397,6 +2414,10 @@ mod tests { assert!(!server.log().contains("INITIALIZED")); assert!(!server.log().contains("HOOK_ENTERED")); assert!(!server.log().contains("x-origin-verify-fixture")); + assert!( + !server.log().contains("startup bind"), + "invalid policy reached bind" + ); TcpStream::connect_timeout(&addr, Duration::from_millis(50)) .expect_err("invalid policy never binds"); assert_eq!(fs::read_dir(cwd.path()).expect("unrelated cwd").count(), 0); diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index 4ac8358e2..d1adbefca 100644 --- a/crates/edgezero-store-aws/src/secrets_manager.rs +++ b/crates/edgezero-store-aws/src/secrets_manager.rs @@ -475,13 +475,19 @@ mod tests { .checked_add(Duration::from_secs(30)) .expect("fixture deadline fits the monotonic clock"); let mut held = Vec::new(); - while !worker_stop.load(Ordering::Acquire) { + 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)); } From e8cf40eb59221b77c3bb3a9984ed9d54ff0daedf Mon Sep 17 00:00:00 2001 From: Aram Grigoryan <132480+aram356@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:39:23 -0800 Subject: [PATCH 6/8] test: run the trusted-proxy hosting tests on every platform Four production_hosting tests bound the proxy fixture's upstream socket to 127.0.0.2 or 127.0.0.3 so the server saw distinct peers. macOS lo0 has only 127.0.0.1, so 6ac23fb7 ignored them off Linux. The server checks one socket fact, its direct peer. Every earlier hop reaches it only as Forwarded or X-Forwarded-For text. So every proxy socket now uses 127.0.0.1 and the trusted ranges name 127.0.0.1, including its mapped /128 and /127 forms. An appending proxy now writes the predecessor it is given, from 192.0.2.0/24, instead of its real client address. That address would also be 127.0.0.1, so the walk would skip it as trusted and accept the visitor's forged earlier hop. The single-proxy test's non-owning range becomes 127.0.0.0/32, the peer's sibling in the 127.0.0.0/31 that the mapped /127 truncates to, as 127.0.0.3/32 was for 127.0.0.2. The two-proxy chain keeps three distinct hops (198.51.100.99, 192.0.2.1, 192.0.2.2) behind the real 127.0.0.1 ingress peer. The exhaustion row's only hop becomes the trusted 127.0.0.1. Each test fails under one temporary production mutation: widening every trusted network by one prefix bit, walking past the first untrusted hop, resolving an all-trusted chain to its leftmost hop, and keeping an earlier Forwarded element's proto. The four tests passed 10 of 10 runs on macOS, alone and in the full suite. --- .../tests/fixtures/native_proxy.rs | 67 +++++++------ .../tests/production_hosting.rs | 93 +++++++++---------- 2 files changed, 79 insertions(+), 81 deletions(-) diff --git a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs index 35953db96..492810218 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" @@ -15,7 +20,7 @@ use rustls::{ClientConfig, RootCertStore, ServerConfig}; use tokio::io::{ AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _, copy_bidirectional_with_sizes, }; -use tokio::net::{TcpListener, TcpSocket, TcpStream}; +use tokio::net::{TcpListener, TcpStream}; use tokio::runtime::Builder; use tokio::sync::oneshot; use tokio::task::JoinSet; @@ -30,10 +35,12 @@ pub(crate) enum Assertions { /// Keep deliberate malformed/gap inputs unchanged while preserving a real owned peer. Preserve, AppendForwarded { + predecessor: IpAddr, host: &'static str, scheme: &'static str, }, AppendXForwarded { + predecessor: IpAddr, host: &'static str, scheme: &'static str, }, @@ -59,12 +66,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 = StdTcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("proxy listener"); let addr = std_listener.local_addr().expect("proxy address"); std_listener @@ -86,17 +88,17 @@ impl LocalProxy { () = async { let _closed = (&mut stopped).await; } => break, _finished = tasks.join_next(), if !tasks.is_empty() => {}, accepted = listener.accept(), if tasks.len() < 64 => { - let (socket, peer) = accepted.expect("proxy accept"); + let (socket, _peer) = accepted.expect("proxy accept"); let task_acceptor = tls_acceptor.clone(); tasks.spawn(async move { let operation = async { if let Some(acceptor) = task_acceptor { if let Ok(mut client) = acceptor.accept(socket).await { - let _relayed = relay(&mut client, peer, upstream, source, assertions).await; + let _relayed = relay(&mut client, upstream, assertions).await; } } else { let mut client = socket; - let _relayed = relay(&mut client, peer, upstream, source, assertions).await; + let _relayed = relay(&mut client, upstream, assertions).await; } }; let _bounded = timeout(Duration::from_secs(5), operation).await; @@ -165,7 +167,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() @@ -176,13 +185,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 { + predecessor, + host, + scheme, + } => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("forwarded")) @@ -190,7 +199,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() { @@ -200,7 +210,11 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result { + Assertions::AppendXForwarded { + predecessor, + host, + scheme, + } => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("x-forwarded-for")) @@ -208,7 +222,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() { @@ -231,10 +245,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}"), @@ -255,19 +266,15 @@ 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 socket = TcpSocket::new_v4()?; - socket.bind(SocketAddr::new(IpAddr::V4(source), 0))?; - let mut origin = socket.connect(upstream).await?; + let rewritten = rewrite(&head, assertions)?; + let mut origin = TcpStream::connect(upstream).await?; origin.write_all(rewritten.as_bytes()).await?; origin.write_all(&body_prefix).await?; // Finite, per-direction relay buffers. Never collect a response or body for proxying. diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index 2bf70337f..d4ce3823b 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -31,6 +31,10 @@ mod tests { const WAIT: Duration = Duration::from_secs(5); + /// 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, @@ -606,16 +610,14 @@ mod tests { } #[test] - #[cfg_attr( - not(target_os = "linux"), - ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" - )] fn native_source_bound_single_proxy_and_mapped_cidr_match_only_owned_peers() { + // 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(); @@ -626,8 +628,8 @@ mod tests { server.ready(); let proxy = LocalProxy::start( addr, - Ipv4Addr::new(127, 0, 0, 2), Assertions::AppendForwarded { + predecessor: VISITOR, host: "public.example", scheme: "https", }, @@ -640,10 +642,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, - if trusted { "127.0.0.1" } else { "127.0.0.2" }, + if trusted { "192.0.2.1" } else { "127.0.0.1" }, if trusted { "public.example" } else { @@ -661,7 +663,7 @@ mod tests { .expect("proxy peer") .parse() .expect("peer address"); - assert_eq!(peer.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))); + assert_eq!(peer.ip(), IpAddr::V4(Ipv4Addr::LOCALHOST)); assert_no_diagnostic_headers(&response); server.signal("TERM"); assert!(server.wait().success()); @@ -670,14 +672,14 @@ mod tests { } #[test] - #[cfg_attr( - not(target_os = "linux"), - ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" - )] fn native_two_proxy_chain_stops_at_untrusted_hop_and_gateway_replaces_prefix() { + // 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(); @@ -688,8 +690,8 @@ mod tests { server.ready(); let ingress = LocalProxy::start( addr, - Ipv4Addr::new(127, 0, 0, 3), Assertions::AppendForwarded { + predecessor: first_proxy, host: "final.example", scheme: "https", }, @@ -697,8 +699,8 @@ mod tests { ); let first = LocalProxy::start( ingress.addr(), - Ipv4Addr::new(127, 0, 0, 2), Assertions::AppendForwarded { + predecessor: VISITOR, host: "earlier.example", scheme: "http", }, @@ -716,7 +718,7 @@ mod tests { value["handler"]["peer"] .as_str() .expect("last proxy peer") - .starts_with("127.0.0.3:") + .starts_with("127.0.0.1:") ); server.signal("TERM"); assert!(server.wait().success()); @@ -725,13 +727,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( addr, - Ipv4Addr::new(127, 0, 0, 3), Assertions::ReplaceForwarded { client: "203.0.113.7".parse().expect("verified gateway client"), host: "gateway.example", @@ -758,13 +759,8 @@ 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, - Ipv4Addr::new(127, 0, 0, 2), - Assertions::Preserve, - false, - ); + // This trusted relay preserves deliberate bad inputs rather than sanitizing them. + let gateway = LocalProxy::start(addr, Assertions::Preserve, false); let absent = if family == "forwarded" { "Forwarded: host=partial.example;proto=https\r\nX-Forwarded-For: 198.51.100.9\r\n" } else { @@ -773,7 +769,7 @@ mod tests { let missing_client = response_json(&raw_request(gateway.addr(), &metadata_request(absent))); assert_metadata( &missing_client, - "127.0.0.2", + "127.0.0.1", "partial.example", "https", if family == "forwarded" { @@ -788,16 +784,17 @@ mod tests { } 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, - "127.0.0.2", + "127.0.0.1", "gap.example", "https", "unresolved_chain", @@ -812,7 +809,7 @@ mod tests { response_json(&raw_request(gateway.addr(), &metadata_request(duplicate))); assert_metadata( &malformed_duplicate, - "127.0.0.2", + "127.0.0.1", "direct.example:8080", "http", "malformed", @@ -820,36 +817,34 @@ mod tests { } #[test] - #[cfg_attr( - not(target_os = "linux"), - ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" - )] fn native_selected_families_conflicts_malformed_sets_gaps_and_exhaustion() { 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 assertions = if family == "forwarded" { Assertions::AppendForwarded { + predecessor: VISITOR, host: "selected.example", scheme: "https", } } else { Assertions::AppendXForwarded { + predecessor: VISITOR, host: "selected.example", scheme: "https", } }; - let proxy = LocalProxy::start(addr, Ipv4Addr::new(127, 0, 0, 2), assertions, false); + let proxy = LocalProxy::start(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", - "127.0.0.1", + "192.0.2.1", "selected.example", "https", ), @@ -860,7 +855,7 @@ mod tests { "X-Forwarded-For: bad-address\r\n" }, "malformed", - "127.0.0.2", + "127.0.0.1", "direct.example:8080", "http", ), @@ -871,7 +866,7 @@ mod tests { "X-Forwarded-For: unknown\r\n" }, "accepted", - "127.0.0.1", + "192.0.2.1", "selected.example", "https", ), @@ -898,22 +893,18 @@ mod tests { } #[test] - #[cfg_attr( - not(target_os = "linux"), - ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" - )] fn native_verified_tls_ingress_overwrites_public_assertions_and_rejects_wrong_name() { 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( addr, - Ipv4Addr::new(127, 0, 0, 2), Assertions::AppendForwarded { + predecessor: VISITOR, host: "native-proxy.test", scheme: "https", }, @@ -927,7 +918,7 @@ mod tests { let value = response_json(&response); assert_metadata( &value, - "127.0.0.1", + "192.0.2.1", "native-proxy.test", "https", "accepted", From 58a238f8495afe1a8b35338bd9ee4d84dc7fe7fd Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Wed, 2 Dec 2026 23:13:36 +0530 Subject: [PATCH 7/8] Share native test fixtures and strengthen timeout evidence --- .../tests/fixtures/blocking_accept.rs | 68 ------ .../tests/fixtures/native_proxy.rs | 39 ++-- .../tests/native_aws_startup.rs | 6 +- .../tests/native_celld_startup.rs | 6 +- .../tests/production_hosting.rs | 66 ++---- .../tests/celld_generated_proof.rs | 7 +- .../tests/dynamodb_generated_proof.rs | 7 +- .../tests/native_store_generated_proof.rs | 7 +- .../tests/support/blocking_accept.rs | 68 ------ crates/edgezero-core/src/lib.rs | 3 + .../src/test_net.rs | 6 +- .../src/dynamodb_records_tests.rs | 2 +- .../edgezero-store-aws/src/dynamodb_tests.rs | 2 +- crates/edgezero-store-aws/src/lib.rs | 6 - .../edgezero-store-aws/src/secrets_manager.rs | 219 +++++++++++++----- 15 files changed, 221 insertions(+), 291 deletions(-) delete mode 100644 crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs delete mode 100644 crates/edgezero-cli/tests/support/blocking_accept.rs rename crates/{edgezero-store-aws => edgezero-core}/src/test_net.rs (93%) diff --git a/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs b/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs deleted file mode 100644 index 2eb24b00c..000000000 --- a/crates/edgezero-adapter-axum/tests/fixtures/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-adapter-axum/tests/fixtures/native_proxy.rs b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs index a33126423..0a04442ee 100644 --- a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs +++ b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs @@ -32,20 +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 { - predecessor: IpAddr, - host: &'static str, - scheme: &'static str, - }, - AppendXForwarded { - predecessor: IpAddr, - host: &'static str, - scheme: &'static str, - }, + AppendForwarded(Hop), + AppendXForwarded(Hop), ReplaceForwarded { client: IpAddr, host: &'static str, @@ -225,11 +236,11 @@ fn rewrite(head: &str, assertions: Assertions) -> io::Result { } match assertions { Assertions::Preserve => {} - Assertions::AppendForwarded { + Assertions::AppendForwarded(Hop { predecessor, host, scheme, - } => { + }) => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("forwarded")) @@ -248,11 +259,11 @@ fn rewrite(head: &str, assertions: Assertions) -> io::Result { }, )); } - Assertions::AppendXForwarded { + Assertions::AppendXForwarded(Hop { predecessor, host, scheme, - } => { + }) => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("x-forwarded-for")) 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 78f132064..96cfd2849 100644 --- a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs @@ -8,13 +8,9 @@ reason = "fixture helpers precede startup scenarios" )] -#[cfg(test)] -#[path = "fixtures/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] mod tests { - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::fs; use std::io::{ErrorKind, Read, Write as _}; use std::net::{SocketAddr, TcpListener, TcpStream}; diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index 33f3888de..5c15d05d0 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; @@ -580,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) { @@ -712,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) @@ -740,7 +745,7 @@ mod tests { } #[test] - fn native_source_bound_single_proxy_and_mapped_cidr_match_only_owned_peers() { + 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 [ @@ -758,11 +763,7 @@ mod tests { server.ready(); let proxy = LocalProxy::start( server.addr(), - Assertions::AppendForwarded { - predecessor: VISITOR, - host: "public.example", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "public.example", "https")), false, ); let response = raw_request( @@ -788,7 +789,7 @@ mod tests { "untrusted_peer" }, ); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); assert_no_diagnostic_headers(&response); server.signal("TERM"); assert!(server.wait().success()); @@ -815,20 +816,12 @@ mod tests { server.ready(); let ingress = LocalProxy::start( server.addr(), - Assertions::AppendForwarded { - predecessor: first_proxy, - host: "final.example", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(first_proxy, "final.example", "https")), false, ); let first = LocalProxy::start( ingress.addr(), - Assertions::AppendForwarded { - predecessor: VISITOR, - host: "earlier.example", - scheme: "http", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "earlier.example", "http")), false, ); let value = response_json(&raw_request( @@ -839,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, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); server.signal("TERM"); assert!(server.wait().success()); assert_final_zero(&server); @@ -889,7 +882,7 @@ mod tests { "http", "absent", ); - assert_peer_ip(&absent, Ipv4Addr::LOCALHOST); + assert_peer_ip(&absent, Ipv4Addr::LOCALHOST, addr); assert_eq!(absent["handler"]["client_source"], "direct"); let without_address = if family == "forwarded" { @@ -916,7 +909,7 @@ mod tests { "partial" }, ); - assert_peer_ip(&missing_client, Ipv4Addr::LOCALHOST); + assert_peer_ip(&missing_client, Ipv4Addr::LOCALHOST, addr); for headers in [ if family == "forwarded" { "Forwarded: for=unknown;host=gap.example;proto=https\r\n" @@ -932,7 +925,7 @@ mod tests { ] { let value = response_json(&raw_request(gateway.addr(), &metadata_request(headers))); assert_metadata(&value, None, "gap.example", "https", "unresolved_chain"); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, addr); let source = if family == "forwarded" { "trusted_forwarded" } else { @@ -955,7 +948,7 @@ mod tests { "http", "malformed", ); - assert_peer_ip(&malformed_duplicate, Ipv4Addr::LOCALHOST); + assert_peer_ip(&malformed_duplicate, Ipv4Addr::LOCALHOST, addr); } #[test] @@ -968,18 +961,11 @@ mod tests { addr, ); server.ready(); + let hop = Hop::new(VISITOR, "selected.example", "https"); let assertions = if family == "forwarded" { - Assertions::AppendForwarded { - predecessor: VISITOR, - host: "selected.example", - scheme: "https", - } + Assertions::AppendForwarded(hop) } else { - Assertions::AppendXForwarded { - predecessor: VISITOR, - host: "selected.example", - scheme: "https", - } + Assertions::AppendXForwarded(hop) }; let proxy = LocalProxy::start(server.addr(), assertions, false); for (prefix, expected_result, client, host, scheme) in [ @@ -1015,7 +1001,7 @@ mod tests { ] { let value = response_json(&raw_request(proxy.addr(), &metadata_request(prefix))); assert_metadata(&value, client, host, scheme, expected_result); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); } assert_missing_unresolved_and_duplicate_family(server.addr(), family); server.signal("TERM"); @@ -1046,11 +1032,7 @@ mod tests { server.ready(); let proxy = LocalProxy::start( server.addr(), - Assertions::AppendForwarded { - predecessor: VISITOR, - host: "native-proxy.test", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "native-proxy.test", "https")), true, ); let request = metadata_request( @@ -1930,7 +1912,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 1a392a3b0..5d286a4ab 100644 --- a/crates/edgezero-cli/tests/celld_generated_proof.rs +++ b/crates/edgezero-cli/tests/celld_generated_proof.rs @@ -6,11 +6,6 @@ //! `CELLD_BIN`, Node.js and OpenSSL. The app trusts the fixture certificate //! through `SSL_CERT_FILE`. -#[cfg(test)] -#[cfg(unix)] -#[path = "support/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] #[cfg(unix)] mod tests { @@ -19,7 +14,7 @@ mod tests { reason = "keep fixture ownership, generated source and proof steps together" )] - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::collections::BTreeMap; use std::env; #[cfg(target_os = "linux")] diff --git a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs index 753e2a196..95bc8bee9 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-store-aws/src/test_net.rs b/crates/edgezero-core/src/test_net.rs similarity index 93% rename from crates/edgezero-store-aws/src/test_net.rs rename to crates/edgezero-core/src/test_net.rs index 2eb24b00c..e36c5b3aa 100644 --- a/crates/edgezero-store-aws/src/test_net.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 63616e527..5b743ba93 100644 --- a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs @@ -9,8 +9,8 @@ use super::*; use crate::dynamodb_kv::sdk_tests::{active_table, loopback_client, read_request}; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits}; -use crate::test_net::accept_blocking; 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}; diff --git a/crates/edgezero-store-aws/src/dynamodb_tests.rs b/crates/edgezero-store-aws/src/dynamodb_tests.rs index a6d032f0f..989cf9680 100644 --- a/crates/edgezero-store-aws/src/dynamodb_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_tests.rs @@ -12,7 +12,7 @@ use super::*; use crate::preparation::AwsPreparation; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits, DynamoDbKvSettings}; -use crate::test_net::accept_blocking; +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 _}; diff --git a/crates/edgezero-store-aws/src/lib.rs b/crates/edgezero-store-aws/src/lib.rs index 24c7e3e56..c4df04a63 100644 --- a/crates/edgezero-store-aws/src/lib.rs +++ b/crates/edgezero-store-aws/src/lib.rs @@ -53,12 +53,6 @@ mod secrets_manager; #[cfg(test)] #[cfg(all(not(target_arch = "wasm32"), feature = "secrets-manager"))] mod snapshot_tests; -#[cfg(test)] -#[cfg(all( - not(target_arch = "wasm32"), - any(feature = "secrets-manager", feature = "dynamodb-kv") -))] -mod test_net; #[cfg(all( not(target_arch = "wasm32"), any( diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index 53ecede1d..72d457254 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()) { @@ -303,11 +311,11 @@ fn classify_sdk_error( mod tests { use super::{classify_operation_error, materialize_payload}; use crate::PreparationError; - use crate::test_net::accept_blocking; use aws_sdk_secretsmanager::error::{ConnectorError, SdkError}; 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}; @@ -318,19 +326,41 @@ mod tests { use std::time::{Duration, Instant}; /// How long the holding fixture waits for the client to abandon an unanswered attempt. - /// The timeout child's attempt deadline is 100 ms and its operation budget is 10 s, so only - /// the attempt deadline can close a held connection inside this bound. + /// 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, - /// Lowercased request head and body, when the complete request arrived first. - request: Option<(String, String)>, } struct LoopbackFixture { @@ -362,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"); @@ -378,43 +446,81 @@ 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" ); + 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()), @@ -503,23 +609,10 @@ mod tests { Err(error) => panic!("held connection read failed: {error}"), } }; - let request = received - .windows(4) - .position(|bytes| bytes == b"\r\n\r\n") - .and_then(|end| { - let head = String::from_utf8_lossy(&received[..end]).to_ascii_lowercase(); - let length = head - .lines() - .find_map(|line| line.strip_prefix("content-length:").map(str::trim)) - .and_then(|value| value.parse::().ok())?; - let body = received.get(end.checked_add(4)?..)?; - (body.len() >= length) - .then(|| (head, String::from_utf8_lossy(&body[..length]).into_owned())) - }); - HeldConnection { - closed_by_client, - request, - } + // 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) { @@ -860,6 +953,15 @@ mod tests { "timeout child failed: {}", String::from_utf8_lossy(&child.stderr) ); + 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", @@ -867,18 +969,8 @@ mod tests { ); assert!( held.iter().all(|connection| connection.closed_by_client), - "the attempt deadline, not the 10 s operation budget, ends every unanswered attempt" + "the SDK must abandon every unanswered fixture connection" ); - for (head, body) in held - .iter() - .filter_map(|connection| connection.request.as_ref()) - { - assert!(head.contains("x-amz-target: secretsmanager.getsecretvalue")); - assert!( - body.contains(TEST_ARN), - "request must name only the fixture ARN" - ); - } } /// Invoked only by an env-cleared child process launched by the parent fixture. @@ -928,6 +1020,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"); From f75296d8ac14c112db6c7c2f325cabb60915167e Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Thu, 3 Dec 2026 07:27:21 +0530 Subject: [PATCH 8/8] Refresh offline dependency closure and isolate cancellation fixtures --- Cargo.lock | 4 +-- .../fixtures/request-fidelity/Cargo.lock | 4 +-- .../fixtures/reusable-app/Cargo.lock | 4 +-- crates/edgezero-test-harness/src/main.rs | 23 ++++++++++-- crates/edgezero-test-harness/src/startup.rs | 35 +++++++++++++++++++ examples/app-demo/Cargo.lock | 4 +-- 6 files changed, 63 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5de661a8c..3e53b0222 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2521,9 +2521,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pin-utils" diff --git a/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock b/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock index 61cd28627..d7ffca03b 100644 --- a/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock +++ b/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock @@ -1046,9 +1046,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "potential_utf" diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock index b9a601443..569120f67 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock +++ b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock @@ -1609,9 +1609,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "potential_utf" diff --git a/crates/edgezero-test-harness/src/main.rs b/crates/edgezero-test-harness/src/main.rs index 350366483..48f0ad3aa 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,16 +1885,24 @@ 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 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); let mut controller = @@ -1948,6 +1962,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"); diff --git a/examples/app-demo/Cargo.lock b/examples/app-demo/Cargo.lock index 8ed6a707e..d5e9e7f75 100644 --- a/examples/app-demo/Cargo.lock +++ b/examples/app-demo/Cargo.lock @@ -2486,9 +2486,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pin-utils"