diff --git a/crates/edgezero-core/src/app.rs b/crates/edgezero-core/src/app.rs index db9c7dda3..6fca1d087 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, @@ -411,6 +411,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" + ); + } +} 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 0db9c2a97..e021a6acf 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 @@ -151,7 +151,9 @@ impl ResponseEgressObserver for FramingObserver { "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}); - let _ = write_framing_receipt(&mut std::io::stderr().lock(), &receipt); + // One complete line prevents host logs from splitting JSON formatter writes. + write_framing_receipt(&mut std::io::stderr().lock(), &receipt) + .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 c1c272097..554d8eb84 100644 --- a/crates/edgezero-test-harness/src/runners/ci.rs +++ b/crates/edgezero-test-harness/src/runners/ci.rs @@ -784,6 +784,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let file = directory.path().join("events.jsonl"); let record = format!("{}\n", json!({"event":"wire-case", "status":"pass"})); + // The current complete Fastly wire capture contains 518 records. fs::write(&file, record.repeat(518)).unwrap(); assert_eq!( read_events(&file, WIRE_ARTIFACT_RECORDS).unwrap().len(), @@ -822,6 +823,9 @@ mod tests { assert!(read_events(&file, CI_ARTIFACT_RECORDS).is_err()); fs::write(&file, vec![b' '; ARTIFACT_BYTES as usize + 1]).unwrap(); assert!(read_events(&file, CI_ARTIFACT_RECORDS).is_err()); - assert!(read_events(&file, WIRE_ARTIFACT_RECORDS).is_err()); + let error = read_events(&file, WIRE_ARTIFACT_RECORDS) + .unwrap_err() + .to_string(); + assert!(error.contains("missing or oversized CI artifact")); } }