From 410a16238b7cb740275ad69b9af628cd52c57bdc Mon Sep 17 00:00:00 2001 From: Christian Date: Wed, 11 Nov 2026 19:52:01 -0600 Subject: [PATCH 1/8] Capture authenticated head facts before transport sanitation --- crates/edgezero-core/src/app.rs | 12 ++- crates/edgezero-core/src/router.rs | 36 ++++++++- .../tests/received_head_preparation.rs | 80 +++++++++++++++++++ 3 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 crates/edgezero-core/tests/received_head_preparation.rs diff --git a/crates/edgezero-core/src/app.rs b/crates/edgezero-core/src/app.rs index 606218d35..e42a62e45 100644 --- a/crates/edgezero-core/src/app.rs +++ b/crates/edgezero-core/src/app.rs @@ -7,7 +7,7 @@ use crate::error::{ suppress_overflow_retry_after, }; use crate::http::header::CONTENT_TYPE; -use crate::http::{HeaderMap, HeaderValue, Method, Request, Response, StatusCode}; +use crate::http::{Extensions, HeaderMap, HeaderValue, Method, Request, Response, StatusCode}; use crate::ingress::{ AdmissionDecision, IngressAdmissionOutcome, IngressAdmissionPolicy, IngressBeginOutcome, IngressDispatchOutcome, IngressFraming, IngressHead, IngressHeadAccounting, IngressHeadLimits, @@ -409,6 +409,16 @@ impl App { self.platform } + /// Captures application-authenticated facts before a managed host sanitizes the head. + /// + /// The host must structurally validate the received head first. The router's + /// [`crate::router::RouterBuilder::received_head_preparer`] can retain facts but cannot mutate + /// headers, poll a body, choose a route or return a response at this stage. + #[inline] + pub fn prepare_received_head(&self, headers: &HeaderMap, extensions: &mut Extensions) { + self.router.prepare_received_head(headers, extensions); + } + fn render_error_response(&self, error: EdgeError) -> Response { let status = error.status(); let overflow_origin = error.request_body_overflow_origin(); diff --git a/crates/edgezero-core/src/router.rs b/crates/edgezero-core/src/router.rs index 518f8d153..a33f99f05 100644 --- a/crates/edgezero-core/src/router.rs +++ b/crates/edgezero-core/src/router.rs @@ -10,7 +10,7 @@ use tower_service::Service; use crate::context::FallbackDrainOutcome; use crate::error::EdgeError; use crate::handler::{BoxHandler, IntoHandler, IntrospectionNeeds}; -use crate::http::{Extensions, HandlerFuture, Method, Request, Response}; +use crate::http::{Extensions, HandlerFuture, HeaderMap, Method, Request, Response}; use crate::ingress::{AdmittedIngress, IngressHeadLimits, validate_normalized_ingress_parts}; use crate::introspection::{ManifestJson, RouteTable}; use crate::middleware::{BoxMiddleware, Middleware, Next}; @@ -21,6 +21,8 @@ use crate::response::IntoResponse as _; /// Shared optional interception performed before router lookup and state injection. pub type BoxPreDispatchHook = Arc; +type ReceivedHeadPreparer = Arc; + /// Inspect or terminate an admitted request before handler dispatch and route middleware. /// /// Adapter admission may resolve route identity first. The hook cannot bypass admission, @@ -212,6 +214,7 @@ pub struct RouterBuilder { manifest_json: Option>, middlewares: Vec, pre_dispatch_hook: Option, + received_head_preparer: Option, route_info: Vec, routes: HashMap>, /// App state registered via [`RouterBuilder::with_state`], keyed by type. @@ -265,6 +268,7 @@ impl RouterBuilder { self.manifest_json, self.state_extensions, self.pre_dispatch_hook, + self.received_head_preparer, ) } @@ -358,6 +362,22 @@ impl RouterBuilder { self.route(path, Method::PUT, handler) } + /// Sets a body-blind preparation callback for structurally validated received heads. + /// + /// Managed hosts call it before stripping forwarding fields or provider credentials. + /// Retain only application-authenticated facts in extensions, never credentials or an + /// unchecked header copy. It cannot change headers, route, read a body or return a response. + /// Router clones share the callback. Setting it again replaces the previous callback. + #[must_use] + #[inline] + pub fn received_head_preparer(mut self, prepare: F) -> Self + where + F: Fn(&HeaderMap, &mut Extensions) + Send + Sync + 'static, + { + self.received_head_preparer = Some(Arc::new(prepare)); + self + } + #[must_use] #[inline] pub fn route(mut self, path: &str, method: Method, handler: H) -> Self @@ -420,6 +440,7 @@ struct RouterInner { manifest_json: Option>, middlewares: Vec, pre_dispatch_hook: Option, + received_head_preparer: Option, route_index: Arc<[RouteInfo]>, routes: HashMap>, state_extensions: Extensions, @@ -642,12 +663,14 @@ impl RouterService { manifest_json: Option>, state_extensions: Extensions, pre_dispatch_hook: Option, + received_head_preparer: Option, ) -> Self { Self { inner: Arc::new(RouterInner { manifest_json, middlewares, pre_dispatch_hook, + received_head_preparer, route_index, routes, state_extensions, @@ -667,6 +690,17 @@ impl RouterService { } } + /// Captures application-authenticated facts from a structurally validated head. + /// + /// Managed hosts call this before stripping forwarding fields or provider credentials. + /// Preparation cannot change headers, poll a body, bypass admission or produce a response. + #[inline] + pub fn prepare_received_head(&self, headers: &HeaderMap, extensions: &mut Extensions) { + if let Some(prepare) = &self.inner.received_head_preparer { + prepare(headers, extensions); + } + } + /// Resolves a route without invoking middleware, handlers, or request-body code. #[must_use] #[inline] diff --git a/crates/edgezero-core/tests/received_head_preparation.rs b/crates/edgezero-core/tests/received_head_preparation.rs new file mode 100644 index 000000000..e69e6a6c3 --- /dev/null +++ b/crates/edgezero-core/tests/received_head_preparation.rs @@ -0,0 +1,80 @@ +#[cfg(test)] +mod tests { + use edgezero_core::app::App; + use edgezero_core::http::{Extensions, HeaderMap, HeaderValue}; + use edgezero_core::router::RouterService; + + #[derive(Clone, Debug, Eq, PartialEq)] + struct AuthenticatedAuthority(String); + + #[test] + fn absent_preparation_callback_leaves_extensions_unchanged() { + let app = App::new(RouterService::builder().build()); + let mut extensions = Extensions::new(); + extensions.insert(AuthenticatedAuthority("retained.example.com".to_owned())); + + app.prepare_received_head(&HeaderMap::new(), &mut extensions); + + assert_eq!( + extensions.get::(), + Some(&AuthenticatedAuthority("retained.example.com".to_owned())), + "the default should preserve existing extensions" + ); + } + + #[test] + fn received_head_preparation_retains_only_authenticated_fact_without_mutating_headers() { + let app = App::new( + RouterService::builder() + .received_head_preparer(|headers, extensions| { + if headers.get("x-fixture-auth") + == Some(&HeaderValue::from_static("fictional-secret")) + && let Some(authority) = headers + .get("x-forwarded-host") + .and_then(|value| value.to_str().ok()) + { + extensions.insert(AuthenticatedAuthority(authority.to_owned())); + } + }) + .build(), + ); + let mut headers = HeaderMap::new(); + headers.insert( + "x-fixture-auth", + HeaderValue::from_static("fictional-secret"), + ); + headers.insert( + "x-forwarded-host", + HeaderValue::from_static("publisher.example.com:8443"), + ); + let original = headers.clone(); + let mut extensions = Extensions::new(); + + app.prepare_received_head(&headers, &mut extensions); + + assert_eq!( + headers, original, + "preparation should not mutate received headers" + ); + assert_eq!( + extensions.get::(), + Some(&AuthenticatedAuthority( + "publisher.example.com:8443".to_owned() + )), + "preparation should retain the authenticated public authority" + ); + assert_eq!( + extensions.len(), + 1, + "preparation should retain only the public fact" + ); + + headers.remove("x-fixture-auth"); + let mut rejected = Extensions::new(); + app.prepare_received_head(&headers, &mut rejected); + assert!( + rejected.is_empty(), + "missing authentication should retain no fact" + ); + } +} From b97efec185abbaa901e633a980975c98ef2f6c3b Mon Sep 17 00:00:00 2001 From: Aram Grigoryan <132480+aram356@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:51:39 -0800 Subject: [PATCH 2/8] fix: close outbound review validation gaps Restore isolated CLI activation, supervised progress tooling, raw qualification telemetry and stable evidence identities. Correct empty Spin request framing, nonce fixtures and documentation while preserving outbound limits, deadlines and ownership contracts. Validation: all five primary Rust gates, 2702 workspace tests, 660 harness tests, 38 tooling tests, isolated CLI compilation and the outbound documentation contract. Full four-adapter/demo and hosted qualification gates remain open. --- .github/workflows/format.yml | 3 + CHANGELOG.md | 19 ++- crates/edgezero-adapter-spin/src/outbound.rs | 3 +- .../tests/sdk_resources.rs | 37 ++++- crates/edgezero-cli/Cargo.toml | 2 +- crates/edgezero-core/src/compression.rs | 9 +- crates/edgezero-test-harness/SUITES.md | 2 +- .../crates/fixture-core/src/lib.rs | 10 +- .../crates/fixture-core/src/qualification.rs | 50 ++++++ .../src/qualification/transport.rs | 16 +- .../fixture-spin-support/src/outbound.rs | 10 +- .../crates/fixture-spin-wire/src/lib.rs | 16 +- .../src/evidence/cutover/reviewed_owners.json | 2 +- crates/edgezero-test-harness/src/main.rs | 147 ++++++++++++++++-- .../src/net/wire/transport.rs | 9 +- .../src/runners/progress.rs | 72 +++++---- .../edgezero-test-harness/src/runners/wire.rs | 39 ++++- .../src/runners/wire/transport.rs | 104 ++++++++++++- crates/edgezero-test-harness/src/startup.rs | 1 + .../src/startup/build_identity.rs | 97 +++++++++++- ...6-09-29-flate-decoder-memory-accounting.md | 12 +- docs/guide/capabilities.md | 19 ++- .../2026-09-15-reusable-app-lifecycle.md | 6 +- .../plans/2026-11-07-pr275-review-repairs.md | 136 ++++++++++++++++ ...026-09-15-reusable-app-lifecycle-design.md | 15 +- scripts/ci_tooling.test.mjs | 6 + scripts/run_tests.sh | 1 + 27 files changed, 747 insertions(+), 96 deletions(-) diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index c2bbc3756..3e0c9cc37 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -75,6 +75,9 @@ jobs: - name: Run cargo clippy run: cargo clippy --workspace --all-targets --all-features -- -D warnings + - name: Check CLI-only library feature + run: cargo check --offline --locked -p edgezero-cli --lib --no-default-features --features cli + # The all-features build unifies the fastly adapter's `cli` and `fastly` # features, which can MASK a dead-code or cfg mistake that only surfaces in # one supported mode. Gate the two the matrix above does not: `cli` alone diff --git a/CHANGELOG.md b/CHANGELOG.md index 50a2f385a..5894556f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,19 @@ their scope when introduced; the current summary supersedes their then-pending A ### Head-First Outbound Hard Cut +- Restore isolated CLI-only compilation by enabling the adapter's CLI helpers explicitly; + check that feature selection independently of provider feature unification. +- Keep qualification lifecycle JSON unwrapped at the fixture telemetry sink, permitting Info + only for that target while ordinary fixture logs retain Warn/Error filtering. +- Supervise progress fixture builds, Cargo metadata and version probes through the existing + process owner, preserving separate stdout/diagnostics and direct-signal descendant cleanup. + Exclude only the selected canonical evidence subtree from fresh source/build identities; + keep dirty/untracked source detection and scoped restoration intact. +- Omit synthesized zero lengths and unnecessary body writers for known-empty Spin + DELETE/OPTIONS. Retain empty POST/PUT/PATCH lengths and document the host's possible empty + chunked framing without relaxing GET/HEAD suppression or any upload/deadline limit. +- Include the codec-wrapper reserve in the flate audit subtotal (77,824 bytes). The conservative + decoder charge stays 1 MiB; no dependency pin, allocation policy or capability is promoted. - Keep startup-attestation test listeners owned from bind through shutdown. The child publishes its ephemeral endpoint, PID and launch nonce atomically; the fixture validates bounded metadata before its first prescribed HTTP request. Preserve response attestation, sticky failures and @@ -532,8 +545,10 @@ their scope when introduced; the current summary supersedes their then-pending A engine shared by the existing Send and Batch receive paths. Select borrowed handle identities, validate every result, rotate slot service, and perform at most one 16 KiB raw read per fresh matching readiness observation. Remove the superseded ownership-reassociation implementation. -- Preserve cached SDK Send behavior with nonblocking opaque-head polling and one shared positive - 1 ms pulse. Keep B31, original deadlines/cutoffs, typed source errors and response policies; +- Preserve SDK cache selection for buffered Send and Batch under both PlatformDefault and + Bypass, with nonblocking opaque-head polling and one shared positive 1 ms pulse. This includes + uncached heads; CPU cost grows with pending slot count and wait duration. + Keep B31, original deadlines/cutoffs, typed source errors and response policies; leave direct native Image Optimizer dispatch unchanged. Ready results backpressure only their own slot, with exactly-once local lease cleanup on cancellation/terminal paths. - Release batch drivers on terminal or poisoned observations even when callers retain the batch. diff --git a/crates/edgezero-adapter-spin/src/outbound.rs b/crates/edgezero-adapter-spin/src/outbound.rs index 4547c62ab..535026bc0 100644 --- a/crates/edgezero-adapter-spin/src/outbound.rs +++ b/crates/edgezero-adapter-spin/src/outbound.rs @@ -678,7 +678,7 @@ mod spin_impl { const EMPTY_REQUEST_TRAILERS: fn() -> Result, ErrorCode> = || Ok(None); fn prepare_request_body(method: &Method, body: &Body) -> PreparedRequestBody { - if matches!(*method, Method::GET | Method::HEAD) + if !matches!(*method, Method::POST | Method::PUT | Method::PATCH) && body.as_bytes().is_some_and(<[u8]>::is_empty) { // Publish clean trailers, not BodyWriter's error-on-drop default. @@ -904,6 +904,7 @@ mod spin_impl { ) -> Result { if !matches!(*method, Method::GET | Method::HEAD) && let Some(bytes) = body.as_bytes() + && (!bytes.is_empty() || matches!(*method, Method::POST | Method::PUT | Method::PATCH)) { let length = HeaderValue::from_str(&bytes.len().to_string()).map_err(|_error| { EdgeError::internal(anyhow::anyhow!( diff --git a/crates/edgezero-adapter-spin/tests/sdk_resources.rs b/crates/edgezero-adapter-spin/tests/sdk_resources.rs index a9f80f7ac..152aec77b 100644 --- a/crates/edgezero-adapter-spin/tests/sdk_resources.rs +++ b/crates/edgezero-adapter-spin/tests/sdk_resources.rs @@ -511,19 +511,31 @@ mod tests { #[test] fn buffered_length_is_derived_after_normalization_without_polling_streams() { use edgezero_core::Body; - for method in [Method::GET, Method::HEAD, Method::POST, Method::PUT] { + for (method, empty_length) in [ + (Method::GET, false), + (Method::HEAD, false), + (Method::POST, true), + (Method::PUT, true), + (Method::PATCH, true), + (Method::DELETE, false), + (Method::OPTIONS, false), + ] { for payload in ["", "abc"] { if matches!(method, Method::GET | Method::HEAD) && !payload.is_empty() { continue; } let mut headers = HeaderMap::new(); let fields = request_fields(&method, &Body::from(payload), &mut headers).unwrap(); - let expected = if matches!(method, Method::GET | Method::HEAD) { + let expected = if payload.is_empty() && !empty_length { vec![] } else { vec![payload.len().to_string().into_bytes()] }; - assert_eq!(fields.get("content-length"), expected); + assert_eq!( + fields.get("content-length"), + expected, + "{method} {payload:?}" + ); } } let stream = poll_fn(|_| -> Poll>> { @@ -555,6 +567,25 @@ mod tests { let fields = request_fields(&parts.method, &parts.body, &mut parts.headers).unwrap(); assert_eq!(fields.get("content-length"), vec![b"3".to_vec()]); assert!(fields.get("transfer-encoding").is_empty()); + for method in [Method::DELETE, Method::OPTIONS] { + let mut empty_request = + OutboundRequest::new(method, "http://example.com/".parse().unwrap()) + .unwrap() + .header("content-length", "999") + .unwrap() + .header("transfer-encoding", "chunked") + .unwrap(); + normalize_for_dispatch(&mut empty_request).unwrap(); + let mut empty_parts = empty_request.into_parts(); + let empty_fields = request_fields( + &empty_parts.method, + &empty_parts.body, + &mut empty_parts.headers, + ) + .unwrap(); + assert!(empty_fields.get("content-length").is_empty()); + assert!(empty_fields.get("transfer-encoding").is_empty()); + } } #[test] diff --git a/crates/edgezero-cli/Cargo.toml b/crates/edgezero-cli/Cargo.toml index ea387f958..f7f8f3017 100644 --- a/crates/edgezero-cli/Cargo.toml +++ b/crates/edgezero-cli/Cargo.toml @@ -59,6 +59,6 @@ default = [ "edgezero-adapter-cloudflare", "edgezero-adapter-spin", ] -cli = ["dep:clap", "dep:handlebars"] +cli = ["dep:clap", "dep:handlebars", "edgezero-adapter/cli"] demo-example = ["dep:app-demo-core", "edgezero-adapter-axum"] nested-app-config-check = ["dep:proc-macro2", "dep:syn", "dep:walkdir"] diff --git a/crates/edgezero-core/src/compression.rs b/crates/edgezero-core/src/compression.rs index 7db696779..db4c11ce3 100644 --- a/crates/edgezero-core/src/compression.rs +++ b/crates/edgezero-core/src/compression.rs @@ -44,8 +44,8 @@ pub const BROTLI_DECODER_FIXED_CHARGE_BYTES: u64 = 16_777_216; /// /// The source audit in /// `docs/audits/2026-09-29-flate-decoder-memory-accounting.md` derives a -/// 73,728-byte reviewed subtotal. The 1 MiB reservation leaves conservative -/// headroom for wrapper objects, the boxed coroutine, alignment, and allocator +/// 77,824-byte reviewed subtotal, including the codec-wrapper reserve. The 1 MiB +/// reservation leaves conservative headroom for the boxed coroutine, alignment, and allocator /// variance that are not claimed as exact heap bounds. Dependency upgrades must /// repeat the audit before changing either the pins or this charge. pub const FLATE_DECODER_FIXED_CHARGE_BYTES: u64 = 0x0010_0000; @@ -780,8 +780,9 @@ mod tests { assert_eq!(decode_buffer_bytes, 8_192); assert_eq!(FLATE_DECODER_FIXED_CHARGE_BYTES, PUBLIC_CHARGE_BYTES); - let audited_payload_bytes = INFLATE_STATE_RESERVE_BYTES + decode_buffer_bytes; - assert_eq!(audited_payload_bytes, 73_728); + let audited_payload_bytes = + INFLATE_STATE_RESERVE_BYTES + CODEC_WRAPPER_RESERVE_BYTES + decode_buffer_bytes; + assert_eq!(audited_payload_bytes, 77_824); assert!(audited_payload_bytes <= FLATE_DECODER_FIXED_CHARGE_BYTES); } diff --git a/crates/edgezero-test-harness/SUITES.md b/crates/edgezero-test-harness/SUITES.md index 856a9ce55..93c878b81 100644 --- a/crates/edgezero-test-harness/SUITES.md +++ b/crates/edgezero-test-harness/SUITES.md @@ -207,7 +207,7 @@ do not promote it solely from a checkpoint test count or green CI. The EZ-23 ready legs share one full Axum suite command, including ignored tests: ```sh -scripts/run_test_nonzero.sh --include-ignored --inventory axum/native-tcp,unit/axum,axum/http1,axum cargo test --offline --locked -p edgezero-adapter-axum --no-default-features --features axum,test-utils --all-targets +scripts/run_test_nonzero.sh --include-ignored --inventory axum/native-tcp,unit/axum,axum/http1,axum,axum/http1-chunked cargo test --offline --locked -p edgezero-adapter-axum --no-default-features --features axum,test-utils --all-targets ``` The guard selects the exact declared command as well as the environment. This keeps Rust test diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/lib.rs b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/lib.rs index 386e1b0ad..51982a5da 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/lib.rs +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/lib.rs @@ -27,9 +27,17 @@ struct FixtureLogger; impl log::Log for FixtureLogger { fn enabled(&self, metadata: &log::Metadata<'_>) -> bool { metadata.level() <= log::Level::Warn + || (metadata.target() == "edgezero_qualification" + && metadata.level() <= log::Level::Info) } fn log(&self, record: &log::Record<'_>) { if self.enabled(record.metadata()) { + if record.target() == "edgezero_qualification" { + if let Some(sink) = TELEMETRY.get() { + sink(&record.args().to_string()); + } + return; + } emit( serde_json::json!({"event":"fixture_log","instance":instance_id(), "level":record.level().to_string(),"target":record.target(),"message":record.args().to_string()}), @@ -49,7 +57,7 @@ pub fn init_fixture_logging(sink: fn(&str)) -> Result<(), EdgeError> { .map_err(|_error| { EdgeError::internal(std::io::Error::other("fixture logger installation failed")) })?; - log::set_max_level(log::LevelFilter::Warn); + log::set_max_level(log::LevelFilter::Info); Ok(()) } diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification.rs b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification.rs index 70d50df28..797f70760 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification.rs +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification.rs @@ -302,6 +302,56 @@ mod tests { use super::*; use futures::StreamExt as _; + #[test] + fn fixture_logging_emits_raw_lifecycle_events_but_filters_ordinary_info() { + static EVENTS: Mutex> = Mutex::new(Vec::new()); + fn sink(line: &str) { + EVENTS + .lock() + .unwrap() + .push(serde_json::from_str(line).unwrap()); + } + crate::init_fixture_logging(sink).expect("fixture logger"); + let trace = test_trace("logging-regression"); + let source = ProbeSource::new(Arc::clone(&trace)); + let resource = ResourceDropProbe(Arc::clone(&trace)); + drop(source); + trace.record("terminal", |state| state.terminals += 1, json!({})); + drop(resource); + drop(trace); + log::info!(target: "ordinary-fixture-regression", "filtered-info-control"); + log::warn!(target: "ordinary-fixture-regression", "retained-warning-control"); + + let events = EVENTS.lock().unwrap(); + let lifecycle: Vec<_> = events + .iter() + .filter(|event| event["case"] == "logging-regression") + .collect(); + assert_eq!( + lifecycle.len(), + 4, + "lifecycle telemetry must reach the raw sink" + ); + for (sequence, (event, kind)) in lifecycle + .iter() + .zip(["source-drop", "terminal", "resource-drop", "trace-closed"]) + .enumerate() + { + assert_eq!(event["event"], kind); + assert_eq!(event["sequence"], sequence); + assert_eq!(event["schema"], 1); + assert_eq!(event["run"], "test-run"); + assert_eq!(event["probe"], "test-1"); + } + assert!( + !events + .iter() + .any(|event| event["message"] == "filtered-info-control") + ); + assert!(events.iter().any(|event| event["event"] == "fixture_log" + && event["message"] == "retained-warning-control")); + } + #[test] fn finite_source_releases_once_and_never_polls_after_terminal() { let trace = test_trace("normal"); diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/transport.rs b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/transport.rs index 9dca19e71..7016144b7 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/transport.rs +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/transport.rs @@ -40,6 +40,9 @@ pub const PARITY_CASES: &[&str] = &[ "parity-upload-cap", "parity-zero-timeout", "parity-expired", + "parity-empty-post", + "parity-empty-delete", + "parity-empty-options", ]; #[derive(Clone, Copy)] @@ -290,7 +293,9 @@ fn parity_request( ) -> Result { let method = match case { "parity-head" => Method::HEAD, - "parity-post" | "parity-upload-cap" => Method::POST, + "parity-post" | "parity-upload-cap" | "parity-empty-post" => Method::POST, + "parity-empty-delete" => Method::DELETE, + "parity-empty-options" => Method::OPTIONS, _ => Method::GET, }; let mut request = OutboundRequest::new(method, uri)? @@ -587,8 +592,15 @@ mod tests { request.method(), if *case == "parity-head" { Method::HEAD - } else if matches!(*case, "parity-post" | "parity-upload-cap") { + } else if matches!( + *case, + "parity-post" | "parity-upload-cap" | "parity-empty-post" + ) { Method::POST + } else if *case == "parity-empty-delete" { + Method::DELETE + } else if *case == "parity-empty-options" { + Method::OPTIONS } else { Method::GET } diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-spin-support/src/outbound.rs b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-spin-support/src/outbound.rs index 730522630..85591a6d9 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-spin-support/src/outbound.rs +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-spin-support/src/outbound.rs @@ -110,11 +110,11 @@ pub fn provider_error_payloads_hold() -> bool { true } -fn bodyless_request_resources_hold() -> bool { +pub fn bodyless_request_resources_hold() -> bool { if !matches!(test_support::empty_request_trailers(), Ok(None)) { return false; } - for method in [Method::GET, Method::HEAD] { + for method in [Method::GET, Method::HEAD, Method::DELETE, Method::OPTIONS] { let body = request_body_resources(&method, &Body::empty()); if body.0.is_some() || body.1.is_some() { drop((body.1, body.2, body.0)); @@ -136,6 +136,10 @@ fn bodyless_request_resources_hold() -> bool { } for (method, source) in [ (Method::POST, Body::empty()), + (Method::PUT, Body::empty()), + (Method::PATCH, Body::empty()), + (Method::DELETE, Body::from("payload")), + (Method::OPTIONS, Body::from("payload")), (Method::GET, Body::from("payload")), ] { let (writer, contents, trailers) = request_body_resources(&method, &source); @@ -325,7 +329,7 @@ pub async fn eager_outbound_paths_hold() -> Result<(), EdgeError> { scopes::canonical_callback_releases_retained_handles().await?; if !bodyless_request_resources_hold() { return Err(EdgeError::internal(anyhow::anyhow!( - "certified empty GET/HEAD must omit WASI contents and close cleanly; other methods retain upload resources" + "known-empty non-content methods must omit WASI contents and close cleanly; content-bearing methods retain upload resources" ))); } check_eager_begin().await?; diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-spin-wire/src/lib.rs b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-spin-wire/src/lib.rs index 03dd64323..0864b511e 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-spin-wire/src/lib.rs +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-spin-wire/src/lib.rs @@ -124,10 +124,19 @@ mod sdk { } if path == "/scope" { drop(request); + if !fixture_spin_support::outbound::bodyless_request_resources_hold() { + return Err(ErrorCode::InternalError(Some( + "empty buffered method resources changed".to_owned(), + ))); + } canonical_entrypoints_release_retained_handles() .await .map_err(|error| ErrorCode::InternalError(Some(error.to_string())))?; - return empty_response(); + let headers = Fields::new(); + headers + .append("x-fixture-empty-method-resources", b"pass") + .map_err(|_| ErrorCode::HttpProtocolError)?; + return empty_response(headers); } let method = match path.as_str() { "/get" | "/get-settled" | "/p5" | "/policy" | "/normalization" @@ -227,7 +236,7 @@ mod sdk { .map_err(|_error| { ErrorCode::InternalError(Some("outbound wire check failed".to_owned())) })?; - empty_response() + empty_response(Fields::new()) } } @@ -273,8 +282,7 @@ mod sdk { eprintln!("FAIL: Spin attached Begin/Batch handoff terminal ownership"); } - fn empty_response() -> Result { - let headers = Fields::new(); + fn empty_response(headers: Fields) -> Result { if let (Ok(nonce), Some(build)) = ( env::var("EDGEZERO_FIXTURE_LAUNCH_NONCE"), option_env!("EDGEZERO_FIXTURE_BUILD_ID"), diff --git a/crates/edgezero-test-harness/src/evidence/cutover/reviewed_owners.json b/crates/edgezero-test-harness/src/evidence/cutover/reviewed_owners.json index 97cef078d..9a6bba9f4 100644 --- a/crates/edgezero-test-harness/src/evidence/cutover/reviewed_owners.json +++ b/crates/edgezero-test-harness/src/evidence/cutover/reviewed_owners.json @@ -2,7 +2,7 @@ "src/main.rs:outbound_lifetimes_selects_exactly_one_explicit_provider": "db8098c65fe1d4c32b4c7572883e02b1267d6ddaa99b751d35a087052409942c", "src/main.rs:outbound_wire_suite_is_explicit_and_selects_one_supported_provider": "5e6bd8b1f347422d0030acab5e43a8c0d9fffbad7f304d7171847fc7e4e04ae7", "src/main.rs:parse_from": "2aef1c2d5aca6902f8c6f67ed820ea578a4062d1f2b9eb16abd25d7bc9a558ac", - "src/main.rs:run": "f8d3b78414c5d69c74c5b6e69a24fe0d1e8ae61067e0247cbff17bf375b237f7", + "src/main.rs:run": "744c16f7b155adb4d27933eed21ab7b6d0adcc40ac81b787e2b8e164b2b78fb5", "src/runners.rs:fastly": "cbea839284606bc7bd552675bdacc8b33c4ff7fe6e8c5ca80a28cd93f8d2117c", "src/runners.rs:provider": "611830f75cbb95179b853a39f49ba9839a9cb06c2967b769a7d9300a40536f5b", "src/runners/ci.rs:phase_with_exit": "071915332c0cd8d29aeade1fc89ed79d35b38037c76d41e55160c11f7f31e76e", diff --git a/crates/edgezero-test-harness/src/main.rs b/crates/edgezero-test-harness/src/main.rs index 84c877383..9a2e711f7 100644 --- a/crates/edgezero-test-harness/src/main.rs +++ b/crates/edgezero-test-harness/src/main.rs @@ -740,6 +740,7 @@ fn run(arguments: Vec) -> Result { } fs::create_dir_all(&path)?; let path = path.canonicalize()?; + let _output_directory = startup::OutputDirectory::enter(&path)?; if args.suite == "ingress-fidelity" { fidelity::run(&args, &path)?; return Ok(0); @@ -1823,6 +1824,112 @@ mod process_tests { } } + fn assert_progress_cargo_cancellation(adapter: &str) { + use std::os::unix::fs::PermissionsExt; + + let fixture = Fixture::new(); + let cargo = fixture.0.join("cargo"); + fs::write(&cargo, r#"#!/bin/sh +case "$1" in + --version) printf 'cargo process-fixture\n'; exit 0 ;; + build|metadata) + printf '%s' "$$" > "$EDGEZERO_PROCESS_TEST_DIR/cargo-started" + export EDGEZERO_PROCESS_TEST_MODE=descendant + exec "$EDGEZERO_TEST_HELPER" --ignored --exact process_tests::outbound_wire_process_helper --nocapture --test-threads=1 + ;; + *) exit 64 ;; +esac +"#).unwrap(); + fs::set_permissions(&cargo, fs::Permissions::from_mode(0o700)).unwrap(); + let output = fixture.0.join("evidence"); + let mut command = static_check_command(&fixture, "--help"); + command + .env( + "EDGEZERO_STATIC_CHECK_ARGS", + json!([ + "--adapter", + adapter, + "--suite", + "outbound-progress", + "--output", + output, + ]) + .to_string(), + ) + .env("EDGEZERO_TEST_HELPER", std::env::current_exe().unwrap()) + .env("CARGO", &cargo) + .env("RUSTC", executable("RUSTC", "rustc").unwrap()) + .env("WRANGLER_BIN", &cargo) + .env("WORKER_BUILD_BIN", &cargo); + let mut controller = + Process::spawn(&mut command, &fixture.0.join("controller.log")).unwrap(); + fixture.ready(); + let cargo_id = fs::read_to_string(fixture.0.join("cargo-started")) + .unwrap() + .parse::() + .unwrap(); + let mut cleanup = GroupCleanup(Some(cargo_id)); + let port = fixture.descendant_port(); + assert!(std::net::TcpStream::connect(("127.0.0.1", port)).is_ok()); + signal_target( + SignalTarget::Pid(controller.0.id()), + Some(Signal::SIGTERM), + Instant::now() + Duration::from_secs(2), + ) + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(3); + while controller.child_status().unwrap().is_none() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(10)); + } + let completed = controller.child_status().unwrap().is_some(); + let child = signal_target( + SignalTarget::Pid(cargo_id), + None, + Instant::now() + Duration::from_secs(2), + ) + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(1); + let descendant_closed = loop { + if std::net::TcpStream::connect(("127.0.0.1", port)).is_err() { + break true; + } + if Instant::now() >= deadline { + break false; + } + thread::sleep(Duration::from_millis(10)); + }; + let outcome = if completed { + controller.wait_exit_code(1).map(|_| ()) + } else { + controller.finish() + }; + cleanup.finish().unwrap(); + assert!( + completed, + "{adapter}: direct cancellation did not stop Cargo" + ); + outcome.unwrap(); + assert_eq!( + child, + SignalOutcome::Absent, + "{adapter}: Cargo was not reaped" + ); + assert!( + descendant_closed, + "{adapter}: Cargo descendant retained its socket" + ); + } + + #[test] + fn progress_build_cancellation_reaps_cargo_and_descendants() { + assert_progress_cargo_cancellation("axum"); + } + + #[test] + fn progress_metadata_cancellation_reaps_cargo_and_descendants() { + assert_progress_cargo_cancellation("cloudflare"); + } + #[test] fn failed_process_fixture_preserves_diagnostics_until_explicit_cleanup() { let fixture = Fixture::new(); @@ -2175,9 +2282,11 @@ mod process_tests { #[test] fn startup_responder_rejects_invalid_endpoint_publication() { let fixture = Fixture::new(); - let mut process = fixture.spawn("graceful"); + let mut command = fixture.command("graceful"); + let nonce = startup::command(&mut command, "fixture-test", TEST_BUILD_ID); + let mut process = Process::spawn(&mut command, &fixture.0.join("runtime.log")).unwrap(); fixture.ready(); - let endpoint = json!({"pid":process.0.id(), "nonce":"expected", "port":1234}); + let endpoint = json!({"pid":process.0.id(), "nonce":nonce, "port":1234}); let mut invalid = vec![json!(null), json!([]), json!("not an endpoint")]; for (field, value) in [ ("pid", json!(u64::from(process.0.id()) + 1)), @@ -2209,7 +2318,7 @@ mod process_tests { let error = fixture .responder_port( &mut process, - "expected", + &nonce, Instant::now() + Duration::from_secs(5), ) .unwrap_err() @@ -2218,18 +2327,33 @@ mod process_tests { assert!(!error.contains("private-foreign-nonce"), "{error}"); assert!(!fixture.0.join("ordinal").exists()); } + let mut exact = serde_json::to_vec(&endpoint).unwrap(); + exact.resize(1024, b' '); + fs::write(fixture.0.join("endpoint.json"), exact).unwrap(); + assert_eq!( + fixture + .responder_port( + &mut process, + &nonce, + Instant::now() + Duration::from_secs(5) + ) + .unwrap(), + 1234 + ); process.finish().unwrap(); } #[test] fn startup_responder_publication_preserves_deadline_and_child_liveness() { let fixture = Fixture::new(); - let mut process = fixture.spawn("graceful"); + let mut command = fixture.command("graceful"); + let nonce = startup::command(&mut command, "fixture-test", TEST_BUILD_ID); + let mut process = Process::spawn(&mut command, &fixture.0.join("runtime.log")).unwrap(); fixture.ready(); let error = fixture .responder_port( &mut process, - "expected", + &nonce, Instant::now() + Duration::from_millis(20), ) .unwrap_err(); @@ -2237,14 +2361,14 @@ mod process_tests { error.to_string().contains("endpoint deadline expired"), "{error}" ); - let endpoint = json!({"pid":process.0.id(), "nonce":"expected", "port":1234}); + let endpoint = json!({"pid":process.0.id(), "nonce":nonce, "port":1234}); fs::write( fixture.0.join("endpoint.json"), serde_json::to_vec(&endpoint).unwrap(), ) .unwrap(); let error = fixture - .responder_port(&mut process, "expected", Instant::now()) + .responder_port(&mut process, &nonce, Instant::now()) .unwrap_err(); assert!( error.to_string().contains("endpoint deadline expired"), @@ -2253,9 +2377,12 @@ mod process_tests { process.finish().unwrap(); let exited_fixture = Fixture::new(); - let mut process = exited_fixture.spawn("exit-zero"); + let mut command = exited_fixture.command("exit-zero"); + let nonce = startup::command(&mut command, "fixture-test", TEST_BUILD_ID); + let mut process = + Process::spawn(&mut command, &exited_fixture.0.join("runtime.log")).unwrap(); until(|| process.child_status().unwrap().is_some()); - let endpoint = json!({"pid":process.0.id(), "nonce":"expected", "port":1234}); + let endpoint = json!({"pid":process.0.id(), "nonce":nonce, "port":1234}); fs::write( exited_fixture.0.join("endpoint.json"), serde_json::to_vec(&endpoint).unwrap(), @@ -2264,7 +2391,7 @@ mod process_tests { let error = exited_fixture .responder_port( &mut process, - "expected", + &nonce, Instant::now() + Duration::from_secs(5), ) .unwrap_err(); diff --git a/crates/edgezero-test-harness/src/net/wire/transport.rs b/crates/edgezero-test-harness/src/net/wire/transport.rs index 0682d45ef..4b8658384 100644 --- a/crates/edgezero-test-harness/src/net/wire/transport.rs +++ b/crates/edgezero-test-harness/src/net/wire/transport.rs @@ -66,6 +66,9 @@ pub(super) fn serve( | "parity-gzip" | "parity-original" | "parity-opaque" + | "parity-empty-post" + | "parity-empty-delete" + | "parity-empty-options" ), "unknown transport route", )?; @@ -102,8 +105,12 @@ pub(super) fn serve( no_trailing_bytes(reader)?; let expected_method = if let Some(spec) = paired_case { spec.request_method() - } else if case == "parity-post" { + } else if matches!(case, "parity-post" | "parity-empty-post") { "POST" + } else if case == "parity-empty-delete" { + "DELETE" + } else if case == "parity-empty-options" { + "OPTIONS" } else if case == "parity-head" { "HEAD" } else { diff --git a/crates/edgezero-test-harness/src/runners/progress.rs b/crates/edgezero-test-harness/src/runners/progress.rs index a50f8fa83..fd34f22a7 100644 --- a/crates/edgezero-test-harness/src/runners/progress.rs +++ b/crates/edgezero-test-harness/src/runners/progress.rs @@ -3,15 +3,14 @@ use super::*; pub(super) fn run(name: &str, parent: &Path, records: &mut Records) -> Result<()> { let run = parent.join(format!("progress-{name}")); fs::create_dir_all(&run)?; - let revision = Command::new("git") - .args(["rev-parse", "HEAD"]) - .current_dir(fixture_root()) - .output()?; - require( - revision.status.success(), - "cannot determine progress source revision", + let revision = capture_command( + Command::new("git") + .args(["rev-parse", "HEAD"]) + .current_dir(fixture_root()), + &run, + "source-revision", )?; - let revision = String::from_utf8(revision.stdout)?.trim().to_owned(); + let revision = String::from_utf8(revision)?.trim().to_owned(); let Some((mut command, port)) = build(name, &run, records, &revision, "outbound-progress")? else { return Ok(()); @@ -366,6 +365,13 @@ fn progress_feature(name: &str, suite: &str) -> &'static str { } } +fn capture_command(command: &mut Command, run: &Path, name: &str) -> Result> { + let stdout = run.join(format!("{name}.stdout")); + let diagnostics = run.join(format!("{name}.stderr")); + Process::spawn_with_stdout(command, &diagnostics, &stdout)?.wait_success()?; + Ok(fs::read(stdout)?) +} + pub(super) fn build( name: &str, run: &Path, @@ -388,8 +394,9 @@ pub(super) fn build( records.push(json!({"status":"unsupported","adapter":name,"phase":"outbound-progress","reason":format!("{fallback} unavailable"),"qualification":false}))?; return Ok(None); }; + let version = capture_command(Command::new(&exe).arg("--version"), run, "runtime-version")?; records.push(json!({"event":"progress-runtime","adapter":name,"executable":exe, - "version":String::from_utf8_lossy(&Command::new(&exe).arg("--version").output()?.stdout).trim(),"revision":revision,"source_state":"working-tree-characterization"}))?; + "version":String::from_utf8_lossy(&version).trim(),"revision":revision,"source_state":"working-tree-characterization"}))?; let artifact_path = if name == "cloudflare" { let Some(builder) = executable("WORKER_BUILD_BIN", "worker-build") else { records.push(json!({"status":"unsupported","adapter":name,"phase":"outbound-progress","reason":"worker-build unavailable"}))?; @@ -452,17 +459,13 @@ pub(super) fn build( command.args(["--bin", "fixture-axum-outbound-progress"]); } command.arg("--message-format=json-render-diagnostics"); - let output = command.stderr(Stdio::inherit()).output()?; - require( - output.status.success(), - format!("{name} progress fixture build failed"), - )?; + let output = capture_command(&mut command, run, "cargo-build")?; let source = match name { "spin" => fixture_root().join("target/wasm32-wasip2/release/fixture_spin.wasm"), "fastly" => fixture_root() .join("target/wasm32-wasip1/release") .join(wasm_name(fastly_variant)), - _ => built_executable(&output.stdout, "fixture-axum-outbound-progress")?, + _ => built_executable(&output, "fixture-axum-outbound-progress")?, }; stage(&source, run)? }; @@ -486,8 +489,13 @@ pub(super) fn build( // Prevent worker-build from implicitly downloading/replacing tools during characterization. pub(super) fn check_bindgen(records: &mut Records) -> Result { - let output = cargo_build()? - .args([ + let run = records + .path + .parent() + .ok_or("missing evidence directory")? + .to_owned(); + let output = capture_command( + cargo_build()?.args([ "metadata", "--offline", "--locked", @@ -495,13 +503,11 @@ pub(super) fn check_bindgen(records: &mut Records) -> Result { "1", "--filter-platform", "wasm32-unknown-unknown", - ]) - .output()?; - require( - output.status.success(), - "cannot inspect locked wasm-bindgen version", + ]), + &run, + "cargo-metadata", )?; - let metadata: Value = serde_json::from_slice(&output.stdout)?; + let metadata: Value = serde_json::from_slice(&output)?; let version = metadata["packages"] .as_array() .ok_or("missing Cargo packages")? @@ -512,11 +518,17 @@ pub(super) fn check_bindgen(records: &mut Records) -> Result { let installed = executable("WASM_BINDGEN_BIN", "wasm-bindgen"); let observed = installed .as_ref() - .map(|exe| Command::new(exe).arg("--version").output()) + .map(|exe| { + capture_command( + Command::new(exe).arg("--version"), + &run, + "wasm-bindgen-version", + ) + }) .transpose()?; let observed = observed .as_ref() - .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()); + .map(|output| String::from_utf8_lossy(output).trim().to_owned()); let ready = observed.as_deref() == Some(format!("wasm-bindgen {version}").as_str()); if !ready { records.push(json!({"status":"unsupported","adapter":"cloudflare","phase":"build-tooling","required_wasm_bindgen":version,"observed":observed,"reason":"matching wasm-bindgen CLI unavailable; no download or dependency repin attempted","qualification":false}))?; @@ -532,12 +544,12 @@ pub(super) fn check_bindgen(records: &mut Records) -> Result { records.push(json!({"status":"unsupported","adapter":"cloudflare","phase":"build-tooling","reason":format!("set {variable} to an existing absolute executable; automatic installation is disabled"),"qualification":false}))?; return Ok(false); }; - let output = Command::new(&path).arg("--version").output()?; - require( - output.status.success(), - format!("{variable} version command failed"), + let output = capture_command( + Command::new(&path).arg("--version"), + &run, + &format!("{variable}-version"), )?; - records.push(json!({"event":"worker-build-tool","variable":variable,"executable":path,"version":String::from_utf8_lossy(&output.stdout).trim()}))?; + records.push(json!({"event":"worker-build-tool","variable":variable,"executable":path,"version":String::from_utf8_lossy(&output).trim()}))?; } } Ok(ready) diff --git a/crates/edgezero-test-harness/src/runners/wire.rs b/crates/edgezero-test-harness/src/runners/wire.rs index 0df58edfc..cd420201d 100644 --- a/crates/edgezero-test-harness/src/runners/wire.rs +++ b/crates/edgezero-test-harness/src/runners/wire.rs @@ -832,6 +832,21 @@ fn component_text(directory: &Path) -> Result { Ok(text) } +fn validate_empty_method_resources(scope: &Value) -> Result<()> { + let headers = scope["headers"].as_array().ok_or("missing scope headers")?; + let mut markers = headers.iter().filter(|field| { + field[0] + .as_str() + .is_some_and(|name| name.eq_ignore_ascii_case("x-fixture-empty-method-resources")) + }); + require( + scope["status"] == 200 + && markers.next().is_some_and(|field| field[1] == "pass") + && markers.next().is_none(), + "canonical scope or empty-method SDK resource control failed", + ) +} + fn controls(port: u16, origins: &WireOrigins, log_dir: &Path, process: &mut Process) -> Result<()> { for name in ["get", "head", "get-settled", "head-settled", "post"] { let uri = format!("http://127.0.0.1:{}/{name}", origins.port(0)); @@ -870,10 +885,8 @@ fn controls(port: u16, origins: &WireOrigins, log_dir: &Path, process: &mut Proc )?; } } - require( - net::header_request(port, "/scope", &token(), &[], None)?["status"] == 200, - "canonical scope control failed", - )?; + let scope = net::header_request(port, "/scope", &token(), &[], None)?; + validate_empty_method_resources(&scope)?; let uri = format!("http://127.0.0.1:{}", origins.port(0)); let reply = net::header_request(port, "/handoff", &token(), &[("x-origin", &uri)], None)?; require(reply["status"] == 200, "handoff guest failed")?; @@ -1150,6 +1163,24 @@ fn finish_wire( mod tests { use super::*; + #[test] + fn empty_method_resource_receipt_requires_one_unambiguous_pass() { + let marker = "x-fixture-empty-method-resources"; + validate_empty_method_resources(&json!({"status":200, + "headers":[["X-Fixture-Empty-Method-Resources", "pass"]]})) + .unwrap(); + for headers in [ + json!([]), + json!([[marker, "fail"]]), + json!([[marker, "pass"], [marker, "fail"]]), + json!([[marker, "pass"], [marker, "pass"]]), + ] { + assert!( + validate_empty_method_resources(&json!({"status":200,"headers":headers})).is_err() + ); + } + } + fn wire_error(kind: &str, reason: &str) -> Value { json!({"error":{"kind":kind,"reason":reason, "status":if kind == "gateway_timeout" {504} else {502},"provider":null}}) diff --git a/crates/edgezero-test-harness/src/runners/wire/transport.rs b/crates/edgezero-test-harness/src/runners/wire/transport.rs index 333128479..ab74bb9e5 100644 --- a/crates/edgezero-test-harness/src/runners/wire/transport.rs +++ b/crates/edgezero-test-harness/src/runners/wire/transport.rs @@ -24,6 +24,9 @@ const PARITY: &[&str] = &[ "parity-upload-cap", "parity-zero-timeout", "parity-expired", + "parity-empty-post", + "parity-empty-delete", + "parity-empty-options", ]; const GZIP: &[u8] = &[ 31, 139, 8, 0, 0, 0, 0, 0, 0, 3, 75, 76, 132, 1, 0, 240, 205, 17, 76, 10, 0, 0, 0, @@ -625,14 +628,18 @@ pub(super) fn validate_artifact(events: &[Value], adapter: &str) -> Result<()> { "native transport origin count differs", )?; for (receipt, (origin, route, step)) in origins.iter().zip(wanted) { - let method = if case == "parity-post" { + let method = if matches!(case, "parity-post" | "parity-empty-post") { "POST" + } else if case == "parity-empty-delete" { + "DELETE" + } else if case == "parity-empty-options" { + "OPTIONS" } else if case == "parity-head" { "HEAD" } else { "GET" }; - let payload = if method == "POST" { "abc" } else { "" }; + let payload = if case == "parity-post" { "abc" } else { "" }; require( receipt["port"] == ports[origin] && receipt["target"] == path(route, token) @@ -667,11 +674,30 @@ pub(super) fn validate_artifact(events: &[Value], adapter: &str) -> Result<()> { "buffered Spin upload lost its trusted content length", )?; } + if adapter == "spin" && case == "parity-empty-post" { + require( + lengths == &vec![json!("0")] && encodings.is_empty(), + "empty Spin POST lost its trusted zero length", + )?; + } + let spin_empty_method = + adapter == "spin" && matches!(case, "parity-empty-delete" | "parity-empty-options"); + if spin_empty_method { + require( + lengths.is_empty() + && receipt["payload"] == "" + && ((encodings.is_empty() && receipt["encoded_body_hex"] == "") + || (encodings == &vec![json!("chunked")] + && receipt["encoded_body_hex"] == "300d0a0d0a")), + "empty Spin method gained a length or nonempty host framing", + )?; + } require( lengths.len() <= 1 && encodings.len() <= 1 && (lengths.is_empty() || encodings.is_empty()) - && (method == "POST" + && (spin_empty_method + || method == "POST" || (encodings.is_empty() && lengths.iter().all(|v| v == "0") && receipt["encoded_body_hex"] == "")), @@ -949,8 +975,8 @@ pub(super) mod tests { let origin=receipts(case).into_iter().map(|(index,route,step)|{ let payload=if *case=="parity-post" {"abc"} else {""}; json!({"port":4001+index,"target":path(route,&token),"token":token,"step":step, - "method":if *case=="parity-post" {"POST"} else if *case=="parity-head" {"HEAD"} else {"GET"}, - "payload":payload,"encoded_body_hex":if payload.is_empty() {""} else {"616263"},"content_length":[payload.len().to_string()],"transfer_encoding":[], + "method":match *case {"parity-post"|"parity-empty-post"=>"POST","parity-empty-delete"=>"DELETE","parity-empty-options"=>"OPTIONS","parity-head"=>"HEAD",_=>"GET"}, + "payload":payload,"encoded_body_hex":if payload.is_empty() {""} else {"616263"},"content_length":if adapter=="spin" && matches!(*case,"parity-empty-delete"|"parity-empty-options") {vec![]} else {vec![payload.len().to_string()]},"transfer_encoding":[], "proof":if *case=="target" {vec!["application-value"]} else {vec![]},"signature":if *case=="target" {vec!["user-built-signature"]} else {vec![]}, "head_delay_us":if *case=="head-900" {Some(900_000)} else {None}}) }).collect::>(); @@ -971,6 +997,74 @@ pub(super) mod tests { } } + #[test] + fn native_transport_evidence_checks_empty_method_framing() { + let valid = artifact("spin"); + validate_artifact(&valid, "spin").unwrap(); + for case in [ + "parity-empty-post", + "parity-empty-delete", + "parity-empty-options", + ] { + for step in [0, 1] { + let mut events = valid.clone(); + let event = events + .iter_mut() + .find(|event| event["case"] == case) + .unwrap(); + event["origin"][step]["content_length"] = if case == "parity-empty-post" { + json!([]) + } else { + json!(["0"]) + }; + assert!(validate_artifact(&events, "spin").is_err(), "{case} {step}"); + } + } + } + + #[test] + fn spin_host_empty_chunking_is_limited_to_empty_delete_and_options() { + let valid = artifact("spin"); + for case in ["parity-empty-delete", "parity-empty-options"] { + for step in [0, 1] { + let mut host = valid.clone(); + let origin = &mut host.iter_mut().find(|event| event["case"] == case).unwrap()["origin"] + [step]; + origin["transfer_encoding"] = json!(["chunked"]); + origin["encoded_body_hex"] = json!("300d0a0d0a"); + validate_artifact(&host, "spin").expect("host's empty chunk terminator"); + for (field, value) in [ + ("content_length", json!(["0"])), + ("transfer_encoding", json!(["invalid"])), + ("transfer_encoding", json!(["chunked", "chunked"])), + ("payload", json!("x")), + ("encoded_body_hex", json!("")), + ("encoded_body_hex", json!("300d0a")), + ("encoded_body_hex", json!("300d0a0d0a00")), + ] { + let mut bad = host.clone(); + bad.iter_mut().find(|event| event["case"] == case).unwrap()["origin"][step] + [field] = value; + assert!( + validate_artifact(&bad, "spin").is_err(), + "{case} {step} {field}" + ); + } + } + } + for case in ["parity-default", "parity-head", "parity-empty-post"] { + for step in [0, 1] { + let mut bad = valid.clone(); + let origin = &mut bad.iter_mut().find(|event| event["case"] == case).unwrap()["origin"] + [step]; + origin["content_length"] = json!([]); + origin["transfer_encoding"] = json!(["chunked"]); + origin["encoded_body_hex"] = json!("300d0a0d0a"); + assert!(validate_artifact(&bad, "spin").is_err(), "{case} {step}"); + } + } + } + #[test] fn native_parity_rejects_the_legacy_seventeen_vector_slice_as_full_contract_proof() { for adapter in ["axum", "cloudflare", "fastly", "spin"] { diff --git a/crates/edgezero-test-harness/src/startup.rs b/crates/edgezero-test-harness/src/startup.rs index 9444bc0cf..018bec708 100644 --- a/crates/edgezero-test-harness/src/startup.rs +++ b/crates/edgezero-test-harness/src/startup.rs @@ -9,6 +9,7 @@ use std::{ }; mod build_identity; +pub(crate) use build_identity::OutputDirectory; pub const HEADER: &str = "x-edgezero-fixture-launch"; pub const NONCE: &str = "EDGEZERO_FIXTURE_LAUNCH_NONCE"; diff --git a/crates/edgezero-test-harness/src/startup/build_identity.rs b/crates/edgezero-test-harness/src/startup/build_identity.rs index 688e18296..7c8ff4418 100644 --- a/crates/edgezero-test-harness/src/startup/build_identity.rs +++ b/crates/edgezero-test-harness/src/startup/build_identity.rs @@ -1,17 +1,45 @@ use sha2::{Digest, Sha256}; use std::{ + cell::RefCell, collections::BTreeMap, env, ffi::{OsStr, OsString}, fs, io::{self, Read as _}, + marker::PhantomData, path::{Path, PathBuf}, process::Command, + rc::Rc, }; // Hash source trees directly, including dirty/untracked inputs, but never build outputs. const ROOTS: &[&str] = &["crates"]; +thread_local! { + static SELECTED_OUTPUT: RefCell> = const { RefCell::new(None) }; +} + +pub(crate) struct OutputDirectory { + previous: Option, + thread: PhantomData>, +} + +impl OutputDirectory { + pub(crate) fn enter(path: &Path) -> io::Result { + let path = path.canonicalize()?; + Ok(Self { + previous: SELECTED_OUTPUT.with_borrow_mut(|selected| selected.replace(path)), + thread: PhantomData, + }) + } +} + +impl Drop for OutputDirectory { + fn drop(&mut self) { + SELECTED_OUTPUT.with_borrow_mut(|selected| *selected = self.previous.take()); + } +} + pub(super) fn current() -> crate::Result { let root = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../..") @@ -159,14 +187,17 @@ fn ignored_output(path: &Path) -> bool { })) } -fn hash_tree(hash: &mut Sha256, root: &Path, path: &Path) -> io::Result<()> { +fn hash_tree(hash: &mut Sha256, root: &Path, path: &Path, output: Option<&Path>) -> io::Result<()> { + if output.is_some_and(|selected| path.starts_with(selected)) { + return Ok(()); + } let metadata = fs::symlink_metadata(path)?; if metadata.is_dir() { let mut entries = fs::read_dir(path)?.collect::>>()?; entries.sort_by_key(fs::DirEntry::file_name); for entry in entries { if !ignored_output(&entry.path()) { - hash_tree(hash, root, &entry.path())?; + hash_tree(hash, root, &entry.path(), output)?; } } } else if metadata.is_file() { @@ -203,15 +234,16 @@ fn capture( field(&mut hash, env::consts::ARCH.as_bytes()); field(&mut hash, compiler); field(&mut hash, cargo); + let output = SELECTED_OUTPUT.with_borrow(Clone::clone); for (name, value) in environment.iter().filter(|(name, _)| build_variable(name)) { field(&mut hash, name.as_os_str().as_encoded_bytes()); field(&mut hash, value.as_os_str().as_encoded_bytes()); } for input in ["Cargo.toml", "Cargo.lock", ".tool-versions"] { - hash_tree(&mut hash, root, &root.join(input))?; + hash_tree(&mut hash, root, &root.join(input), output.as_deref())?; } for input in ROOTS { - hash_tree(&mut hash, root, &root.join(input))?; + hash_tree(&mut hash, root, &root.join(input), output.as_deref())?; } let local_configs = [ ".cargo/config", @@ -249,6 +281,63 @@ fn capture( mod tests { use super::*; + #[test] + fn selected_output_is_excluded_but_sources_and_unselected_siblings_are_not() { + let fixture = fixture(); + let root = fixture.path().canonicalize().unwrap(); + let output = root.join("crates/edgezero-test-harness/results/run-1"); + fs::create_dir_all(&output).unwrap(); + let _selection = OutputDirectory::enter(&output).unwrap(); + let first = identity(&root); + for name in ["events.jsonl", "build/artifact.wasm", "component/log.txt"] { + write(&output, name, b"output-only mutation"); + assert_eq!(identity(&root), first, "selected output {name}"); + } + for name in [ + "crates/edgezero-test-harness/results/run-10/events.jsonl", + "crates/edgezero-test-harness/results/run-2/artifact.wasm", + "crates/edgezero-core/src/untracked.rs", + ] { + write(&root, name, b"unselected source input"); + assert_ne!(identity(&root), first, "unselected {name}"); + fs::remove_file(root.join(name)).unwrap(); + assert_eq!(identity(&root), first); + } + write(&root, FILES[4], b"dirty tracked source"); + assert_ne!(identity(&root), first); + } + + #[test] + fn selected_output_scope_restores_after_nesting_panic_and_thread_switch() { + let fixture = fixture(); + let root = fixture.path().canonicalize().unwrap(); + let outer = root.join("crates/results/outer"); + let inner = root.join("crates/results/inner"); + write(&outer, "events.jsonl", b"outer evidence"); + write(&inner, "events.jsonl", b"inner evidence"); + let unselected = identity(&root); + { + let _outer = OutputDirectory::enter(&outer).unwrap(); + let selected = identity(&root); + assert_ne!(selected, unselected); + let panic = std::panic::catch_unwind(|| { + let _inner = OutputDirectory::enter(&inner).unwrap(); + assert_ne!(identity(&root), selected); + panic!("controlled output-scope unwind"); + }); + assert!(panic.is_err()); + assert_eq!(identity(&root), selected); + let other_root = root.clone(); + assert_eq!( + std::thread::spawn(move || identity(&other_root)) + .join() + .unwrap(), + unselected + ); + } + assert_eq!(identity(&root), unselected); + } + #[cfg(unix)] #[test] fn explicit_cargo_config_symlinks_hash_their_regular_target_and_fail_closed() { diff --git a/docs/audits/2026-09-29-flate-decoder-memory-accounting.md b/docs/audits/2026-09-29-flate-decoder-memory-accounting.md index 9dca951c5..f20a334c7 100644 --- a/docs/audits/2026-09-29-flate-decoder-memory-accounting.md +++ b/docs/audits/2026-09-29-flate-decoder-memory-accounting.md @@ -17,12 +17,12 @@ decoder contracts share one metadata snapshot per workspace; audited values are ## Charge -The pinned `miniz_oxide` state reserves a 32 KiB sliding window and a 64 KiB -inflate state. The codec wrapper reserve is 4 KiB and the shared EdgeZero -stream output buffer is 8 KiB. The measured source subtotal is therefore -73,728 bytes before allocator metadata, fragmentation, task stacks, and host -buffers. `FLATE_DECODER_FIXED_CHARGE_BYTES` is pinned to 1 MiB, giving more -than 14x headroom over that subtotal while keeping the public policy uniform +The 64 KiB reserve for the pinned `miniz_oxide` inflate state includes its +embedded 32 KiB sliding window. The codec wrapper reserve is 4 KiB and the shared +EdgeZero stream output buffer is 8 KiB. The reserved source subtotal is therefore +77,824 bytes before allocator metadata, fragmentation, task stacks, and host +buffers. `FLATE_DECODER_FIXED_CHARGE_BYTES` is pinned to 1 MiB, giving approximately +13.47x headroom over that subtotal while keeping the public policy uniform for Brotli, gzip, and deflate. The charge is a conservative guest-visible policy reservation, not a claim diff --git a/docs/guide/capabilities.md b/docs/guide/capabilities.md index 0ca781b4c..3059d5981 100644 --- a/docs/guide/capabilities.md +++ b/docs/guide/capabilities.md @@ -413,11 +413,13 @@ capabilities above. ⁴ Fastly dispatches slots sequentially, then cooperatively services pending heads and demanded bodies within that operation. Each raw body read requires fresh matching timed readiness and reads at most 16 KiB; rotating slot service prevents a continuously-ready body from monopolizing -the driver. An occupied result slot backpressures only its own exchange. Cached SDK Send heads -retain their opaque cache state and use nonblocking polling with one shared positive 1 ms pulse. -That pulse has a CPU cost during a long pending cached head. It is shared across slots, not one -timer per request. Backoff would change ready-observation latency; replacing the SDK head would -change cache ownership. Neither change is made without a separate measured policy decision. +the driver. An occupied result slot backpressures only its own exchange. Buffered SDK Send and +batch response heads are opaque under both `PlatformDefault` and `Bypass`; their nonblocking +polling uses one shared positive 1 ms pulse. This is not limited to cached requests. Each turn +polls pending head slots, so guest CPU cost grows with their number and wait duration. The pulse +is shared across slots, not one timer per request. Backoff would change ready-observation +latency; replacing the SDK head could change cache ownership. Neither change is made without +a separate measured policy decision. Native Image Optimizer dispatch remains synchronous. Cold backend registration can still delay dispatch; synchronous provider work and SDK cleanup remain non-preemptible. Progress is cooperative, not autonomous during application CPU work, and does not establish hosted isolation. @@ -445,6 +447,13 @@ keep the response-egress cells BestEffort. compilation prove the coordinator, but a live Spin component test has not yet established the generated production composition. Host teardown and network completion also lack deployed proof. +For known-empty buffered DELETE/OPTIONS, EdgeZero omits synthetic `Content-Length: 0` +and supplies absent WASI content with clean trailers. The Spin 4.1 host may still choose +empty chunked framing (`0\r\n\r\n`). This is a provider exception to the empty-buffered-method +SHOULD in EZ-1.10, not a relaxation of its mandatory unchunked GET/HEAD behavior. Empty +buffered POST/PUT/PATCH retain their derived zero length; nonempty and streamed bodies +retain their existing preparation and limits. + ⁸ Spin cancellation is cooperative until host teardown is observable within a documented bound. Cloudflare wires one owned `AbortController` through fetch and streamed body consumption, but no deployed host-observed cancellation artifact currently proves a finite cancellation bound; diff --git a/docs/superpowers/plans/2026-09-15-reusable-app-lifecycle.md b/docs/superpowers/plans/2026-09-15-reusable-app-lifecycle.md index 064313266..8db3c1b10 100644 --- a/docs/superpowers/plans/2026-09-15-reusable-app-lifecycle.md +++ b/docs/superpowers/plans/2026-09-15-reusable-app-lifecycle.md @@ -137,8 +137,10 @@ let app = retained.state().expect("successful initialization"); `Hooks::configure` returns `Result<(), EdgeError>`; `App::build` installs and validates platform metadata. No partial app or initialization error is retained. -Custom callbacks decide whether a failure is recoverable; standard serving -propagates it and stops without another send. +Standard serving delivers application assembly failures through detached egress; +successful delivery completes the callback and the next request retries assembly. +Logging/setup failures and terminal-delivery errors still propagate. Custom +callbacks decide their own recoverable-error policy. - [x] **2.3 Preserve the degraded first logging snapshot.** Exercise production `setup_once` with an empty initial environment and later successful selector reads. Logging is not reconfigured after successful setup, while runtime/store resolution remains per request. The earlier private-helper test sketch is superseded. diff --git a/docs/superpowers/plans/2026-11-07-pr275-review-repairs.md b/docs/superpowers/plans/2026-11-07-pr275-review-repairs.md index b5860df73..f547a2e20 100644 --- a/docs/superpowers/plans/2026-11-07-pr275-review-repairs.md +++ b/docs/superpowers/plans/2026-11-07-pr275-review-repairs.md @@ -159,3 +159,139 @@ ceiling. Each production backend's Off-through-Trace filter matrix and all threshold, redaction and release assertions remain unchanged. This is test-only state isolation, not a production logging or timing-policy change. Retain the failed run separately and rerun the complete suite on the final clean commit. + +## Focused Review Closeout (2026-11-10) + +AG requested items 1 (CodeQL cleanup) and 2 (review closeout), including resolution +of issues already addressed. This checkpoint starts at `a7d7fd0f` and preserves +the architecture and outbound requirements above. Issue #458 stays separate. + +- [x] Replace the four hard-coded expected nonce arguments in startup-publication + fixtures with the nonce generated for each owned child launch. Retain wrong + nonce, PID, schema, byte-boundary, deadline and liveness controls; do not + suppress CodeQL or change production startup validation. +- [x] Correct current Fastly guidance and the changelog: buffered SDK Send and + batch heads use the shared positive 1 ms pulse under both PlatformDefault + and Bypass. Preserve scheduler timing, cache selection and native optimizer. +- [x] Verify Spin's empty buffered request framing at the SDK and existing wire + boundary before correcting unnecessary synthesized zero lengths. Preserve + empty POST/PUT/PATCH framing, actual nonempty lengths, GET/HEAD behavior, + limits, original deadlines and streamed bodies without prebuffering. +- [ ] Run focused regressions, all five root gates, the full prescribed adapter, + demo/generated-project suite, strict harness/provider lint and docs checks. + Verify the pushed-head CodeQL result separately from local test results. +- [ ] Push this checkpoint to PR #275 and reply in each affected original thread + with the exact fix and executed evidence. Under AG's explicit request, + resolve external threads only when the requested correction is verified + or the reviewer has explicitly accepted the retained policy. Record that + this maintainer-directed resolution is not independent approval. Own + amendment threads and unresolved policy/hosted questions stay open. + +No pin relaxation, alternate transport, backoff policy, generic body-error +reclassification, manifest-discovery policy change, hosted deployment, evidence +promotion, review dismissal or merge is authorized by this checkpoint. Further +source changes require fresh current-head validation and independent re-review. + +## Scoped Repairs (2026-11-11) + +AG approved cleanup followed by items 1-3 of the current closeout list. Reuse the +existing Rust harness, process supervisor, fixture logger and body preparation; +do not introduce another transport or compatibility API. Hosted qualification, +candidate freeze and review acceptance remain separate. + +- [x] Remove inactive generated output while preserving source changes, runtime + evidence and active worktrees/builds. +- [x] Fix CLI-only dependency-feature activation and retain an isolated check in + the existing CI job and prescribed suite. +- [x] Emit qualification lifecycle JSON through both logger filters without + enabling ordinary Info logging or wrapping the structured event. +- [x] Supervise progress fixture builds and Cargo metadata capture through the + existing process owner; prove direct-controller cancellation reaps children. +- [x] Exclude only the canonical selected evidence subtree from every fresh + build-identity capture; retain dirty/untracked source detection and scoped + restoration across nesting, unwinding and threads. +- [x] Reconcile decoder charge arithmetic, standard Fastly assembly-error retry, + the Axum full-suite selector and the current response-type path. +- [x] Complete the earlier nonce and Fastly disclosure changes, and verify Spin's + empty-method SDK projection and actual host framing without changing its + deadline, upload, ownership or body-suppression contracts. +- [x] Run focused regressions and the applicable Rust, harness, fixture and docs + gates. Record failures without treating supporting captures as qualification. + +### Focused Evidence + +The CLI-only check, real qualification logger, selected-output identity tests, +build/metadata cancellation tests and flate subtotal assertion each reproduced +their original failure before the fix. Direct-controller cancellation checks +Cargo absence and descendant socket closure before either safety cleanup. + +The 78 fixture-core tests pass. Spin's 23 SDK resource tests pass with Wasmtime +48.0.2, and the existing Spin outbound-wire suite passes with 166 passing records +and no failed records. The capture is +`crates/edgezero-test-harness/fixtures/reusable-app/.runs/18e70ebb3cd1b6d0-e2a5-0/`; +its records remain `qualification: false`. Send and Begin preserve zero-length +POST while DELETE/OPTIONS have no Content-Length and exactly the host's empty +chunk terminator. GET/HEAD requirements remain strict. The resource receipt is +added before the WASI response freezes its fields and rejects duplicate markers. + +Retain the failed baseline harness run and initial failed wire capture. The +baseline source-verifier assertion passed on its exact rerun; no cause is claimed. +The first current full harness run passed 659 tests but detected the entrypoint's +changed control-flow fingerprint. Review confirmed that its sole change installs +the selected-output scope. Only that recorded fingerprint changed; the full +rerun passes all 660 tests. No selector, controller, result or qualification +predicate is relaxed. + +Two read-only verification agents rechecked the process/logging/identity and Spin +resource/framing changes. Their follow-up reviews found no remaining issues after +the version-probe ownership, pre-cleanup observation and immutable-header fixes. +### Final Local Validation + +- All five primary Rust gates pass on Rust 1.98.1. The workspace run reports 2,700 + passing tests across 33 binaries, no failures and one ignored generated-project + build. Root, harness and fixture formatting checks pass. +- Harness: 660 passed, three ignored helper entrypoints. Fixture core with + qualification enabled: 78 passed. Spin SDK resources: 23 passed. The final + Spin outbound-wire capture has 166 passing records and no failures. +- Strict Clippy passes for the root workspace, harness, qualification fixture and + Spin WASM all-targets build. Rename the new test's shadowed bindings rather than + suppressing restriction lints; retain the initial failing lint/format logs. +- CI-tooling tests: 38 passed. Outbound legacy-API and docs contracts pass, as do + docs formatting, lint and VitePress build. The documented Axum command resolves + all 43 expected sentinels; this lookup is not a TCP execution claim. + +The complete four-adapter/demo/generated-project prescribed suite was not rerun +in this scoped checkpoint. Publication, remote CodeQL/check verification, +per-thread replies/resolution, independent acceptance and hosted qualification +remain outstanding. No commit or push is included in the items 1-3 completion. + +## Publication Followup (2026-11-11) + +AG subsequently requested publishing this checkpoint and cleaning disposable +build output afterward. The remote branch had independently advanced to +`410a16238b7cb740275ad69b9af628cd52c57bdc` (received-head preparation). Retain +that commit by fast-forwarding before adding the scoped repairs; do not rewrite +or discard it. The earlier green counts above describe the repair tree before +this independent addition, not a full-suite pass for the combined published head. + +The combined-tree publication attempt passed root formatting and the Spin WASM +compilation check. Workspace tests, strict workspace Clippy, feature compilation +and the harness rerun exited 101 with actual compiler/linker failures reporting +`No space left on device` (errno 28). The first Node run exited 1 without usable +output; docs/CLI checks could not create their redirected logs. Do not present +those attempts as passing, infer a source regression, suppress checks or waive +the complete-suite/hosted gates. Retain the failed logs and use CI to verify the +published head before any readiness claim. + +After disk space recovered, repeat the interrupted checks without modifying +source, assertions or CI policy. The combined tree passes all five primary Rust +gates: 2,702 workspace tests across 34 binaries, strict workspace Clippy, native +feature compilation, Spin WASM compilation and root formatting. The harness +rerun reports `660 passed; 0 failed; 3 ignored`. The isolated CLI-only check, +all 38 tooling tests and outbound docs contract also pass on retry. These are +successful reruns, not a dismissal or relabeling of the failed attempts. The +complete four-adapter/demo/generated-project and hosted gates remain separate. + +Inactive fixture build output was removed to recover working space. Only this +task's disposable validation/build outputs may be removed after remote-head +verification; preserve source, the active worktrees and runtime/test evidence. diff --git a/docs/superpowers/specs/2026-09-15-reusable-app-lifecycle-design.md b/docs/superpowers/specs/2026-09-15-reusable-app-lifecycle-design.md index 6cfae2d0a..11101de4e 100644 --- a/docs/superpowers/specs/2026-09-15-reusable-app-lifecycle-design.md +++ b/docs/superpowers/specs/2026-09-15-reusable-app-lifecycle-design.md @@ -140,7 +140,7 @@ pub fn serve_app_with_hooks( where A: Hooks, Prepare: FnMut(&mut fastly::Request, &mut Extensions), - Finalize: FnMut(&mut edgezero_core::Response) -> State; + Finalize: FnMut(&mut edgezero_core::http::Response) -> State; ``` `serve_app` delegates with empty preparation and finalization callbacks. Both helpers: @@ -164,11 +164,14 @@ Capture preparation and finalization callbacks in the serving closure and pass fresh mutable reborrows on every request. Do not move either callback out on the first invocation or retain request-owned values in its captures. -An initialization `Err` leaves `Sandbox` empty. Standard serving propagates that -error and terminates; custom callbacks may handle a recoverable failure and retry -on a later request. Configuration is fallible, and panics remain sandbox failures. -Partial global setup side effects are not rolled back, so custom retry policy must -make setup safe to repeat. +An application assembly `Err` leaves `Sandbox` empty. Standard serving delivers +the typed error through detached response egress. Successful error delivery lets +the callback finish normally and a later request retries assembly; only a +successful app is retained. Logging/setup failures and terminal-delivery errors +still propagate through the SDK serving result. Custom callbacks choose their +own recoverable-error policy. Configuration is fallible, and panics remain +sandbox failures. Partial global setup side effects are not rolled back, so +retryable setup must be safe to repeat. Example entry point after implementation: diff --git a/scripts/ci_tooling.test.mjs b/scripts/ci_tooling.test.mjs index 928e2a352..e8d6581fb 100644 --- a/scripts/ci_tooling.test.mjs +++ b/scripts/ci_tooling.test.mjs @@ -50,6 +50,12 @@ const adapters = tests.jobs["adapter-wasm-tests"]; const yamlContractName = "workflow YAML preserves trigger keys and scalar types"; +test("CLI-only compilation is isolated from adapter feature unification", () => { + const check = "cargo check --offline --locked -p edgezero-cli --lib --no-default-features --features cli"; + assert.ok(format.jobs.format.steps.some((step) => step.run?.includes(check))); + assert.ok(readFileSync(join(root, "scripts/run_tests.sh"), "utf8").includes(check)); +}); + test(yamlContractName, () => { assert.deepEqual(tests.on, { push: { branches: ["main"] }, diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh index 14272cd57..8631fd0cd 100755 --- a/scripts/run_tests.sh +++ b/scripts/run_tests.sh @@ -64,6 +64,7 @@ done section "Workspace Feature Compilation" run cargo check --workspace --all-targets --features "fastly cloudflare spin" +run cargo check --offline --locked -p edgezero-cli --lib --no-default-features --features cli section "Adapter Native Feature Matrices" for adapter in axum cloudflare fastly spin; do From 658f89d0083abb776f8553e92e2d1e7cbbf3efa5 Mon Sep 17 00:00:00 2001 From: Christian Date: Wed, 11 Nov 2026 21:24:48 -0600 Subject: [PATCH 3/8] Read complete byte-bounded CI wire evidence and preserve atomic receipts --- .../fixture-core/src/qualification/progress.rs | 13 ++++++++----- crates/edgezero-test-harness/src/runners/ci.rs | 16 ++++++++++++---- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs index 989a9e7fd..70bed34df 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs @@ -17,6 +17,7 @@ use futures::{ task::AtomicWaker, }; use serde_json::{Value, json}; +use std::io::Write as _; use std::sync::{ Arc, OnceLock, atomic::{AtomicBool, AtomicUsize, Ordering}, @@ -138,13 +139,15 @@ impl ResponseEgressObserver for FramingObserver { if report.framing_failures.application().is_some() || report.framing_failures.fallback().is_some() { - eprintln!( - "{}", - json!({"event":"framing-terminal", "application":report.framing_failures.application().map(|reason|format!("{reason:?}")), + let record = json!({"event":"framing-terminal", "application":report.framing_failures.application().map(|reason|format!("{reason:?}")), "fallback":report.framing_failures.fallback().map(|reason|format!("{reason:?}")), "outcome":format!("{:?}",report.outcome),"body_kind":format!("{:?}",report.body_kind), - "bytes_written":report.bytes_written,"disposition":report.fallback_disposition.map(|value|format!("{value:?}")),"qualification":false}) - ); + "bytes_written":report.bytes_written,"disposition":report.fallback_disposition.map(|value|format!("{value:?}")),"qualification":false}); + // One complete line prevents host logs from splitting JSON formatter writes. + let line = format!("{record}\n"); + std::io::stderr() + .write_all(line.as_bytes()) + .expect("should write framing receipt"); } } } diff --git a/crates/edgezero-test-harness/src/runners/ci.rs b/crates/edgezero-test-harness/src/runners/ci.rs index aea4e842a..5e703b5ba 100644 --- a/crates/edgezero-test-harness/src/runners/ci.rs +++ b/crates/edgezero-test-harness/src/runners/ci.rs @@ -33,7 +33,7 @@ pub(super) fn read_events(path: &Path) -> Result> { .lines() .map(serde_json::from_str) .collect::, _>>()?; - require(events.len() <= 512, "too many CI artifact records")?; + // Bound input bytes here; each suite validates its complete event schedule. Ok(events) } @@ -774,6 +774,15 @@ mod tests { } } + #[test] + fn persisted_artifacts_preserve_bounded_wire_records_beyond_512() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("events.jsonl"); + // The current complete Fastly wire capture contains 518 records. + fs::write(&file, "{}\n".repeat(518)).unwrap(); + assert_eq!(read_events(&file).unwrap().len(), 518); + } + #[test] fn persisted_artifacts_reject_empty_malformed_truncated_and_oversized_jsonl() { let directory = tempfile::tempdir().unwrap(); @@ -785,9 +794,8 @@ mod tests { } fs::write(&file, format!("{}\n", json!({"event":"pass"}))).unwrap(); assert_eq!(read_events(&file).unwrap().len(), 1); - fs::write(&file, "{}\n".repeat(513)).unwrap(); - assert!(read_events(&file).is_err()); fs::write(&file, vec![b' '; ARTIFACT_BYTES as usize + 1]).unwrap(); - assert!(read_events(&file).is_err()); + let error = read_events(&file).unwrap_err().to_string(); + assert!(error.contains("missing or oversized CI artifact")); } } From 14a6ca8bb5a5cbe055a1f725bdab8f42569a3bf0 Mon Sep 17 00:00:00 2001 From: Christian Date: Wed, 11 Nov 2026 22:28:31 -0600 Subject: [PATCH 4/8] Make retained callback-scope fixture independent of IO timing --- crates/edgezero-adapter-fastly/src/lifecycle.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/edgezero-adapter-fastly/src/lifecycle.rs b/crates/edgezero-adapter-fastly/src/lifecycle.rs index b09ee3c90..5d8f98c1c 100644 --- a/crates/edgezero-adapter-fastly/src/lifecycle.rs +++ b/crates/edgezero-adapter-fastly/src/lifecycle.rs @@ -443,7 +443,17 @@ mod tests { let OutboundBatchNext::Item(_) = block_on(batch.next()).unwrap() else { panic!("fresh scope"); }; - batch + // Both observed slots may already be complete after a loopback refusal. + // Retain unpolled work to test callback revocation independently of IO timing. + drop(batch); + client.start_batch_until( + vec![ + OutboundRequest::post("http://127.0.0.1:9/callback-scope") + .unwrap() + .body("pending"), + ], + Deadline::after(Duration::from_secs(1)), + ) }); previous = Some(batch); } From 9c7c2f0252deaacebc47a64b7507836a60bc1a56 Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 12 Nov 2026 13:11:33 -0600 Subject: [PATCH 5/8] Revert our three cutover additions to PR 275 Undo the changes from 14a6ca8bb5a5cbe055a1f725bdab8f42569a3bf0, 658f89d0083abb776f8553e92e2d1e7cbbf3efa5, and 410a16238b7cb740275ad69b9af628cd52c57bdc as one history-preserving revert. Preserve b97efec185abbaa901e633a980975c98ef2f6c3b and all existing commits. This is a local comparison baseline; Aram is handling the public cleanup. No remote branch update is part of this commit. The five required Rust gates pass. Broader checks retain a pre-existing parallel fixture logger failure and reproduce the restored Fastly framing-receipt issue. Neither is hidden by this cleanup. --- .../edgezero-adapter-fastly/src/lifecycle.rs | 12 +-- crates/edgezero-core/src/app.rs | 12 +-- crates/edgezero-core/src/router.rs | 36 +-------- .../tests/received_head_preparation.rs | 80 ------------------- .../src/qualification/progress.rs | 13 ++- .../edgezero-test-harness/src/runners/ci.rs | 16 +--- 6 files changed, 12 insertions(+), 157 deletions(-) delete mode 100644 crates/edgezero-core/tests/received_head_preparation.rs diff --git a/crates/edgezero-adapter-fastly/src/lifecycle.rs b/crates/edgezero-adapter-fastly/src/lifecycle.rs index 5d8f98c1c..b09ee3c90 100644 --- a/crates/edgezero-adapter-fastly/src/lifecycle.rs +++ b/crates/edgezero-adapter-fastly/src/lifecycle.rs @@ -443,17 +443,7 @@ mod tests { let OutboundBatchNext::Item(_) = block_on(batch.next()).unwrap() else { panic!("fresh scope"); }; - // Both observed slots may already be complete after a loopback refusal. - // Retain unpolled work to test callback revocation independently of IO timing. - drop(batch); - client.start_batch_until( - vec![ - OutboundRequest::post("http://127.0.0.1:9/callback-scope") - .unwrap() - .body("pending"), - ], - Deadline::after(Duration::from_secs(1)), - ) + batch }); previous = Some(batch); } diff --git a/crates/edgezero-core/src/app.rs b/crates/edgezero-core/src/app.rs index e42a62e45..606218d35 100644 --- a/crates/edgezero-core/src/app.rs +++ b/crates/edgezero-core/src/app.rs @@ -7,7 +7,7 @@ use crate::error::{ suppress_overflow_retry_after, }; use crate::http::header::CONTENT_TYPE; -use crate::http::{Extensions, HeaderMap, HeaderValue, Method, Request, Response, StatusCode}; +use crate::http::{HeaderMap, HeaderValue, Method, Request, Response, StatusCode}; use crate::ingress::{ AdmissionDecision, IngressAdmissionOutcome, IngressAdmissionPolicy, IngressBeginOutcome, IngressDispatchOutcome, IngressFraming, IngressHead, IngressHeadAccounting, IngressHeadLimits, @@ -409,16 +409,6 @@ impl App { self.platform } - /// Captures application-authenticated facts before a managed host sanitizes the head. - /// - /// The host must structurally validate the received head first. The router's - /// [`crate::router::RouterBuilder::received_head_preparer`] can retain facts but cannot mutate - /// headers, poll a body, choose a route or return a response at this stage. - #[inline] - pub fn prepare_received_head(&self, headers: &HeaderMap, extensions: &mut Extensions) { - self.router.prepare_received_head(headers, extensions); - } - fn render_error_response(&self, error: EdgeError) -> Response { let status = error.status(); let overflow_origin = error.request_body_overflow_origin(); diff --git a/crates/edgezero-core/src/router.rs b/crates/edgezero-core/src/router.rs index a33f99f05..518f8d153 100644 --- a/crates/edgezero-core/src/router.rs +++ b/crates/edgezero-core/src/router.rs @@ -10,7 +10,7 @@ use tower_service::Service; use crate::context::FallbackDrainOutcome; use crate::error::EdgeError; use crate::handler::{BoxHandler, IntoHandler, IntrospectionNeeds}; -use crate::http::{Extensions, HandlerFuture, HeaderMap, Method, Request, Response}; +use crate::http::{Extensions, HandlerFuture, Method, Request, Response}; use crate::ingress::{AdmittedIngress, IngressHeadLimits, validate_normalized_ingress_parts}; use crate::introspection::{ManifestJson, RouteTable}; use crate::middleware::{BoxMiddleware, Middleware, Next}; @@ -21,8 +21,6 @@ use crate::response::IntoResponse as _; /// Shared optional interception performed before router lookup and state injection. pub type BoxPreDispatchHook = Arc; -type ReceivedHeadPreparer = Arc; - /// Inspect or terminate an admitted request before handler dispatch and route middleware. /// /// Adapter admission may resolve route identity first. The hook cannot bypass admission, @@ -214,7 +212,6 @@ pub struct RouterBuilder { manifest_json: Option>, middlewares: Vec, pre_dispatch_hook: Option, - received_head_preparer: Option, route_info: Vec, routes: HashMap>, /// App state registered via [`RouterBuilder::with_state`], keyed by type. @@ -268,7 +265,6 @@ impl RouterBuilder { self.manifest_json, self.state_extensions, self.pre_dispatch_hook, - self.received_head_preparer, ) } @@ -362,22 +358,6 @@ impl RouterBuilder { self.route(path, Method::PUT, handler) } - /// Sets a body-blind preparation callback for structurally validated received heads. - /// - /// Managed hosts call it before stripping forwarding fields or provider credentials. - /// Retain only application-authenticated facts in extensions, never credentials or an - /// unchecked header copy. It cannot change headers, route, read a body or return a response. - /// Router clones share the callback. Setting it again replaces the previous callback. - #[must_use] - #[inline] - pub fn received_head_preparer(mut self, prepare: F) -> Self - where - F: Fn(&HeaderMap, &mut Extensions) + Send + Sync + 'static, - { - self.received_head_preparer = Some(Arc::new(prepare)); - self - } - #[must_use] #[inline] pub fn route(mut self, path: &str, method: Method, handler: H) -> Self @@ -440,7 +420,6 @@ struct RouterInner { manifest_json: Option>, middlewares: Vec, pre_dispatch_hook: Option, - received_head_preparer: Option, route_index: Arc<[RouteInfo]>, routes: HashMap>, state_extensions: Extensions, @@ -663,14 +642,12 @@ impl RouterService { manifest_json: Option>, state_extensions: Extensions, pre_dispatch_hook: Option, - received_head_preparer: Option, ) -> Self { Self { inner: Arc::new(RouterInner { manifest_json, middlewares, pre_dispatch_hook, - received_head_preparer, route_index, routes, state_extensions, @@ -690,17 +667,6 @@ impl RouterService { } } - /// Captures application-authenticated facts from a structurally validated head. - /// - /// Managed hosts call this before stripping forwarding fields or provider credentials. - /// Preparation cannot change headers, poll a body, bypass admission or produce a response. - #[inline] - pub fn prepare_received_head(&self, headers: &HeaderMap, extensions: &mut Extensions) { - if let Some(prepare) = &self.inner.received_head_preparer { - prepare(headers, extensions); - } - } - /// Resolves a route without invoking middleware, handlers, or request-body code. #[must_use] #[inline] diff --git a/crates/edgezero-core/tests/received_head_preparation.rs b/crates/edgezero-core/tests/received_head_preparation.rs deleted file mode 100644 index e69e6a6c3..000000000 --- a/crates/edgezero-core/tests/received_head_preparation.rs +++ /dev/null @@ -1,80 +0,0 @@ -#[cfg(test)] -mod tests { - use edgezero_core::app::App; - use edgezero_core::http::{Extensions, HeaderMap, HeaderValue}; - use edgezero_core::router::RouterService; - - #[derive(Clone, Debug, Eq, PartialEq)] - struct AuthenticatedAuthority(String); - - #[test] - fn absent_preparation_callback_leaves_extensions_unchanged() { - let app = App::new(RouterService::builder().build()); - let mut extensions = Extensions::new(); - extensions.insert(AuthenticatedAuthority("retained.example.com".to_owned())); - - app.prepare_received_head(&HeaderMap::new(), &mut extensions); - - assert_eq!( - extensions.get::(), - Some(&AuthenticatedAuthority("retained.example.com".to_owned())), - "the default should preserve existing extensions" - ); - } - - #[test] - fn received_head_preparation_retains_only_authenticated_fact_without_mutating_headers() { - let app = App::new( - RouterService::builder() - .received_head_preparer(|headers, extensions| { - if headers.get("x-fixture-auth") - == Some(&HeaderValue::from_static("fictional-secret")) - && let Some(authority) = headers - .get("x-forwarded-host") - .and_then(|value| value.to_str().ok()) - { - extensions.insert(AuthenticatedAuthority(authority.to_owned())); - } - }) - .build(), - ); - let mut headers = HeaderMap::new(); - headers.insert( - "x-fixture-auth", - HeaderValue::from_static("fictional-secret"), - ); - headers.insert( - "x-forwarded-host", - HeaderValue::from_static("publisher.example.com:8443"), - ); - let original = headers.clone(); - let mut extensions = Extensions::new(); - - app.prepare_received_head(&headers, &mut extensions); - - assert_eq!( - headers, original, - "preparation should not mutate received headers" - ); - assert_eq!( - extensions.get::(), - Some(&AuthenticatedAuthority( - "publisher.example.com:8443".to_owned() - )), - "preparation should retain the authenticated public authority" - ); - assert_eq!( - extensions.len(), - 1, - "preparation should retain only the public fact" - ); - - headers.remove("x-fixture-auth"); - let mut rejected = Extensions::new(); - app.prepare_received_head(&headers, &mut rejected); - assert!( - rejected.is_empty(), - "missing authentication should retain no fact" - ); - } -} diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs index 70bed34df..989a9e7fd 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs @@ -17,7 +17,6 @@ use futures::{ task::AtomicWaker, }; use serde_json::{Value, json}; -use std::io::Write as _; use std::sync::{ Arc, OnceLock, atomic::{AtomicBool, AtomicUsize, Ordering}, @@ -139,15 +138,13 @@ impl ResponseEgressObserver for FramingObserver { if report.framing_failures.application().is_some() || report.framing_failures.fallback().is_some() { - let record = json!({"event":"framing-terminal", "application":report.framing_failures.application().map(|reason|format!("{reason:?}")), + eprintln!( + "{}", + json!({"event":"framing-terminal", "application":report.framing_failures.application().map(|reason|format!("{reason:?}")), "fallback":report.framing_failures.fallback().map(|reason|format!("{reason:?}")), "outcome":format!("{:?}",report.outcome),"body_kind":format!("{:?}",report.body_kind), - "bytes_written":report.bytes_written,"disposition":report.fallback_disposition.map(|value|format!("{value:?}")),"qualification":false}); - // One complete line prevents host logs from splitting JSON formatter writes. - let line = format!("{record}\n"); - std::io::stderr() - .write_all(line.as_bytes()) - .expect("should write framing receipt"); + "bytes_written":report.bytes_written,"disposition":report.fallback_disposition.map(|value|format!("{value:?}")),"qualification":false}) + ); } } } diff --git a/crates/edgezero-test-harness/src/runners/ci.rs b/crates/edgezero-test-harness/src/runners/ci.rs index 5e703b5ba..aea4e842a 100644 --- a/crates/edgezero-test-harness/src/runners/ci.rs +++ b/crates/edgezero-test-harness/src/runners/ci.rs @@ -33,7 +33,7 @@ pub(super) fn read_events(path: &Path) -> Result> { .lines() .map(serde_json::from_str) .collect::, _>>()?; - // Bound input bytes here; each suite validates its complete event schedule. + require(events.len() <= 512, "too many CI artifact records")?; Ok(events) } @@ -774,15 +774,6 @@ mod tests { } } - #[test] - fn persisted_artifacts_preserve_bounded_wire_records_beyond_512() { - let directory = tempfile::tempdir().unwrap(); - let file = directory.path().join("events.jsonl"); - // The current complete Fastly wire capture contains 518 records. - fs::write(&file, "{}\n".repeat(518)).unwrap(); - assert_eq!(read_events(&file).unwrap().len(), 518); - } - #[test] fn persisted_artifacts_reject_empty_malformed_truncated_and_oversized_jsonl() { let directory = tempfile::tempdir().unwrap(); @@ -794,8 +785,9 @@ mod tests { } fs::write(&file, format!("{}\n", json!({"event":"pass"}))).unwrap(); assert_eq!(read_events(&file).unwrap().len(), 1); + fs::write(&file, "{}\n".repeat(513)).unwrap(); + assert!(read_events(&file).is_err()); fs::write(&file, vec![b' '; ARTIFACT_BYTES as usize + 1]).unwrap(); - let error = read_events(&file).unwrap_err().to_string(); - assert!(error.contains("missing or oversized CI artifact")); + assert!(read_events(&file).is_err()); } } From eb95665f7585497bd90be3bb5ef1d8a3deecc854 Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 12 Nov 2026 13:37:04 -0600 Subject: [PATCH 6/8] Capture authenticated head facts before transport sanitation Prepare this change on an owned local follow-up for review. The parent is a temporary local revert baseline; publication and reconciliation onto the actual author-cleaned head are separate steps. Original-commit: 410a16238b7cb740275ad69b9af628cd52c57bdc --- crates/edgezero-core/src/app.rs | 12 ++- crates/edgezero-core/src/router.rs | 36 ++++++++- .../tests/received_head_preparation.rs | 80 +++++++++++++++++++ 3 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 crates/edgezero-core/tests/received_head_preparation.rs diff --git a/crates/edgezero-core/src/app.rs b/crates/edgezero-core/src/app.rs index 606218d35..e42a62e45 100644 --- a/crates/edgezero-core/src/app.rs +++ b/crates/edgezero-core/src/app.rs @@ -7,7 +7,7 @@ use crate::error::{ suppress_overflow_retry_after, }; use crate::http::header::CONTENT_TYPE; -use crate::http::{HeaderMap, HeaderValue, Method, Request, Response, StatusCode}; +use crate::http::{Extensions, HeaderMap, HeaderValue, Method, Request, Response, StatusCode}; use crate::ingress::{ AdmissionDecision, IngressAdmissionOutcome, IngressAdmissionPolicy, IngressBeginOutcome, IngressDispatchOutcome, IngressFraming, IngressHead, IngressHeadAccounting, IngressHeadLimits, @@ -409,6 +409,16 @@ impl App { self.platform } + /// Captures application-authenticated facts before a managed host sanitizes the head. + /// + /// The host must structurally validate the received head first. The router's + /// [`crate::router::RouterBuilder::received_head_preparer`] can retain facts but cannot mutate + /// headers, poll a body, choose a route or return a response at this stage. + #[inline] + pub fn prepare_received_head(&self, headers: &HeaderMap, extensions: &mut Extensions) { + self.router.prepare_received_head(headers, extensions); + } + fn render_error_response(&self, error: EdgeError) -> Response { let status = error.status(); let overflow_origin = error.request_body_overflow_origin(); diff --git a/crates/edgezero-core/src/router.rs b/crates/edgezero-core/src/router.rs index 518f8d153..a33f99f05 100644 --- a/crates/edgezero-core/src/router.rs +++ b/crates/edgezero-core/src/router.rs @@ -10,7 +10,7 @@ use tower_service::Service; use crate::context::FallbackDrainOutcome; use crate::error::EdgeError; use crate::handler::{BoxHandler, IntoHandler, IntrospectionNeeds}; -use crate::http::{Extensions, HandlerFuture, Method, Request, Response}; +use crate::http::{Extensions, HandlerFuture, HeaderMap, Method, Request, Response}; use crate::ingress::{AdmittedIngress, IngressHeadLimits, validate_normalized_ingress_parts}; use crate::introspection::{ManifestJson, RouteTable}; use crate::middleware::{BoxMiddleware, Middleware, Next}; @@ -21,6 +21,8 @@ use crate::response::IntoResponse as _; /// Shared optional interception performed before router lookup and state injection. pub type BoxPreDispatchHook = Arc; +type ReceivedHeadPreparer = Arc; + /// Inspect or terminate an admitted request before handler dispatch and route middleware. /// /// Adapter admission may resolve route identity first. The hook cannot bypass admission, @@ -212,6 +214,7 @@ pub struct RouterBuilder { manifest_json: Option>, middlewares: Vec, pre_dispatch_hook: Option, + received_head_preparer: Option, route_info: Vec, routes: HashMap>, /// App state registered via [`RouterBuilder::with_state`], keyed by type. @@ -265,6 +268,7 @@ impl RouterBuilder { self.manifest_json, self.state_extensions, self.pre_dispatch_hook, + self.received_head_preparer, ) } @@ -358,6 +362,22 @@ impl RouterBuilder { self.route(path, Method::PUT, handler) } + /// Sets a body-blind preparation callback for structurally validated received heads. + /// + /// Managed hosts call it before stripping forwarding fields or provider credentials. + /// Retain only application-authenticated facts in extensions, never credentials or an + /// unchecked header copy. It cannot change headers, route, read a body or return a response. + /// Router clones share the callback. Setting it again replaces the previous callback. + #[must_use] + #[inline] + pub fn received_head_preparer(mut self, prepare: F) -> Self + where + F: Fn(&HeaderMap, &mut Extensions) + Send + Sync + 'static, + { + self.received_head_preparer = Some(Arc::new(prepare)); + self + } + #[must_use] #[inline] pub fn route(mut self, path: &str, method: Method, handler: H) -> Self @@ -420,6 +440,7 @@ struct RouterInner { manifest_json: Option>, middlewares: Vec, pre_dispatch_hook: Option, + received_head_preparer: Option, route_index: Arc<[RouteInfo]>, routes: HashMap>, state_extensions: Extensions, @@ -642,12 +663,14 @@ impl RouterService { manifest_json: Option>, state_extensions: Extensions, pre_dispatch_hook: Option, + received_head_preparer: Option, ) -> Self { Self { inner: Arc::new(RouterInner { manifest_json, middlewares, pre_dispatch_hook, + received_head_preparer, route_index, routes, state_extensions, @@ -667,6 +690,17 @@ impl RouterService { } } + /// Captures application-authenticated facts from a structurally validated head. + /// + /// Managed hosts call this before stripping forwarding fields or provider credentials. + /// Preparation cannot change headers, poll a body, bypass admission or produce a response. + #[inline] + pub fn prepare_received_head(&self, headers: &HeaderMap, extensions: &mut Extensions) { + if let Some(prepare) = &self.inner.received_head_preparer { + prepare(headers, extensions); + } + } + /// Resolves a route without invoking middleware, handlers, or request-body code. #[must_use] #[inline] diff --git a/crates/edgezero-core/tests/received_head_preparation.rs b/crates/edgezero-core/tests/received_head_preparation.rs new file mode 100644 index 000000000..e69e6a6c3 --- /dev/null +++ b/crates/edgezero-core/tests/received_head_preparation.rs @@ -0,0 +1,80 @@ +#[cfg(test)] +mod tests { + use edgezero_core::app::App; + use edgezero_core::http::{Extensions, HeaderMap, HeaderValue}; + use edgezero_core::router::RouterService; + + #[derive(Clone, Debug, Eq, PartialEq)] + struct AuthenticatedAuthority(String); + + #[test] + fn absent_preparation_callback_leaves_extensions_unchanged() { + let app = App::new(RouterService::builder().build()); + let mut extensions = Extensions::new(); + extensions.insert(AuthenticatedAuthority("retained.example.com".to_owned())); + + app.prepare_received_head(&HeaderMap::new(), &mut extensions); + + assert_eq!( + extensions.get::(), + Some(&AuthenticatedAuthority("retained.example.com".to_owned())), + "the default should preserve existing extensions" + ); + } + + #[test] + fn received_head_preparation_retains_only_authenticated_fact_without_mutating_headers() { + let app = App::new( + RouterService::builder() + .received_head_preparer(|headers, extensions| { + if headers.get("x-fixture-auth") + == Some(&HeaderValue::from_static("fictional-secret")) + && let Some(authority) = headers + .get("x-forwarded-host") + .and_then(|value| value.to_str().ok()) + { + extensions.insert(AuthenticatedAuthority(authority.to_owned())); + } + }) + .build(), + ); + let mut headers = HeaderMap::new(); + headers.insert( + "x-fixture-auth", + HeaderValue::from_static("fictional-secret"), + ); + headers.insert( + "x-forwarded-host", + HeaderValue::from_static("publisher.example.com:8443"), + ); + let original = headers.clone(); + let mut extensions = Extensions::new(); + + app.prepare_received_head(&headers, &mut extensions); + + assert_eq!( + headers, original, + "preparation should not mutate received headers" + ); + assert_eq!( + extensions.get::(), + Some(&AuthenticatedAuthority( + "publisher.example.com:8443".to_owned() + )), + "preparation should retain the authenticated public authority" + ); + assert_eq!( + extensions.len(), + 1, + "preparation should retain only the public fact" + ); + + headers.remove("x-fixture-auth"); + let mut rejected = Extensions::new(); + app.prepare_received_head(&headers, &mut rejected); + assert!( + rejected.is_empty(), + "missing authentication should retain no fact" + ); + } +} From 1ea46af3672537f84cff735984e398874b555b9d Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 12 Nov 2026 13:37:36 -0600 Subject: [PATCH 7/8] Read complete byte-bounded CI wire evidence and preserve atomic receipts Prepare this change on an owned local follow-up for review. The parent is a temporary local revert baseline; publication and reconciliation onto the actual author-cleaned head are separate steps. Original-commit: 658f89d0083abb776f8553e92e2d1e7cbbf3efa5 --- .../fixture-core/src/qualification/progress.rs | 13 ++++++++----- crates/edgezero-test-harness/src/runners/ci.rs | 16 ++++++++++++---- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs index 989a9e7fd..70bed34df 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-core/src/qualification/progress.rs @@ -17,6 +17,7 @@ use futures::{ task::AtomicWaker, }; use serde_json::{Value, json}; +use std::io::Write as _; use std::sync::{ Arc, OnceLock, atomic::{AtomicBool, AtomicUsize, Ordering}, @@ -138,13 +139,15 @@ impl ResponseEgressObserver for FramingObserver { if report.framing_failures.application().is_some() || report.framing_failures.fallback().is_some() { - eprintln!( - "{}", - json!({"event":"framing-terminal", "application":report.framing_failures.application().map(|reason|format!("{reason:?}")), + let record = json!({"event":"framing-terminal", "application":report.framing_failures.application().map(|reason|format!("{reason:?}")), "fallback":report.framing_failures.fallback().map(|reason|format!("{reason:?}")), "outcome":format!("{:?}",report.outcome),"body_kind":format!("{:?}",report.body_kind), - "bytes_written":report.bytes_written,"disposition":report.fallback_disposition.map(|value|format!("{value:?}")),"qualification":false}) - ); + "bytes_written":report.bytes_written,"disposition":report.fallback_disposition.map(|value|format!("{value:?}")),"qualification":false}); + // One complete line prevents host logs from splitting JSON formatter writes. + let line = format!("{record}\n"); + std::io::stderr() + .write_all(line.as_bytes()) + .expect("should write framing receipt"); } } } diff --git a/crates/edgezero-test-harness/src/runners/ci.rs b/crates/edgezero-test-harness/src/runners/ci.rs index aea4e842a..5e703b5ba 100644 --- a/crates/edgezero-test-harness/src/runners/ci.rs +++ b/crates/edgezero-test-harness/src/runners/ci.rs @@ -33,7 +33,7 @@ pub(super) fn read_events(path: &Path) -> Result> { .lines() .map(serde_json::from_str) .collect::, _>>()?; - require(events.len() <= 512, "too many CI artifact records")?; + // Bound input bytes here; each suite validates its complete event schedule. Ok(events) } @@ -774,6 +774,15 @@ mod tests { } } + #[test] + fn persisted_artifacts_preserve_bounded_wire_records_beyond_512() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("events.jsonl"); + // The current complete Fastly wire capture contains 518 records. + fs::write(&file, "{}\n".repeat(518)).unwrap(); + assert_eq!(read_events(&file).unwrap().len(), 518); + } + #[test] fn persisted_artifacts_reject_empty_malformed_truncated_and_oversized_jsonl() { let directory = tempfile::tempdir().unwrap(); @@ -785,9 +794,8 @@ mod tests { } fs::write(&file, format!("{}\n", json!({"event":"pass"}))).unwrap(); assert_eq!(read_events(&file).unwrap().len(), 1); - fs::write(&file, "{}\n".repeat(513)).unwrap(); - assert!(read_events(&file).is_err()); fs::write(&file, vec![b' '; ARTIFACT_BYTES as usize + 1]).unwrap(); - assert!(read_events(&file).is_err()); + let error = read_events(&file).unwrap_err().to_string(); + assert!(error.contains("missing or oversized CI artifact")); } } From e0f01bc08fe7bbac8a43c129c2b0d49fae035c73 Mon Sep 17 00:00:00 2001 From: Christian Date: Thu, 12 Nov 2026 13:37:54 -0600 Subject: [PATCH 8/8] Make retained callback-scope fixture independent of IO timing Prepare this change on an owned local follow-up for review. The parent is a temporary local revert baseline; publication and reconciliation onto the actual author-cleaned head are separate steps. Original-commit: 14a6ca8bb5a5cbe055a1f725bdab8f42569a3bf0 --- crates/edgezero-adapter-fastly/src/lifecycle.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/edgezero-adapter-fastly/src/lifecycle.rs b/crates/edgezero-adapter-fastly/src/lifecycle.rs index b09ee3c90..5d8f98c1c 100644 --- a/crates/edgezero-adapter-fastly/src/lifecycle.rs +++ b/crates/edgezero-adapter-fastly/src/lifecycle.rs @@ -443,7 +443,17 @@ mod tests { let OutboundBatchNext::Item(_) = block_on(batch.next()).unwrap() else { panic!("fresh scope"); }; - batch + // Both observed slots may already be complete after a loopback refusal. + // Retain unpolled work to test callback revocation independently of IO timing. + drop(batch); + client.start_batch_until( + vec![ + OutboundRequest::post("http://127.0.0.1:9/callback-scope") + .unwrap() + .body("pending"), + ], + Deadline::after(Duration::from_secs(1)), + ) }); previous = Some(batch); }