Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion crates/edgezero-core/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down
36 changes: 35 additions & 1 deletion crates/edgezero-core/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -21,6 +21,8 @@ use crate::response::IntoResponse as _;
/// Shared optional interception performed before router lookup and state injection.
pub type BoxPreDispatchHook = Arc<dyn PreDispatchHook>;

type ReceivedHeadPreparer = Arc<dyn Fn(&HeaderMap, &mut Extensions) + Send + Sync + 'static>;

/// Inspect or terminate an admitted request before handler dispatch and route middleware.
///
/// Adapter admission may resolve route identity first. The hook cannot bypass admission,
Expand Down Expand Up @@ -212,6 +214,7 @@ pub struct RouterBuilder {
manifest_json: Option<Arc<str>>,
middlewares: Vec<BoxMiddleware>,
pre_dispatch_hook: Option<BoxPreDispatchHook>,
received_head_preparer: Option<ReceivedHeadPreparer>,
route_info: Vec<RouteInfo>,
routes: HashMap<Method, PathRouter<RouteEntry>>,
/// App state registered via [`RouterBuilder::with_state`], keyed by type.
Expand Down Expand Up @@ -265,6 +268,7 @@ impl RouterBuilder {
self.manifest_json,
self.state_extensions,
self.pre_dispatch_hook,
self.received_head_preparer,
)
}

Expand Down Expand Up @@ -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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: no adapter calls prepare_received_head at this head, so a preparer registered here never runs on Fastly, Cloudflare, Spin or Axum. Further up the stack, only the Axum service wires it in (#409). Consider naming the host that invokes it, e.g. "The Axum managed host calls it…", or saying that adapters which don't sanitize forwarding fields never invoke it. That way an app on another adapter won't count on authenticated facts that never get filled in.

/// 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<F>(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<H>(mut self, path: &str, method: Method, handler: H) -> Self
Expand Down Expand Up @@ -420,6 +440,7 @@ struct RouterInner {
manifest_json: Option<Arc<str>>,
middlewares: Vec<BoxMiddleware>,
pre_dispatch_hook: Option<BoxPreDispatchHook>,
received_head_preparer: Option<ReceivedHeadPreparer>,
route_index: Arc<[RouteInfo]>,
routes: HashMap<Method, PathRouter<RouteEntry>>,
state_extensions: Extensions,
Expand Down Expand Up @@ -642,12 +663,14 @@ impl RouterService {
manifest_json: Option<Arc<str>>,
state_extensions: Extensions,
pre_dispatch_hook: Option<BoxPreDispatchHook>,
received_head_preparer: Option<ReceivedHeadPreparer>,
) -> Self {
Self {
inner: Arc::new(RouterInner {
manifest_json,
middlewares,
pre_dispatch_hook,
received_head_preparer,
route_index,
routes,
state_extensions,
Expand All @@ -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]
Expand Down
80 changes: 80 additions & 0 deletions crates/edgezero-core/tests/received_head_preparation.rs
Original file line number Diff line number Diff line change
@@ -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::<AuthenticatedAuthority>(),
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::<AuthenticatedAuthority>(),
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"
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}
}
Expand Down
6 changes: 5 additions & 1 deletion crates/edgezero-test-harness/src/runners/ci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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"));
}
}
Loading