diff --git a/.claude/settings.json b/.claude/settings.json index 02b602d4..b7b0afdc 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -25,7 +25,7 @@ "Bash(git status:*)", "mcp__plugin_chrome-devtools-mcp_chrome-devtools__new_page", "mcp__plugin_chrome-devtools-mcp_chrome-devtools__performance_stop_trace", - "mcp__plugin_chrome-devtools-mcp_chrome-devtools__evaluate_script", + "mcp__plugin_chrome-devtools-mcp_chrome-devtools__evaluate_script" ] }, "enabledPlugins": { diff --git a/Cargo.lock b/Cargo.lock index 942d5f64..55289366 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -750,7 +750,7 @@ dependencies = [ [[package]] name = "edgezero-adapter-fastly" version = "0.1.0" -source = "git+https://github.com/stackpop/edgezero?rev=170b74b#170b74bd2c9933b7d561f7ccdb67c53b239e9527" +source = "git+https://github.com/stackpop/edgezero?rev=38198f9839b70aef03ab971ae5876982773fc2a1#38198f9839b70aef03ab971ae5876982773fc2a1" dependencies = [ "anyhow", "async-stream", @@ -771,7 +771,7 @@ dependencies = [ [[package]] name = "edgezero-core" version = "0.1.0" -source = "git+https://github.com/stackpop/edgezero?rev=170b74b#170b74bd2c9933b7d561f7ccdb67c53b239e9527" +source = "git+https://github.com/stackpop/edgezero?rev=38198f9839b70aef03ab971ae5876982773fc2a1#38198f9839b70aef03ab971ae5876982773fc2a1" dependencies = [ "anyhow", "async-compression", @@ -799,7 +799,7 @@ dependencies = [ [[package]] name = "edgezero-macros" version = "0.1.0" -source = "git+https://github.com/stackpop/edgezero?rev=170b74b#170b74bd2c9933b7d561f7ccdb67c53b239e9527" +source = "git+https://github.com/stackpop/edgezero?rev=38198f9839b70aef03ab971ae5876982773fc2a1#38198f9839b70aef03ab971ae5876982773fc2a1" dependencies = [ "log", "proc-macro2", diff --git a/Cargo.toml b/Cargo.toml index 9f2f4c67..05a0eaf7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,10 +56,10 @@ config = "0.15.19" cookie = "0.18.1" derive_more = { version = "2.0", features = ["display", "error"] } ed25519-dalek = { version = "2.2", features = ["rand_core"] } -edgezero-adapter-axum = { git = "https://github.com/stackpop/edgezero", rev = "170b74b", default-features = false } -edgezero-adapter-cloudflare = { git = "https://github.com/stackpop/edgezero", rev = "170b74b", default-features = false } -edgezero-adapter-fastly = { git = "https://github.com/stackpop/edgezero", rev = "170b74b", default-features = false } -edgezero-core = { git = "https://github.com/stackpop/edgezero", rev = "170b74b", default-features = false } +edgezero-adapter-axum = { git = "https://github.com/stackpop/edgezero", rev = "38198f9839b70aef03ab971ae5876982773fc2a1", default-features = false } +edgezero-adapter-cloudflare = { git = "https://github.com/stackpop/edgezero", rev = "38198f9839b70aef03ab971ae5876982773fc2a1", default-features = false } +edgezero-adapter-fastly = { git = "https://github.com/stackpop/edgezero", rev = "38198f9839b70aef03ab971ae5876982773fc2a1", default-features = false } +edgezero-core = { git = "https://github.com/stackpop/edgezero", rev = "38198f9839b70aef03ab971ae5876982773fc2a1", default-features = false } error-stack = "0.6" fastly = "0.11.12" fern = "0.7.1" @@ -83,7 +83,7 @@ sha2 = "0.10.9" subtle = "2.6" temp-env = "0.3.6" tokio = { version = "1.49", features = ["sync", "macros", "io-util", "rt", "time"] } -toml = "1.0" +toml = "1.1" trusted-server-core = { path = "crates/trusted-server-core" } url = "2.5.8" urlencoding = "2.1" diff --git a/crates/trusted-server-adapter-fastly/src/app.rs b/crates/trusted-server-adapter-fastly/src/app.rs new file mode 100644 index 00000000..2c7df2e1 --- /dev/null +++ b/crates/trusted-server-adapter-fastly/src/app.rs @@ -0,0 +1,757 @@ +//! Full `EdgeZero` application wiring for Trusted Server. +//! +//! Registers all routes from the legacy [`crate::route_request`] into a +//! [`RouterService`]. On successful startup, attaches [`FinalizeResponseMiddleware`] +//! (outermost) and [`AuthMiddleware`] (inner). When startup fails, +//! [`startup_error_router`] returns a bare router without middleware. +//! Builds the [`AppState`] once per Wasm instance. +//! +//! `EdgeZero`'s current Fastly request context exposes client IP but not TLS +//! protocol or cipher metadata. The `EdgeZero` path therefore preserves TLS +//! metadata as `None` until the upstream adapter exposes those fields. +//! +//! # Route inventory +//! +//! | Method | Path pattern | Handler | +//! |--------|-------------|---------| +//! | GET | `/.well-known/trusted-server.json` | [`handle_trusted_server_discovery`] | +//! | POST | `/verify-signature` | [`handle_verify_signature`] | +//! | POST | `/admin/keys/rotate` | [`handle_rotate_key`] | +//! | POST | `/admin/keys/deactivate` | [`handle_deactivate_key`] | +//! | POST | `/auction` | [`handle_auction`] | +//! | GET | `/first-party/proxy` | [`handle_first_party_proxy`] | +//! | GET | `/first-party/click` | [`handle_first_party_click`] | +//! | GET | `/first-party/sign` | [`handle_first_party_proxy_sign`] | +//! | POST | `/first-party/sign` | [`handle_first_party_proxy_sign`] | +//! | POST | `/first-party/proxy-rebuild` | [`handle_first_party_proxy_rebuild`] | +//! | GET | `/` and `/{*rest}` | tsjs (if `/static/tsjs=` prefix), integration proxy, or publisher fallback | +//! | POST, HEAD, OPTIONS, PUT, PATCH, DELETE | `/` and `/{*rest}` | integration proxy or publisher fallback | +//! | POST, HEAD, OPTIONS, PUT, PATCH, DELETE | named paths above | publisher fallback (legacy parity for non-primary methods) | +//! +//! > **Note:** Methods not in the list above (e.g. `TRACE`, `CONNECT`, WebDAV verbs) return a +//! > router-level 405. Legacy routing proxied *every* method through to the publisher origin. +//! > This is a known intentional restriction of the EdgeZero router; the entry-point +//! > `apply_finalize_headers` call in `main.rs` still adds TS headers to those 405 responses. +//! +//! # Startup error handling +//! +//! When [`build_state`] fails, [`startup_error_router`] returns a minimal router +//! that responds to all routes with the startup error. This router does **not** +//! attach middleware — startup errors are returned without geo or TS headers. + +use core::future::Future; +use std::sync::Arc; + +use edgezero_adapter_fastly::FastlyRequestContext; +use edgezero_core::app::Hooks; +use edgezero_core::context::RequestContext; +use edgezero_core::error::EdgeError; +use edgezero_core::http::{header, HandlerFuture, HeaderValue, Method, Request, Response}; +use edgezero_core::router::RouterService; +use error_stack::Report; +use trusted_server_core::auction::endpoints::handle_auction; +use trusted_server_core::auction::{build_orchestrator, AuctionOrchestrator}; +use trusted_server_core::error::{IntoHttpResponse as _, TrustedServerError}; +use trusted_server_core::integrations::IntegrationRegistry; +use trusted_server_core::platform::{ClientInfo, PlatformKvStore, RuntimeServices}; +use trusted_server_core::proxy::{ + handle_first_party_click, handle_first_party_proxy, handle_first_party_proxy_rebuild, + handle_first_party_proxy_sign, +}; +use trusted_server_core::publisher::{handle_publisher_request, handle_tsjs_dynamic}; +use trusted_server_core::request_signing::{ + handle_deactivate_key, handle_rotate_key, handle_trusted_server_discovery, + handle_verify_signature, +}; +use trusted_server_core::settings::Settings; +use trusted_server_core::settings_data::get_settings; + +use crate::middleware::{AuthMiddleware, FinalizeResponseMiddleware}; +use crate::platform::{ + open_kv_store, FastlyPlatformBackend, FastlyPlatformConfigStore, FastlyPlatformGeo, + FastlyPlatformHttpClient, FastlyPlatformSecretStore, UnavailableKvStore, +}; + +// --------------------------------------------------------------------------- +// AppState +// --------------------------------------------------------------------------- + +/// Application state built once per Wasm instance and shared for its lifetime. +/// +/// In Fastly Compute each request spawns a new Wasm instance, so this struct is +/// effectively per-request. It holds pre-parsed settings and all service handles. +pub(crate) struct AppState { + pub(crate) settings: Arc, + pub(crate) orchestrator: Arc, + pub(crate) registry: Arc, + pub(crate) kv_store: Arc, +} + +/// Build the application state, loading settings and constructing all per-application components. +/// +/// # Errors +/// +/// Returns an error when settings, the auction orchestrator, or the integration +/// registry fail to initialise. +pub(crate) fn build_state() -> Result, Report> { + let settings = get_settings()?; + + let orchestrator = build_orchestrator(&settings)?; + + let registry = IntegrationRegistry::new(&settings)?; + + let kv_store = Arc::new(UnavailableKvStore) as Arc; + + Ok(Arc::new(AppState { + settings: Arc::new(settings), + orchestrator: Arc::new(orchestrator), + registry: Arc::new(registry), + kv_store, + })) +} + +/// Resolves per-request consent KV store services for routes that read consent data. +/// +/// When `settings.consent.consent_store` is configured and the named KV store cannot +/// be opened, returns `Err` so the caller can respond with 503 (fail-closed). This +/// matches the legacy `route_request` behavior where a misconfigured consent store +/// makes consent-dependent routes unavailable rather than proceeding without consent. +/// +/// # Errors +/// +/// Returns an error when the configured consent store cannot be opened. +pub(crate) fn runtime_services_for_consent_route( + settings: &Settings, + runtime_services: &RuntimeServices, +) -> Result> { + let Some(store_name) = settings.consent.consent_store.as_deref() else { + return Ok(runtime_services.clone()); + }; + + open_kv_store(store_name) + .map(|store| runtime_services.clone().with_kv_store(store)) + .map_err(|e| { + Report::new(TrustedServerError::KvStore { + store_name: store_name.to_string(), + message: e.to_string(), + }) + }) +} + +// --------------------------------------------------------------------------- +// Per-request RuntimeServices +// --------------------------------------------------------------------------- + +/// Construct per-request [`RuntimeServices`] from the `EdgeZero` request context. +/// +/// Extracts the client IP address from the [`FastlyRequestContext`] extension +/// inserted by `edgezero_adapter_fastly::dispatch`. TLS metadata is not +/// available through the `EdgeZero` context so those fields are left empty. +fn build_per_request_services(state: &AppState, ctx: &RequestContext) -> RuntimeServices { + let client_ip = FastlyRequestContext::get(ctx.request()).and_then(|c| c.client_ip); + + RuntimeServices::builder() + .config_store(Arc::new(FastlyPlatformConfigStore)) + .secret_store(Arc::new(FastlyPlatformSecretStore)) + .kv_store(Arc::clone(&state.kv_store)) + .backend(Arc::new(FastlyPlatformBackend)) + .http_client(Arc::new(FastlyPlatformHttpClient)) + .geo(Arc::new(FastlyPlatformGeo)) + .client_info(ClientInfo { + client_ip, + tls_protocol: None, + tls_cipher: None, + }) + .build() +} + +fn publisher_fallback_methods() -> [Method; 7] { + [ + Method::GET, + Method::POST, + Method::HEAD, + Method::OPTIONS, + Method::PUT, + Method::PATCH, + Method::DELETE, + ] +} + +fn uses_dynamic_tsjs_fallback(method: &Method, path: &str) -> bool { + *method == Method::GET && path.starts_with("/static/tsjs=") +} + +async fn execute_handler( + state: Arc, + ctx: RequestContext, + handler: F, +) -> Result +where + F: FnOnce(Arc, RuntimeServices, Request) -> Fut, + Fut: Future>>, +{ + let services = build_per_request_services(&state, &ctx); + let req = ctx.into_request(); + + Ok(handler(state, services, req) + .await + .unwrap_or_else(|e| http_error(&e))) +} + +async fn dispatch_fallback( + state: &AppState, + services: &RuntimeServices, + req: Request, +) -> Result> { + let path = req.uri().path().to_string(); + let method = req.method().clone(); + + if uses_dynamic_tsjs_fallback(&method, &path) { + return handle_tsjs_dynamic(&req, &state.registry); + } + + if state.registry.has_route(&method, &path) { + return state + .registry + .handle_proxy(&method, &path, &state.settings, services, req) + .await + .unwrap_or_else(|| { + Err(Report::new(TrustedServerError::BadRequest { + message: format!("Unknown integration route: {path}"), + })) + }); + } + + handle_publisher_request(&state.settings, &state.registry, services, req) + .await + .and_then(|pub_response| { + crate::resolve_publisher_response_buffered( + pub_response, + &state.settings, + &state.registry, + ) + }) +} + +// --------------------------------------------------------------------------- +// Error helper +// --------------------------------------------------------------------------- + +/// Convert a [`Report`] into an HTTP [`Response`], +/// mirroring [`crate::http_error_response`] exactly. +/// +/// The near-identical function in `main.rs` is intentional: the legacy path +/// uses fastly HTTP types while this path uses `edgezero_core` types. The +/// duplication will be removed when `legacy_main` is deleted in PR 15. +pub(crate) fn http_error(report: &Report) -> Response { + let root_error = report.current_context(); + log::error!("Error occurred: {:?}", report); + + let body = edgezero_core::body::Body::from(format!("{}\n", root_error.user_message())); + let mut response = Response::new(body); + *response.status_mut() = root_error.status_code(); + response.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/plain; charset=utf-8"), + ); + response +} + +// --------------------------------------------------------------------------- +// Startup error fallback +// --------------------------------------------------------------------------- + +/// Returns a [`RouterService`] that responds to every registered route with the startup error. +/// +/// Called when [`build_state`] fails so that request handling degrades to a +/// structured HTTP error response rather than an unrecoverable panic. +fn startup_error_router(e: &Report) -> RouterService { + let message = Arc::new(format!("{}\n", e.current_context().user_message())); + let status = e.current_context().status_code(); + + let make = move |msg: Arc| { + move |_ctx: RequestContext| { + let body = edgezero_core::body::Body::from((*msg).clone()); + let mut resp = Response::new(body); + *resp.status_mut() = status; + resp.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/plain; charset=utf-8"), + ); + async move { Ok::(resp) } + } + }; + + let mut router = RouterService::builder(); + for method in publisher_fallback_methods() { + router = router.route("/", method.clone(), make(Arc::clone(&message))); + router = router.route("/{*rest}", method, make(Arc::clone(&message))); + } + router.build() +} + +// --------------------------------------------------------------------------- +// Route registration +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy)] +enum NamedRouteHandler { + TrustedServerDiscovery, + VerifySignature, + RotateKey, + DeactivateKey, + Auction, + FirstPartyProxy, + FirstPartyClick, + FirstPartySign, + FirstPartyProxyRebuild, +} + +struct NamedRoute { + path: &'static str, + primary_methods: &'static [Method], + handler: NamedRouteHandler, +} + +fn named_routes() -> [NamedRoute; 9] { + [ + NamedRoute { + path: "/.well-known/trusted-server.json", + primary_methods: &[Method::GET], + handler: NamedRouteHandler::TrustedServerDiscovery, + }, + NamedRoute { + path: "/verify-signature", + primary_methods: &[Method::POST], + handler: NamedRouteHandler::VerifySignature, + }, + NamedRoute { + path: "/admin/keys/rotate", + primary_methods: &[Method::POST], + handler: NamedRouteHandler::RotateKey, + }, + NamedRoute { + path: "/admin/keys/deactivate", + primary_methods: &[Method::POST], + handler: NamedRouteHandler::DeactivateKey, + }, + NamedRoute { + path: "/auction", + primary_methods: &[Method::POST], + handler: NamedRouteHandler::Auction, + }, + NamedRoute { + path: "/first-party/proxy", + primary_methods: &[Method::GET], + handler: NamedRouteHandler::FirstPartyProxy, + }, + NamedRoute { + path: "/first-party/click", + primary_methods: &[Method::GET], + handler: NamedRouteHandler::FirstPartyClick, + }, + NamedRoute { + path: "/first-party/sign", + primary_methods: &[Method::GET, Method::POST], + handler: NamedRouteHandler::FirstPartySign, + }, + NamedRoute { + path: "/first-party/proxy-rebuild", + primary_methods: &[Method::POST], + handler: NamedRouteHandler::FirstPartyProxyRebuild, + }, + ] +} + +fn named_route_handler( + state: Arc, + handler: NamedRouteHandler, +) -> impl Fn(RequestContext) -> HandlerFuture + Clone + Send + Sync + 'static { + move |ctx: RequestContext| { + let state = Arc::clone(&state); + Box::pin(execute_handler( + state, + ctx, + move |state, services, req| async move { + match handler { + NamedRouteHandler::TrustedServerDiscovery => { + handle_trusted_server_discovery(&state.settings, &services, req) + } + NamedRouteHandler::VerifySignature => { + handle_verify_signature(&state.settings, &services, req) + } + NamedRouteHandler::RotateKey => { + handle_rotate_key(&state.settings, &services, req) + } + NamedRouteHandler::DeactivateKey => { + handle_deactivate_key(&state.settings, &services, req) + } + NamedRouteHandler::Auction => { + match runtime_services_for_consent_route(&state.settings, &services) { + Ok(consent_services) => { + handle_auction( + &state.settings, + &state.orchestrator, + &consent_services, + req, + ) + .await + } + Err(e) => Err(e), + } + } + NamedRouteHandler::FirstPartyProxy => { + handle_first_party_proxy(&state.settings, &services, req).await + } + NamedRouteHandler::FirstPartyClick => { + handle_first_party_click(&state.settings, &services, req).await + } + NamedRouteHandler::FirstPartySign => { + handle_first_party_proxy_sign(&state.settings, &services, req).await + } + NamedRouteHandler::FirstPartyProxyRebuild => { + handle_first_party_proxy_rebuild(&state.settings, &services, req).await + } + } + }, + )) + } +} + +fn fallback_route_handler( + state: Arc, +) -> impl Fn(RequestContext) -> HandlerFuture + Clone + Send + Sync + 'static { + move |ctx: RequestContext| { + let state = Arc::clone(&state); + Box::pin(execute_handler( + state, + ctx, + |state, services, req| async move { + match runtime_services_for_consent_route(&state.settings, &services) { + Ok(consent_services) => dispatch_fallback(&state, &consent_services, req).await, + Err(e) => Err(e), + } + }, + )) + } +} + +// --------------------------------------------------------------------------- +// TrustedServerApp +// --------------------------------------------------------------------------- + +/// `EdgeZero` [`Hooks`] implementation for the Trusted Server application. +pub struct TrustedServerApp; + +impl TrustedServerApp { + fn routes_for_state(state: &Arc) -> RouterService { + let mut router = RouterService::builder() + .middleware(FinalizeResponseMiddleware::new( + Arc::clone(&state.settings), + Arc::new(FastlyPlatformGeo), + )) + .middleware(AuthMiddleware::new(Arc::clone(&state.settings))); + + let fallback_handler = fallback_route_handler(Arc::clone(state)); + + // matchit prefers exact path+method over a wildcard catch-all. Each + // named route is registered from this single table, then every + // non-primary publisher fallback method is registered from the same + // row. Adding a named route now requires editing only this table. + for route in named_routes() { + for method in route.primary_methods { + router = router.route( + route.path, + method.clone(), + named_route_handler(Arc::clone(state), route.handler), + ); + } + + for method in publisher_fallback_methods() { + if !route.primary_methods.contains(&method) { + router = router.route(route.path, method, fallback_handler.clone()); + } + } + } + + // matchit's `/{*rest}` does not match the bare root `/` — register + // explicit root routes so `/` reaches the publisher fallback too. + for method in publisher_fallback_methods() { + router = router.route("/", method.clone(), fallback_handler.clone()); + router = router.route("/{*rest}", method, fallback_handler.clone()); + } + + router.build() + } +} + +impl Hooks for TrustedServerApp { + fn name() -> &'static str { + "TrustedServer" + } + + fn routes() -> RouterService { + let state = match build_state() { + Ok(s) => s, + Err(ref e) => { + log::error!("failed to build application state: {:?}", e); + return startup_error_router(e); + } + }; + + Self::routes_for_state(&state) + } +} + +#[cfg(test)] +mod tests { + use super::{startup_error_router, AppState, TrustedServerApp}; + + use std::sync::Arc; + + use edgezero_core::app::Hooks as _; + use edgezero_core::body::Body; + use edgezero_core::http::{header, request_builder, Method, StatusCode}; + use error_stack::Report; + use futures::executor::block_on; + use serde_json::json; + use trusted_server_core::auction::build_orchestrator; + use trusted_server_core::constants::HEADER_X_GEO_INFO_AVAILABLE; + use trusted_server_core::error::TrustedServerError; + use trusted_server_core::integrations::IntegrationRegistry; + use trusted_server_core::platform::PlatformKvStore; + use trusted_server_core::settings::Settings; + + fn settings_with_missing_consent_store() -> Settings { + Settings::from_toml( + r#" + [[handlers]] + path = "^/admin" + username = "admin" + password = "admin-pass" + + [publisher] + domain = "test-publisher.com" + cookie_domain = ".test-publisher.com" + origin_url = "https://origin.test-publisher.com" + proxy_secret = "unit-test-proxy-secret" + + [edge_cookie] + secret_key = "test-secret-key" + + [request_signing] + enabled = false + config_store_id = "test-config-store-id" + secret_store_id = "test-secret-store-id" + + [consent] + consent_store = "missing-consent-store" + + [integrations.prebid] + enabled = true + server_url = "https://test-prebid.com/openrtb2/auction" + + [auction] + enabled = true + providers = ["prebid"] + timeout_ms = 2000 + "#, + ) + .expect("should parse EdgeZero app test settings") + } + + fn app_state_for_settings(settings: Settings) -> Arc { + let orchestrator = + build_orchestrator(&settings).expect("should build auction orchestrator"); + let registry = IntegrationRegistry::new(&settings).expect("should create registry"); + let kv_store = Arc::new(crate::platform::UnavailableKvStore) as Arc; + + Arc::new(AppState { + settings: Arc::new(settings), + orchestrator: Arc::new(orchestrator), + registry: Arc::new(registry), + kv_store, + }) + } + + fn empty_request(method: Method, uri: &str) -> edgezero_core::http::Request { + request_builder() + .method(method) + .uri(uri) + .body(Body::empty()) + .expect("should build request") + } + + #[test] + fn startup_error_router_handles_head_and_options() { + let report = Report::new(TrustedServerError::BadRequest { + message: "startup failed".to_string(), + }); + let router = startup_error_router(&report); + + let head_response = block_on(router.oneshot(empty_request(Method::HEAD, "/"))); + let options_response = block_on(router.oneshot(empty_request(Method::OPTIONS, "/any"))); + + assert_eq!( + head_response.status(), + StatusCode::BAD_REQUEST, + "HEAD should use the degraded startup-error response" + ); + assert_eq!( + options_response.status(), + StatusCode::BAD_REQUEST, + "OPTIONS should use the degraded startup-error response" + ); + assert_eq!( + head_response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()), + Some("text/plain; charset=utf-8"), + "startup errors should stay plain-text for HEAD requests" + ); + assert_eq!( + options_response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()), + Some("text/plain; charset=utf-8"), + "startup errors should stay plain-text for OPTIONS requests" + ); + } + + #[test] + fn dynamic_tsjs_fallback_is_get_only() { + assert!( + super::uses_dynamic_tsjs_fallback(&Method::GET, "/static/tsjs=tsjs-unified.js"), + "GET should use the dynamic tsjs shortcut" + ); + assert!( + !super::uses_dynamic_tsjs_fallback(&Method::HEAD, "/static/tsjs=tsjs-unified.js"), + "HEAD should fall through to the publisher/integration fallback" + ); + assert!( + !super::uses_dynamic_tsjs_fallback(&Method::OPTIONS, "/static/tsjs=tsjs-unified.js"), + "OPTIONS should fall through to the publisher/integration fallback" + ); + } + + // --------------------------------------------------------------------------- + // Full EdgeZero dispatch-path tests + // --------------------------------------------------------------------------- + + #[test] + fn dispatch_auth_rejected_401_carries_finalize_headers() { + // Verifies FinalizeResponseMiddleware is outermost: an auth-rejected 401 + // must still carry standard TS headers before reaching the client. + // + // The embedded trusted-server.toml protects `^/admin` with basic-auth. + // Sending the request without an Authorization header causes AuthMiddleware + // to short-circuit with a 401, which then bubbles through + // FinalizeResponseMiddleware for header injection. + // + // This is safe to run without Viceroy: enforce_basic_auth is pure Rust + // (reads settings + request headers only) and FastlyPlatformGeo.lookup(None) + // short-circuits without calling any Fastly ABI. + let router = TrustedServerApp::routes(); + let req = request_builder() + .method(Method::POST) + .uri("/admin/keys/rotate") + .body(Body::empty()) + .expect("should build test request"); + + let response = block_on(router.oneshot(req)); + + assert_eq!( + response.status(), + StatusCode::UNAUTHORIZED, + "request without credentials should be rejected" + ); + assert_eq!( + response + .headers() + .get(HEADER_X_GEO_INFO_AVAILABLE) + .and_then(|v| v.to_str().ok()), + Some("false"), + "FinalizeResponseMiddleware must run even for auth-rejected responses" + ); + } + + #[test] + fn dispatch_head_on_named_get_route_falls_through_to_publisher_fallback() { + // Regression guard: HEAD /first-party/proxy must reach the publisher + // fallback, not return a router-level 405. Legacy route_request proxies + // every (method, path) combination not matched by a specific arm through + // to the publisher origin. + // + // Without a live backend the publisher proxy errors (502/503), but the + // important invariant is that the status is NOT 405. + let router = TrustedServerApp::routes(); + let req = request_builder() + .method(Method::HEAD) + .uri("/first-party/proxy") + .body(Body::empty()) + .expect("should build HEAD request"); + + let response = block_on(router.oneshot(req)); + + assert_ne!( + response.status(), + StatusCode::METHOD_NOT_ALLOWED, + "HEAD on a named GET path should reach the publisher fallback, not return 405" + ); + } + + #[test] + fn dispatch_auction_with_missing_consent_store_returns_503() { + let state = app_state_for_settings(settings_with_missing_consent_store()); + let router = TrustedServerApp::routes_for_state(&state); + let body = json!({ "adUnits": [] }).to_string(); + let req = request_builder() + .method(Method::POST) + .uri("/auction") + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body)) + .expect("should build auction request"); + + let response = block_on(router.oneshot(req)); + + assert_eq!( + response.status(), + StatusCode::SERVICE_UNAVAILABLE, + "auction route should fail closed when configured consent store cannot be opened" + ); + } + + #[test] + fn dispatch_unregistered_method_returns_405_at_router_level() { + // Documents the known router-level behavior for verbs outside the + // publisher_fallback_methods() list (e.g. TRACE, CONNECT): the RouterService + // returns 405 before the middleware chain runs, so FinalizeResponseMiddleware + // does not inject TS headers at this layer. + // + // The full-system guarantee (TS headers on ALL responses including these 405s) + // is maintained by the entry-point apply_finalize_headers call in main.rs. + let router = TrustedServerApp::routes(); + let req = request_builder() + .method(Method::from_bytes(b"TRACE").expect("should parse TRACE")) + .uri("/") + .body(Body::empty()) + .expect("should build TRACE request"); + + let response = block_on(router.oneshot(req)); + + assert_eq!( + response.status(), + StatusCode::METHOD_NOT_ALLOWED, + "unregistered method should return 405 from the router layer" + ); + assert!( + response + .headers() + .get(HEADER_X_GEO_INFO_AVAILABLE) + .is_none(), + "router-level 405 bypasses FinalizeResponseMiddleware; main.rs entry-point covers this" + ); + } +} diff --git a/crates/trusted-server-adapter-fastly/src/main.rs b/crates/trusted-server-adapter-fastly/src/main.rs index d8b08e17..34c40c31 100644 --- a/crates/trusted-server-adapter-fastly/src/main.rs +++ b/crates/trusted-server-adapter-fastly/src/main.rs @@ -1,22 +1,25 @@ +use std::net::IpAddr; +use std::sync::Arc; + +use edgezero_adapter_fastly::FastlyConfigStore; +use edgezero_core::app::Hooks as _; use edgezero_core::body::Body as EdgeBody; +use edgezero_core::config_store::ConfigStoreHandle; use edgezero_core::http::{ - header, HeaderName, HeaderValue, Method, Request as HttpRequest, Response as HttpResponse, + header, HeaderValue, Method, Request as HttpRequest, Response as HttpResponse, }; use error_stack::Report; use fastly::http::Method as FastlyMethod; use fastly::{Request as FastlyRequest, Response as FastlyResponse}; use trusted_server_core::auction::endpoints::handle_auction; -use trusted_server_core::auction::{build_orchestrator, AuctionOrchestrator}; +use trusted_server_core::auction::AuctionOrchestrator; use trusted_server_core::auth::enforce_basic_auth; use trusted_server_core::compat; -use trusted_server_core::constants::{ - ENV_FASTLY_IS_STAGING, ENV_FASTLY_SERVICE_VERSION, HEADER_X_GEO_INFO_AVAILABLE, - HEADER_X_TS_ENV, HEADER_X_TS_VERSION, -}; use trusted_server_core::error::{IntoHttpResponse, TrustedServerError}; use trusted_server_core::geo::GeoInfo; use trusted_server_core::integrations::IntegrationRegistry; +use trusted_server_core::platform::PlatformGeo as _; use trusted_server_core::platform::RuntimeServices; use trusted_server_core::proxy::{ handle_first_party_click, handle_first_party_proxy, handle_first_party_proxy_rebuild, @@ -33,21 +36,27 @@ use trusted_server_core::request_signing::{ use trusted_server_core::settings::Settings; use trusted_server_core::settings_data::get_settings; +mod app; mod error; mod logging; mod management_api; +mod middleware; mod platform; #[cfg(test)] mod route_tests; +use crate::app::{build_state, runtime_services_for_consent_route, TrustedServerApp}; use crate::error::to_error_response; -use crate::logging::init_logger; -use crate::platform::{build_runtime_services, open_kv_store, UnavailableKvStore}; +use crate::middleware::{apply_finalize_headers, HEADER_X_TS_FINALIZED}; +use crate::platform::{build_runtime_services, FastlyPlatformGeo}; + +const TRUSTED_SERVER_CONFIG_STORE: &str = "trusted_server_config"; +const EDGEZERO_ENABLED_KEY: &str = "edgezero_enabled"; /// Result of routing a request, distinguishing buffered from streaming publisher responses. /// /// The streaming arm keeps the publisher body out of WASM heap until it is written directly -/// to the client via [`fastly::Response::stream_to_client`]. All other routes are buffered. +/// to the client via [`fastly::Response::stream_to_client`]. All other legacy routes are buffered. enum HandlerOutcome { Buffered(HttpResponse), Streaming { @@ -66,77 +75,204 @@ impl HandlerOutcome { } } +/// Returns `true` if the raw config-store value represents an enabled flag. +/// +/// Accepted values (after whitespace trimming): `"1"` or `"true"` in any ASCII case. +/// All other values, including the empty string, are treated as disabled. +fn parse_edgezero_flag(value: &str) -> bool { + let v = value.trim(); + v.eq_ignore_ascii_case("true") || v == "1" +} + +/// Opens the shared Fastly Config Store used by both the `EdgeZero` flag read and +/// `EdgeZero` dispatch metadata. +/// +/// # Errors +/// +/// Returns [`fastly::Error`] if the config store cannot be opened. +fn open_trusted_server_config_store() -> Result { + let store = FastlyConfigStore::try_open(TRUSTED_SERVER_CONFIG_STORE) + .map_err(|e| fastly::Error::msg(format!("failed to open config store: {e}")))?; + Ok(ConfigStoreHandle::new(Arc::new(store))) +} + +/// Reads the `edgezero_enabled` key from the prepared Fastly Config Store +/// handle. +/// +/// Returns `Err` on any key-read failure, so callers should use the legacy path +/// as the safe default. +/// +/// # Errors +/// +/// - [`fastly::Error`] if the key cannot be read. +fn is_edgezero_enabled(config_store: &ConfigStoreHandle) -> Result { + let value = config_store + .get(EDGEZERO_ENABLED_KEY) + .map_err(|e| fastly::Error::msg(format!("failed to read edgezero_enabled: {e}")))?; + Ok(value.as_deref().is_some_and(parse_edgezero_flag)) +} + +fn health_response(req: &FastlyRequest) -> Option { + if req.get_method() == FastlyMethod::GET && req.get_path() == "/health" { + return Some(FastlyResponse::from_status(200).with_body_text_plain("ok")); + } + + None +} + /// Entry point for the Fastly Compute program. /// /// Uses an undecorated `main()` with `FastlyRequest::from_client()` instead of -/// `#[fastly::main]` so we can call `send_to_client()` explicitly when needed. +/// `#[fastly::main]` so the legacy streaming publisher path can call +/// [`fastly::Response::stream_to_client`] explicitly. fn main() { - init_logger(); - - let mut req = FastlyRequest::from_client(); + let req = FastlyRequest::from_client(); - // Keep the health probe independent from settings loading and routing so - // readiness checks still get a cheap liveness response during startup. - if req.get_method() == FastlyMethod::GET && req.get_path() == "/health" { - FastlyResponse::from_status(200) - .with_body_text_plain("ok") - .send_to_client(); + // Health probe bypasses logging, settings, and app construction as a cheap liveness signal. + if let Some(response) = health_response(&req) { + response.send_to_client(); return; } - let settings = match get_settings() { - Ok(s) => s, + logging::init_logger(); + + let edgezero_config_store = match open_trusted_server_config_store() { + Ok(config_store) => config_store, Err(e) => { - log::error!("Failed to load settings: {:?}", e); - to_error_response(&e).send_to_client(); + log::warn!("failed to open EdgeZero config store, falling back to legacy path: {e}"); + legacy_main(req); return; } }; - log::debug!("Settings {settings:?}"); - // Short-circuit the ja4 debug probe before finalize_response so that - // Cache-Control: no-store, private cannot be replaced by operator [response_headers]. - if req.get_method() == FastlyMethod::GET && req.get_path() == "/_ts/debug/ja4" { - if settings.debug.ja4_endpoint_enabled { - build_ja4_debug_response(&req).send_to_client(); - } else { - FastlyResponse::from_status(fastly::http::StatusCode::NOT_FOUND).send_to_client(); - } - return; + if is_edgezero_enabled(&edgezero_config_store).unwrap_or_else(|e| { + log::warn!("failed to read edgezero_enabled flag, falling back to legacy path: {e}"); + false + }) { + log::debug!("routing request through EdgeZero path"); + edgezero_main(req, edgezero_config_store); + } else { + log::debug!("routing request through legacy path"); + legacy_main(req); } +} - // Build the auction orchestrator once at startup - let orchestrator = match build_orchestrator(&settings) { - Ok(o) => o, - Err(e) => { - log::error!("Failed to build auction orchestrator: {:?}", e); - to_error_response(&e).send_to_client(); - return; +/// Handles a request through the `EdgeZero` router path. +fn edgezero_main(mut req: FastlyRequest, config_store: ConfigStoreHandle) { + let app = TrustedServerApp::build_app(); + + // Strip client-spoofable forwarded headers before handing off to the + // EdgeZero dispatcher, mirroring the sanitization done in legacy_main. + compat::sanitize_fastly_forwarded_headers(&mut req); + + // Capture client IP before the request is consumed by dispatch. + let client_ip = req.get_client_ip_addr(); + + // `run_app_with_config` and `run_app_with_logging` call `init_logger` + // internally. A second `set_logger` call panics because our custom fern + // logger is already initialised above. `dispatch_with_config_handle` skips logger + // initialisation and injects the config store directly. + let mut response = + match edgezero_adapter_fastly::dispatch_with_config_handle(&app, req, config_store) { + Ok(response) => compat::from_fastly_response(response), + Err(e) => { + log::error!("EdgeZero dispatch failed: {e}"); + FastlyResponse::from_status(fastly::http::StatusCode::INTERNAL_SERVER_ERROR) + .with_body_text_plain("Internal Server Error") + .send_to_client(); + return; + } + }; + + if !response_was_finalized_by_middleware(&mut response) { + // Apply finalize headers at the entry point so that router-level + // 405/404 responses for unregistered HTTP methods (e.g. TRACE, WebDAV + // verbs) carry TS/geo headers. Middleware-finalized responses are + // skipped here to avoid a second settings read and geo lookup on the + // normal registered-route path. + match get_settings() { + Ok(settings) => { + apply_entry_point_finalize(&settings, client_ip, &mut response, |client_ip| { + FastlyPlatformGeo.lookup(client_ip).unwrap_or_else(|e| { + log::warn!("entry-point geo lookup failed: {e}"); + None + }) + }) + } + Err(e) => { + log::warn!("entry-point finalize skipped: failed to reload settings: {e:?}"); + } } + } + + compat::to_fastly_response(response).send_to_client(); +} + +fn response_was_finalized_by_middleware(response: &mut HttpResponse) -> bool { + response + .headers_mut() + .remove(HEADER_X_TS_FINALIZED) + .is_some() +} + +fn apply_entry_point_finalize( + settings: &Settings, + client_ip: Option, + response: &mut HttpResponse, + lookup_geo: F, +) where + F: FnOnce(Option) -> Option, +{ + let geo_info = if response.status() == edgezero_core::http::StatusCode::UNAUTHORIZED { + None + } else { + lookup_geo(client_ip) }; + apply_finalize_headers(settings, geo_info.as_ref(), response); +} - let integration_registry = match IntegrationRegistry::new(&settings) { - Ok(r) => r, +/// Handles a request using the original Fastly-native entry point. +/// +/// Preserves identical semantics to the pre-PR14 `main()`. Called when +/// the `edgezero_enabled` config flag is absent or `false`. +/// +/// The thin fastly<->http conversion layer (via `compat::from_fastly_request` / +/// `compat::to_fastly_response`) lives here in the adapter crate. `compat.rs` +/// will be deleted in PR 15 once this legacy path is retired. +// TODO: delete after Phase 5 EdgeZero cutover - see issue #495 +fn legacy_main(mut req: FastlyRequest) { + let state = match build_state() { + Ok(state) => state, Err(e) => { - log::error!("Failed to create integration registry: {:?}", e); + log::error!("Failed to build application state: {:?}", e); to_error_response(&e).send_to_client(); return; } }; + log::debug!("Settings {:?}", state.settings); + + // Short-circuit the ja4 debug probe before finalize_response so that + // Cache-Control: no-store, private cannot be replaced by operator [response_headers]. + if req.get_method() == FastlyMethod::GET && req.get_path() == "/_ts/debug/ja4" { + if state.settings.debug.ja4_endpoint_enabled { + build_ja4_debug_response(&req).send_to_client(); + } else { + FastlyResponse::from_status(fastly::http::StatusCode::NOT_FOUND).send_to_client(); + } + return; + } - let kv_store = std::sync::Arc::new(UnavailableKvStore) - as std::sync::Arc; // Strip client-spoofable forwarded headers at the edge before building // any request-derived context or converting to the core HTTP types. compat::sanitize_fastly_forwarded_headers(&mut req); - let runtime_services = build_runtime_services(&req, kv_store); + let runtime_services = build_runtime_services(&req, std::sync::Arc::clone(&state.kv_store)); let http_req = compat::from_fastly_request(req); let outcome = futures::executor::block_on(route_request( - &settings, - &orchestrator, - &integration_registry, + &state.settings, + &state.orchestrator, + &state.registry, &runtime_services, http_req, )) @@ -157,7 +293,7 @@ fn main() { match outcome { HandlerOutcome::Buffered(mut response) => { - finalize_response(&settings, geo_info.as_ref(), &mut response); + finalize_response(&state.settings, geo_info.as_ref(), &mut response); compat::to_fastly_response(response).send_to_client(); } HandlerOutcome::Streaming { @@ -165,15 +301,15 @@ fn main() { body, params, } => { - finalize_response(&settings, geo_info.as_ref(), &mut response); + finalize_response(&state.settings, geo_info.as_ref(), &mut response); let fastly_resp = compat::to_fastly_response_skeleton(response); let mut streaming_body = fastly_resp.stream_to_client(); match stream_publisher_body( body, &mut streaming_body, ¶ms, - &settings, - &integration_registry, + &state.settings, + &state.registry, ) { Ok(()) => { if let Err(e) = streaming_body.finish() { @@ -195,7 +331,7 @@ const FALLBACK_UNAVAILABLE: &str = "unavailable"; const FALLBACK_NOT_SENT: &str = "not sent"; const FALLBACK_NONE: &str = "none"; -// TODO: remove after JA4 evaluation completes — see #645 +// TODO: remove after JA4 evaluation completes - see #645 fn build_ja4_debug_response(req: &FastlyRequest) -> FastlyResponse { let ja4 = req.get_tls_ja4().unwrap_or(FALLBACK_UNAVAILABLE); let h2 = req @@ -249,29 +385,29 @@ async fn route_request( Err(e) => return Err(e), } - // Get path and method for routing + // Get path and method for routing. let path = req.uri().path().to_string(); let method = req.method().clone(); - // Match known routes and handle them + // Match known routes and handle them. match (method, path.as_str()) { - // Serve the tsjs library + // Serve the tsjs library. (Method::GET, path) if path.starts_with("/static/tsjs=") => { handle_tsjs_dynamic(&req, integration_registry).map(HandlerOutcome::Buffered) } - // Discovery endpoint for trusted-server capabilities and JWKS + // Discovery endpoint for trusted-server capabilities and JWKS. (Method::GET, "/.well-known/trusted-server.json") => { handle_trusted_server_discovery(settings, runtime_services, req) .map(HandlerOutcome::Buffered) } - // Signature verification endpoint + // Signature verification endpoint. (Method::POST, "/verify-signature") => { handle_verify_signature(settings, runtime_services, req).map(HandlerOutcome::Buffered) } - // Key rotation admin endpoints + // Key rotation admin endpoints. // Keep in sync with Settings::ADMIN_ENDPOINTS in crates/trusted-server-core/src/settings.rs (Method::POST, "/admin/keys/rotate") => { handle_rotate_key(settings, runtime_services, req).map(HandlerOutcome::Buffered) @@ -280,7 +416,7 @@ async fn route_request( handle_deactivate_key(settings, runtime_services, req).map(HandlerOutcome::Buffered) } - // Unified auction endpoint (returns creative HTML inline) + // Unified auction endpoint. (Method::POST, "/auction") => { match runtime_services_for_consent_route(settings, runtime_services) { Ok(auction_services) => { @@ -292,7 +428,7 @@ async fn route_request( } } - // tsjs endpoints + // tsjs endpoints. (Method::GET, "/first-party/proxy") => { handle_first_party_proxy(settings, runtime_services, req) .await @@ -323,7 +459,7 @@ async fn route_request( }) .map(HandlerOutcome::Buffered), - // No known route matched, proxy to publisher origin as fallback + // No known route matched, proxy to publisher origin as fallback. _ => { log::info!( "No known route matched for path: {}, proxying to publisher origin", @@ -366,22 +502,32 @@ fn resolve_publisher_response( } } -fn runtime_services_for_consent_route( +pub(crate) fn resolve_publisher_response_buffered( + publisher_response: PublisherResponse, settings: &Settings, - runtime_services: &RuntimeServices, -) -> Result> { - let Some(store_name) = settings.consent.consent_store.as_deref() else { - return Ok(runtime_services.clone()); - }; - - open_kv_store(store_name) - .map(|store| runtime_services.clone().with_kv_store(store)) - .map_err(|e| { - Report::new(TrustedServerError::KvStore { - store_name: store_name.to_string(), - message: e.to_string(), - }) - }) + integration_registry: &IntegrationRegistry, +) -> Result> { + match publisher_response { + PublisherResponse::Buffered(response) => Ok(response), + PublisherResponse::Stream { + mut response, + body, + params, + } => { + let mut output = Vec::new(); + stream_publisher_body(body, &mut output, ¶ms, settings, integration_registry)?; + response.headers_mut().insert( + header::CONTENT_LENGTH, + HeaderValue::from(output.len() as u64), + ); + *response.body_mut() = EdgeBody::from(output); + Ok(response) + } + PublisherResponse::PassThrough { mut response, body } => { + *response.body_mut() = body; + Ok(response) + } + } } /// Applies all standard response headers: geo, version, staging, and configured headers. @@ -393,35 +539,7 @@ fn runtime_services_for_consent_route( /// version/staging, then operator-configured `settings.response_headers`. /// This means operators can intentionally override any managed header. fn finalize_response(settings: &Settings, geo_info: Option<&GeoInfo>, response: &mut HttpResponse) { - if let Some(geo) = geo_info { - geo.set_response_headers(response); - } else { - response.headers_mut().insert( - HEADER_X_GEO_INFO_AVAILABLE, - HeaderValue::from_static("false"), - ); - } - - if let Ok(v) = ::std::env::var(ENV_FASTLY_SERVICE_VERSION) { - if let Ok(value) = HeaderValue::from_str(&v) { - response.headers_mut().insert(HEADER_X_TS_VERSION, value); - } else { - log::warn!("Skipping invalid FASTLY_SERVICE_VERSION response header value"); - } - } - if ::std::env::var(ENV_FASTLY_IS_STAGING).as_deref() == Ok("1") { - response - .headers_mut() - .insert(HEADER_X_TS_ENV, HeaderValue::from_static("staging")); - } - - for (key, value) in &settings.response_headers { - let header_name = HeaderName::from_bytes(key.as_bytes()) - .expect("settings.response_headers validated at load time"); - let header_value = - HeaderValue::from_str(value).expect("settings.response_headers validated at load time"); - response.headers_mut().insert(header_name, header_value); - } + apply_finalize_headers(settings, geo_info, response); } fn http_error_response(report: &Report) -> HttpResponse { @@ -441,8 +559,104 @@ fn http_error_response(report: &Report) -> HttpResponse { #[cfg(test)] mod tests { use super::*; + use edgezero_core::http::response_builder; use fastly::mime; + #[test] + fn parses_true_flag_values() { + assert!(parse_edgezero_flag("true"), "should parse 'true'"); + assert!(parse_edgezero_flag("1"), "should parse '1'"); + assert!(parse_edgezero_flag(" true "), "should trim whitespace"); + assert!( + parse_edgezero_flag(" 1 "), + "should trim whitespace around '1'" + ); + assert!(parse_edgezero_flag("TRUE"), "should parse uppercase 'TRUE'"); + assert!( + parse_edgezero_flag("True"), + "should parse mixed-case 'True'" + ); + } + + #[test] + fn rejects_non_true_flag_values() { + assert!(!parse_edgezero_flag("false"), "should not parse 'false'"); + assert!(!parse_edgezero_flag(""), "should not parse empty string"); + assert!( + !parse_edgezero_flag(" "), + "should not parse whitespace-only" + ); + assert!(!parse_edgezero_flag("yes"), "should not parse 'yes'"); + } + + #[test] + fn health_response_short_circuits_get_health() { + let req = FastlyRequest::get("https://example.com/health"); + + let mut response = health_response(&req).expect("should build health response"); + + assert_eq!( + response.get_status(), + fastly::http::StatusCode::OK, + "should return 200 OK" + ); + assert_eq!( + response.take_body_str(), + "ok", + "should return the health body" + ); + } + + #[test] + fn health_response_ignores_non_health_paths() { + let req = FastlyRequest::get("https://example.com/auction"); + + assert!( + health_response(&req).is_none(), + "should only short-circuit /health" + ); + } + + #[test] + fn response_was_finalized_by_middleware_strips_sentinel() { + let mut response = HttpResponse::new(EdgeBody::empty()); + response + .headers_mut() + .insert("x-ts-finalized", HeaderValue::from_static("1")); + + assert!( + response_was_finalized_by_middleware(&mut response), + "should detect middleware-finalized responses" + ); + assert!( + response.headers().get("x-ts-finalized").is_none(), + "sentinel should not be sent to clients" + ); + } + + #[test] + #[allow(clippy::panic)] + fn entry_point_finalize_skips_geo_lookup_for_401() { + let settings = get_settings().expect("should load settings"); + let mut response = response_builder() + .status(edgezero_core::http::StatusCode::UNAUTHORIZED) + .body(EdgeBody::empty()) + .expect("should build response"); + + apply_entry_point_finalize(&settings, None, &mut response, |_| { + panic!("should skip entry-point geo lookup for 401 responses"); + }); + + assert_eq!( + response + .headers() + .get(trusted_server_core::constants::HEADER_X_GEO_INFO_AVAILABLE) + .and_then(|v| v.to_str().ok()), + Some("false"), + "401 responses should still carry geo-unavailable headers" + ); + } + #[test] fn ja4_debug_response_uses_plain_text_and_fallback_values() { let req = FastlyRequest::get("https://example.com/_ts/debug/ja4"); diff --git a/crates/trusted-server-adapter-fastly/src/middleware.rs b/crates/trusted-server-adapter-fastly/src/middleware.rs new file mode 100644 index 00000000..bf94873a --- /dev/null +++ b/crates/trusted-server-adapter-fastly/src/middleware.rs @@ -0,0 +1,417 @@ +//! Middleware implementations for the dual-path entry point. +//! +//! Provides two middleware types that mirror the finalization and auth logic +//! from the legacy [`crate::finalize_response`] and [`crate::route_request`]: +//! +//! - [`FinalizeResponseMiddleware`] — geo lookup and standard TS header injection +//! - [`AuthMiddleware`] — basic-auth enforcement via [`enforce_basic_auth`] +//! +//! Registration order in [`crate::app`]: `FinalizeResponseMiddleware` outermost, +//! then `AuthMiddleware`. This ensures auth-rejected responses also receive the +//! standard TS headers before being returned to the client. + +use std::sync::Arc; + +use async_trait::async_trait; +use edgezero_adapter_fastly::FastlyRequestContext; +use edgezero_core::context::RequestContext; +use edgezero_core::error::EdgeError; +use edgezero_core::http::{HeaderName, HeaderValue, Response, StatusCode}; +use edgezero_core::middleware::{Middleware, Next}; +use edgezero_core::response::IntoResponse; +use trusted_server_core::auth::enforce_basic_auth; +use trusted_server_core::constants::{ + ENV_FASTLY_IS_STAGING, ENV_FASTLY_SERVICE_VERSION, HEADER_X_GEO_INFO_AVAILABLE, + HEADER_X_TS_ENV, HEADER_X_TS_VERSION, +}; +use trusted_server_core::geo::GeoInfo; +use trusted_server_core::platform::PlatformGeo; +use trusted_server_core::settings::Settings; + +pub(crate) const HEADER_X_TS_FINALIZED: &str = "x-ts-finalized"; + +// --------------------------------------------------------------------------- +// FinalizeResponseMiddleware +// --------------------------------------------------------------------------- + +/// Outermost middleware: performs geo lookup and injects all standard TS response headers. +/// +/// Registered first in the middleware chain so that it wraps all inner middleware +/// (including [`AuthMiddleware`]) and the handler. This guarantees every registered-route +/// response — including auth-rejected ones — carries a consistent set of headers. +/// +/// Router-level 405/404 responses for unregistered HTTP methods (e.g. TRACE) bypass the +/// middleware chain. Those are covered by a second call to [`apply_finalize_headers`] at +/// the `main.rs` entry point. Middleware-finalized responses carry +/// [`HEADER_X_TS_FINALIZED`] so the entry point can skip duplicate finalization. +/// +/// # Header precedence +/// +/// Headers are written in this order (last write wins): +/// 1. Geo headers (or `X-Geo-Info-Available: false` when geo is unavailable) +/// 2. `X-TS-Version` from `FASTLY_SERVICE_VERSION` env var +/// 3. `X-TS-ENV: staging` when `FASTLY_IS_STAGING == "1"` +/// 4. Operator-configured `settings.response_headers` (can override any managed header) +pub struct FinalizeResponseMiddleware { + settings: Arc, + geo: Arc, +} + +impl FinalizeResponseMiddleware { + /// Creates a new [`FinalizeResponseMiddleware`] with the given settings and geo lookup service. + pub fn new(settings: Arc, geo: Arc) -> Self { + Self { settings, geo } + } +} + +#[async_trait(?Send)] +impl Middleware for FinalizeResponseMiddleware { + async fn handle(&self, ctx: RequestContext, next: Next<'_>) -> Result { + let client_ip = FastlyRequestContext::get(ctx.request()).and_then(|c| c.client_ip); + + let mut response = match next.run(ctx).await { + Ok(r) => r, + Err(e) => { + log::error!("request handler failed: {e:?}"); + e.into_response() + } + }; + + // Skip geo lookup for authentication rejections — the lookup is unnecessary for 401s. + let geo_info = if response.status() != StatusCode::UNAUTHORIZED { + self.geo.lookup(client_ip).unwrap_or_else(|e| { + log::warn!("geo lookup failed: {e}"); + None + }) + } else { + None + }; + + apply_finalize_headers(&self.settings, geo_info.as_ref(), &mut response); + response + .headers_mut() + .insert(HEADER_X_TS_FINALIZED, HeaderValue::from_static("1")); + + Ok(response) + } +} + +// --------------------------------------------------------------------------- +// AuthMiddleware +// --------------------------------------------------------------------------- + +/// Inner middleware: enforces basic-auth before the handler runs. +/// +/// - `Ok(Some(response))` from [`enforce_basic_auth`] → auth failed; return the +/// challenge response (bubbles through [`FinalizeResponseMiddleware`] for header injection). +/// - `Ok(None)` → no auth required or credentials accepted; continue the chain. +/// - `Err(report)` → internal error; log and convert to an HTTP response via +/// [`crate::app::http_error`] using the error's documented status code. +/// +/// # Errors +/// +/// When [`enforce_basic_auth`] returns an error report, converts it to an HTTP +/// response via [`crate::app::http_error`] (preserving the error's status code) +/// so that [`FinalizeResponseMiddleware`] can still inject standard TS headers +/// before the response reaches the client. +pub struct AuthMiddleware { + settings: Arc, +} + +impl AuthMiddleware { + /// Creates a new [`AuthMiddleware`] with the given settings. + pub fn new(settings: Arc) -> Self { + Self { settings } + } +} + +#[async_trait(?Send)] +impl Middleware for AuthMiddleware { + async fn handle(&self, ctx: RequestContext, next: Next<'_>) -> Result { + match enforce_basic_auth(&self.settings, ctx.request()) { + Ok(Some(response)) => return Ok(response), + Ok(None) => {} + Err(report) => { + log::error!("auth check failed: {:?}", report); + return Ok(crate::app::http_error(&report)); + } + } + + next.run(ctx).await + } +} + +// --------------------------------------------------------------------------- +// apply_finalize_headers — extracted for unit testing +// --------------------------------------------------------------------------- + +/// Applies all standard Trusted Server response headers to the given response. +/// +/// Mirrors [`crate::finalize_response`] exactly, operating on [`Response`] from +/// `edgezero_core::http` instead of `HttpResponse`. +/// +/// Header write order (last write wins): +/// 1. Geo headers (`x-geo-*`) — or `X-Geo-Info-Available: false` when absent +/// 2. `X-TS-Version` from `FASTLY_SERVICE_VERSION` env var +/// 3. `X-TS-ENV: staging` when `FASTLY_IS_STAGING == "1"` +/// 4. `settings.response_headers` — operator-configured overrides applied last +pub(crate) fn apply_finalize_headers( + settings: &Settings, + geo_info: Option<&GeoInfo>, + response: &mut Response, +) { + if let Some(geo) = geo_info { + geo.set_response_headers(response); + } else { + response.headers_mut().insert( + HEADER_X_GEO_INFO_AVAILABLE, + HeaderValue::from_static("false"), + ); + } + + if let Ok(v) = std::env::var(ENV_FASTLY_SERVICE_VERSION) { + if let Ok(value) = HeaderValue::from_str(&v) { + response.headers_mut().insert(HEADER_X_TS_VERSION, value); + } else { + log::warn!("Skipping invalid FASTLY_SERVICE_VERSION response header value"); + } + } + + if std::env::var(ENV_FASTLY_IS_STAGING).as_deref() == Ok("1") { + response + .headers_mut() + .insert(HEADER_X_TS_ENV, HeaderValue::from_static("staging")); + } + + for (key, value) in &settings.response_headers { + let header_name = HeaderName::from_bytes(key.as_bytes()) + .expect("settings.response_headers validated at load time"); + let header_value = + HeaderValue::from_str(value).expect("settings.response_headers validated at load time"); + response.headers_mut().insert(header_name, header_value); + } +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + use std::collections::HashMap; + use std::net::IpAddr; + use std::sync::Arc; + + use edgezero_core::body::Body; + use edgezero_core::context::RequestContext; + use edgezero_core::error::EdgeError; + use edgezero_core::http::{request_builder, response_builder, Method, StatusCode}; + use edgezero_core::middleware::Next; + use edgezero_core::params::PathParams; + use error_stack::Report; + use futures::executor::block_on; + use trusted_server_core::platform::{PlatformError, PlatformGeo}; + + fn empty_response() -> Response { + response_builder() + .body(Body::empty()) + .expect("should build empty test response") + } + + fn empty_ctx() -> RequestContext { + let req = request_builder() + .method(Method::GET) + .uri("/test") + .body(Body::empty()) + .expect("should build test request"); + RequestContext::new(req, PathParams::new(HashMap::new())) + } + + struct FixedGeo(Option); + + impl PlatformGeo for FixedGeo { + fn lookup(&self, _: Option) -> Result, Report> { + Ok(self.0.clone()) + } + } + + fn settings_with_response_headers(headers: Vec<(&str, &str)>) -> Settings { + let mut s = + trusted_server_core::settings_data::get_settings().expect("should load test settings"); + s.response_headers = headers + .into_iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + s + } + + #[test] + fn operator_response_headers_override_earlier_headers() { + let settings = + settings_with_response_headers(vec![("X-Geo-Info-Available", "operator-override")]); + let mut response = empty_response(); + + // No geo_info → would set "false"; operator header should win instead. + apply_finalize_headers(&settings, None, &mut response); + + assert_eq!( + response + .headers() + .get("x-geo-info-available") + .and_then(|v| v.to_str().ok()), + Some("operator-override"), + "should override the managed geo header with the operator-configured value" + ); + } + + #[test] + fn sets_geo_unavailable_header_when_no_geo_info() { + let settings = settings_with_response_headers(vec![]); + let mut response = empty_response(); + + apply_finalize_headers(&settings, None, &mut response); + + assert_eq!( + response + .headers() + .get("x-geo-info-available") + .and_then(|v| v.to_str().ok()), + Some("false"), + "should set X-Geo-Info-Available: false when no geo info is available" + ); + } + + // --------------------------------------------------------------------------- + // FinalizeResponseMiddleware::handle tests + // --------------------------------------------------------------------------- + + #[test] + fn finalize_handle_injects_geo_unavailable_on_ok_response() { + let settings = settings_with_response_headers(vec![]); + let middleware = + FinalizeResponseMiddleware::new(Arc::new(settings), Arc::new(FixedGeo(None))); + let handler = + Arc::new( + |_ctx: RequestContext| async move { Ok::(empty_response()) }, + ); + + let response = block_on(middleware.handle(empty_ctx(), Next::new(&[], &*handler))) + .expect("should succeed"); + + assert_eq!( + response + .headers() + .get("x-geo-info-available") + .and_then(|v| v.to_str().ok()), + Some("false"), + "should set X-Geo-Info-Available: false when geo returns None" + ); + } + + #[test] + fn finalize_handle_marks_response_as_finalized() { + let settings = settings_with_response_headers(vec![]); + let middleware = + FinalizeResponseMiddleware::new(Arc::new(settings), Arc::new(FixedGeo(None))); + let handler = + Arc::new( + |_ctx: RequestContext| async move { Ok::(empty_response()) }, + ); + + let response = block_on(middleware.handle(empty_ctx(), Next::new(&[], &*handler))) + .expect("should succeed"); + + assert_eq!( + response + .headers() + .get("x-ts-finalized") + .and_then(|v| v.to_str().ok()), + Some("1"), + "middleware-finalized responses should carry the entry-point sentinel" + ); + } + + #[test] + fn finalize_handle_absorbs_handler_error_and_injects_headers() { + let settings = settings_with_response_headers(vec![]); + let middleware = + FinalizeResponseMiddleware::new(Arc::new(settings), Arc::new(FixedGeo(None))); + let handler = Arc::new(|_ctx: RequestContext| async move { + Err::(EdgeError::service_unavailable("test error")) + }); + + let response = block_on(middleware.handle(empty_ctx(), Next::new(&[], &*handler))) + .expect("should absorb handler error into a response"); + + assert!( + response.status().is_server_error(), + "should produce a server-error status for absorbed handler error" + ); + assert!( + response.headers().get("x-geo-info-available").is_some(), + "absorbed error response should still carry geo header" + ); + } + + #[test] + #[allow(clippy::panic)] + fn finalize_handle_skips_geo_lookup_for_401() { + struct PanicGeo; + impl PlatformGeo for PanicGeo { + fn lookup(&self, _: Option) -> Result, Report> { + panic!("should not call geo for 401 responses") + } + } + + let settings = settings_with_response_headers(vec![]); + let middleware = FinalizeResponseMiddleware::new(Arc::new(settings), Arc::new(PanicGeo)); + let handler = Arc::new(|_ctx: RequestContext| async move { + let mut resp = empty_response(); + *resp.status_mut() = StatusCode::UNAUTHORIZED; + Ok::(resp) + }); + + let response = block_on(middleware.handle(empty_ctx(), Next::new(&[], &*handler))) + .expect("should succeed without calling geo"); + + assert_eq!( + response.status(), + StatusCode::UNAUTHORIZED, + "should preserve 401 status" + ); + assert_eq!( + response + .headers() + .get("x-geo-info-available") + .and_then(|v| v.to_str().ok()), + Some("false"), + "should set geo-unavailable header without calling geo for 401" + ); + } + + // --------------------------------------------------------------------------- + // AuthMiddleware::handle tests + // --------------------------------------------------------------------------- + + #[test] + fn auth_handle_passes_through_when_auth_not_configured() { + let settings = + trusted_server_core::settings_data::get_settings().expect("should load test settings"); + let middleware = AuthMiddleware::new(Arc::new(settings)); + let handler = + Arc::new( + |_ctx: RequestContext| async move { Ok::(empty_response()) }, + ); + + let response = block_on(middleware.handle(empty_ctx(), Next::new(&[], &*handler))) + .expect("should pass through when auth is not configured"); + + assert_eq!( + response.status(), + StatusCode::OK, + "should reach the handler when auth is not required" + ); + } +} diff --git a/crates/trusted-server-core/src/integrations/sourcepoint.rs b/crates/trusted-server-core/src/integrations/sourcepoint.rs index 55bcdbb2..37334bab 100644 --- a/crates/trusted-server-core/src/integrations/sourcepoint.rs +++ b/crates/trusted-server-core/src/integrations/sourcepoint.rs @@ -315,9 +315,7 @@ impl SourcepointIntegration { ) -> bool { if let Some(client_ip) = client_ip { if let Ok(val) = HeaderValue::from_str(&client_ip.to_string()) { - proxy_req - .headers_mut() - .insert("x-forwarded-for", val); + proxy_req.headers_mut().insert("x-forwarded-for", val); } } @@ -417,8 +415,11 @@ impl SourcepointIntegration { let val = if forwarded_cookies { HeaderValue::from_static("private, max-age=0") } else { - HeaderValue::from_str(&format!("public, max-age={}", self.config.cache_ttl_seconds)) - .unwrap_or(HeaderValue::from_static("public")) + HeaderValue::from_str(&format!( + "public, max-age={}", + self.config.cache_ttl_seconds + )) + .unwrap_or(HeaderValue::from_static("public")) }; response.headers_mut().insert(header::CACHE_CONTROL, val); } @@ -680,9 +681,12 @@ impl IntegrationProxy for SourcepointIntegration { let (req_parts, req_body) = req.into_parts(); let request_body = if method == Method::POST { - let bytes = - collect_body_bounded(req_body, INTEGRATION_MAX_BODY_BYTES, SOURCEPOINT_INTEGRATION_ID) - .await?; + let bytes = collect_body_bounded( + req_body, + INTEGRATION_MAX_BODY_BYTES, + SOURCEPOINT_INTEGRATION_ID, + ) + .await?; EdgeBody::from(bytes) } else { EdgeBody::empty() @@ -703,9 +707,10 @@ impl IntegrationProxy for SourcepointIntegration { // responses (images, JSON API responses, CSS) keep the client's // original Accept-Encoding for efficiency. if self.config.rewrite_sdk && Self::is_likely_javascript_path(target_path) { - proxy_req - .headers_mut() - .insert(header::ACCEPT_ENCODING, HeaderValue::from_static("identity")); + proxy_req.headers_mut().insert( + header::ACCEPT_ENCODING, + HeaderValue::from_static("identity"), + ); } else if let Some(ae) = source_req.headers().get(header::ACCEPT_ENCODING) { proxy_req .headers_mut() @@ -801,8 +806,7 @@ impl IntegrationProxy for SourcepointIntegration { EdgeBody::Once(b) => b.to_vec(), EdgeBody::Stream(_) => { log::warn!("Sourcepoint: streaming response body, skipping rewrite"); - let mut response = - http::Response::from_parts(resp_parts, EdgeBody::empty()); + let mut response = http::Response::from_parts(resp_parts, EdgeBody::empty()); self.apply_cache_headers(&mut response, forwarded_cookies); return Ok(response); } @@ -1431,14 +1435,26 @@ mod tests { req.headers().get(name).and_then(|v| v.to_str().ok()) } - fn set_header(resp: &mut Response, name: impl http::header::IntoHeaderName, value: &str) { - resp.headers_mut() - .insert(name, HeaderValue::from_str(value).expect("should build header value")); + fn set_header( + resp: &mut Response, + name: impl http::header::IntoHeaderName, + value: &str, + ) { + resp.headers_mut().insert( + name, + HeaderValue::from_str(value).expect("should build header value"), + ); } - fn set_req_header(req: &mut Request, name: impl http::header::IntoHeaderName, value: &str) { - req.headers_mut() - .insert(name, HeaderValue::from_str(value).expect("should build header value")); + fn set_req_header( + req: &mut Request, + name: impl http::header::IntoHeaderName, + value: &str, + ) { + req.headers_mut().insert( + name, + HeaderValue::from_str(value).expect("should build header value"), + ); } fn take_body_bytes(resp: Response) -> Vec { @@ -1472,7 +1488,8 @@ mod tests { #[test] fn copy_headers_forwards_preflight_headers() { let integration = SourcepointIntegration::new(Arc::new(config(true))); - let mut original_req = make_req(Method::OPTIONS, "https://publisher.example.com/sourcepoint"); + let mut original_req = + make_req(Method::OPTIONS, "https://publisher.example.com/sourcepoint"); set_req_header(&mut original_req, "access-control-request-method", "POST"); set_req_header( &mut original_req, @@ -1552,7 +1569,11 @@ mod tests { fn apply_cache_headers_uses_private_no_store_for_cookie_setting_responses() { let integration = SourcepointIntegration::new(Arc::new(config(true))); let mut response = make_resp_with_status(StatusCode::OK); - set_header(&mut response, header::SET_COOKIE, "consentUUID=uuid123; Path=/"); + set_header( + &mut response, + header::SET_COOKIE, + "consentUUID=uuid123; Path=/", + ); set_header(&mut response, header::CACHE_CONTROL, "public, max-age=3600"); integration.apply_cache_headers(&mut response, false); diff --git a/crates/trusted-server-core/src/proxy.rs b/crates/trusted-server-core/src/proxy.rs index c456cfb2..bff1170e 100644 --- a/crates/trusted-server-core/src/proxy.rs +++ b/crates/trusted-server-core/src/proxy.rs @@ -74,9 +74,15 @@ pub struct ProxyRequestConfig<'a> { pub stream_passthrough: bool, /// Domains allowed for the initial request and any redirects. /// - /// When empty every host is permitted (open mode). Integration proxies - /// should leave this empty; first-party handlers should pass - /// `&settings.proxy.allowed_domains` to enforce the publisher allowlist. + /// **Open mode** (`&[]`): every host is permitted. Integration proxies pass `&[]` + /// because their target URLs originate from operator-controlled configuration + /// (e.g. `trusted-server.toml` integration settings) and are therefore trusted at + /// operator setup time rather than at request time. + /// + /// **Restricted mode** (non-empty slice): only hosts matching a listed pattern are + /// permitted. Currently only [`handle_first_party_proxy`] passes + /// `&settings.proxy.allowed_domains` because it follows redirect chains that may + /// originate from untrusted creative-supplied URLs. pub allowed_domains: &'a [String], } @@ -419,10 +425,11 @@ struct ProxyRequestHeaders<'a> { additional_headers: &'a [(header::HeaderName, HeaderValue)], copy_request_headers: bool, services: &'a RuntimeServices, - /// Domains permitted for the initial request and any redirects. - /// - /// Empty slice means open mode (all hosts allowed). Populated by first-party - /// handlers; integration proxies leave it empty. +} + +struct ProxyRedirectPolicy<'a> { + follow_redirects: bool, + stream_passthrough: bool, allowed_domains: &'a [String], } @@ -467,15 +474,17 @@ pub async fn proxy_request( settings, &req, target_url_parsed, - follow_redirects, body.as_deref(), ProxyRequestHeaders { additional_headers: &headers, copy_request_headers, services, + }, + ProxyRedirectPolicy { + follow_redirects, + stream_passthrough, allowed_domains, }, - stream_passthrough, ) .await } @@ -554,10 +563,9 @@ async fn proxy_with_redirects( settings: &Settings, req: &Request, target_url_parsed: url::Url, - follow_redirects: bool, body: Option<&[u8]>, request_headers: ProxyRequestHeaders<'_>, - stream_passthrough: bool, + redirect_policy: ProxyRedirectPolicy<'_>, ) -> Result, Report> { const MAX_REDIRECTS: usize = 4; @@ -585,7 +593,7 @@ async fn proxy_with_redirects( })); } - if !redirect_is_permitted(request_headers.allowed_domains, host) { + if !redirect_is_permitted(redirect_policy.allowed_domains, host) { log::warn!( "request to `{}` blocked: host not in proxy allowed_domains", host @@ -657,8 +665,14 @@ async fn proxy_with_redirects( let beresp = platform_resp.response; - if !follow_redirects { - return finalize_response(settings, req, ¤t_url, beresp, stream_passthrough); + if !redirect_policy.follow_redirects { + return finalize_response( + settings, + req, + ¤t_url, + beresp, + redirect_policy.stream_passthrough, + ); } let status = beresp.status(); @@ -672,7 +686,13 @@ async fn proxy_with_redirects( ); if !is_redirect { - return finalize_response(settings, req, ¤t_url, beresp, stream_passthrough); + return finalize_response( + settings, + req, + ¤t_url, + beresp, + redirect_policy.stream_passthrough, + ); } let Some(location) = beresp @@ -681,7 +701,13 @@ async fn proxy_with_redirects( .and_then(|h| h.to_str().ok()) .filter(|value| !value.is_empty()) else { - return finalize_response(settings, req, ¤t_url, beresp, stream_passthrough); + return finalize_response( + settings, + req, + ¤t_url, + beresp, + redirect_policy.stream_passthrough, + ); }; if redirect_attempt == MAX_REDIRECTS { @@ -702,7 +728,13 @@ async fn proxy_with_redirects( let next_scheme = next_url.scheme().to_ascii_lowercase(); if next_scheme != "http" && next_scheme != "https" { - return finalize_response(settings, req, ¤t_url, beresp, stream_passthrough); + return finalize_response( + settings, + req, + ¤t_url, + beresp, + redirect_policy.stream_passthrough, + ); } let next_host = match next_url.host_str() { @@ -713,7 +745,7 @@ async fn proxy_with_redirects( })); } }; - if !redirect_is_permitted(request_headers.allowed_domains, next_host) { + if !redirect_is_permitted(redirect_policy.allowed_domains, next_host) { log::warn!( "redirect to `{}` blocked: host not in proxy allowed_domains", next_host @@ -1292,7 +1324,8 @@ fn reconstruct_and_validate_signed_target( #[cfg(test)] mod tests { - use std::sync::Arc; + use std::collections::VecDeque; + use std::sync::{Arc, Mutex}; use super::{ handle_first_party_click, handle_first_party_proxy, handle_first_party_proxy_rebuild, @@ -1374,6 +1407,79 @@ mod tests { .expect("response body should be valid UTF-8") } + struct QueuedHttpResponse { + status: u16, + headers: Vec<(header::HeaderName, HeaderValue)>, + body: Vec, + } + + #[derive(Default)] + struct HeaderAwareStubHttpClient { + responses: Mutex>, + } + + impl HeaderAwareStubHttpClient { + fn new() -> Self { + Self::default() + } + + fn push_response( + &self, + status: u16, + headers: Vec<(header::HeaderName, HeaderValue)>, + body: Vec, + ) { + self.responses + .lock() + .expect("should lock queued responses") + .push_back(QueuedHttpResponse { + status, + headers, + body, + }); + } + } + + #[async_trait::async_trait(?Send)] + impl PlatformHttpClient for HeaderAwareStubHttpClient { + async fn send( + &self, + _request: PlatformHttpRequest, + ) -> Result> { + let queued = self + .responses + .lock() + .expect("should lock queued responses") + .pop_front() + .ok_or_else(|| Report::new(PlatformError::HttpClient))?; + + let mut builder = edgezero_core::http::response_builder().status(queued.status); + for (name, value) in queued.headers { + builder = builder.header(name, value); + } + + let response = builder + .body(EdgeBody::from(queued.body)) + .expect("should build stub HTTP response"); + + Ok(PlatformResponse::new(response)) + } + + async fn send_async( + &self, + _request: PlatformHttpRequest, + ) -> Result> { + Err(Report::new(PlatformError::Unsupported)) + } + + async fn select( + &self, + _pending_requests: Vec, + ) -> Result> { + Err(Report::new(PlatformError::Unsupported)) + } + } + fn build_http_response(status: StatusCode, body: EdgeBody) -> Response { let mut response = Response::new(body); *response.status_mut() = status; @@ -2139,6 +2245,83 @@ mod tests { ); } + #[tokio::test] + async fn proxy_request_allows_open_mode_when_settings_allowlist_is_non_empty() { + let mut settings = create_test_settings(); + settings.proxy.allowed_domains = vec!["allowed.example".to_string()]; + + let stub = Arc::new(HeaderAwareStubHttpClient::new()); + stub.push_response(200, Vec::new(), b"ok".to_vec()); + let services = build_services_with_http_client( + Arc::clone(&stub) as Arc + ); + let req = build_http_request(Method::GET, "https://edge.example/"); + + let response = proxy_request( + &settings, + req, + ProxyRequestConfig { + target_url: "https://blocked.example/resource.js", + follow_redirects: false, + forward_ec_id: false, + body: None, + headers: Vec::new(), + copy_request_headers: false, + stream_passthrough: false, + allowed_domains: &[], + }, + &services, + ) + .await + .expect("open mode should ignore settings.proxy.allowed_domains"); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response_body_string(response), "ok"); + } + + #[tokio::test] + async fn proxy_request_uses_config_allowlist_for_redirect_hops() { + let mut settings = create_test_settings(); + settings.proxy.allowed_domains = vec!["origin.example".to_string()]; + + let stub = Arc::new(HeaderAwareStubHttpClient::new()); + stub.push_response( + 302, + vec![( + header::LOCATION, + HeaderValue::from_static("https://redirected.example/final.js"), + )], + Vec::new(), + ); + stub.push_response(200, Vec::new(), b"redirected".to_vec()); + + let services = build_services_with_http_client( + Arc::clone(&stub) as Arc + ); + let req = build_http_request(Method::GET, "https://edge.example/"); + + let response = proxy_request( + &settings, + req, + ProxyRequestConfig { + target_url: "https://origin.example/start.js", + follow_redirects: true, + forward_ec_id: false, + body: None, + headers: Vec::new(), + copy_request_headers: false, + stream_passthrough: false, + allowed_domains: &[], + }, + &services, + ) + .await + .expect("open mode should allow redirect hops outside settings allowlist"); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response_body_string(response), "redirected"); + } + #[tokio::test] async fn proxy_request_forwards_curated_headers_when_copy_request_headers_is_true() { use crate::platform::test_support::StubHttpClient; @@ -2511,12 +2694,9 @@ mod tests { // --- initial target allowlist enforcement (integration-level) --- // - // NOTE: A test for Nth-hop redirect blocking (i.e. exercising the - // `redirect_is_permitted` check that fires *after* receiving a 302 - // response) requires a Viceroy backend fixture that returns a redirect. - // That infrastructure is not available here. The unit tests above for - // `redirect_is_permitted` and `ip_literal_blocked_by_domain_allowlist` - // cover the blocking logic used at every hop. + // The unit tests above cover the host-matching logic itself. The tests + // below verify that proxy_request threads config.allowed_domains through + // the initial target check and redirect hops. #[tokio::test] async fn proxy_initial_target_blocked_by_allowlist() { diff --git a/crates/trusted-server-core/src/settings_data.rs b/crates/trusted-server-core/src/settings_data.rs index f69fc7ba..00f9bb20 100644 --- a/crates/trusted-server-core/src/settings_data.rs +++ b/crates/trusted-server-core/src/settings_data.rs @@ -1,4 +1,6 @@ use core::str; +use std::sync::OnceLock; + use error_stack::{Report, ResultExt}; use validator::Validate; @@ -8,6 +10,7 @@ use crate::settings::{EdgeCookie, Publisher, Settings}; pub use crate::auction_config_types::AuctionConfig; const SETTINGS_DATA: &[u8] = include_bytes!("../../../target/trusted-server-out.toml"); +static SETTINGS: OnceLock = OnceLock::new(); /// Creates a new [`Settings`] instance from the embedded configuration file. /// @@ -20,6 +23,21 @@ const SETTINGS_DATA: &[u8] = include_bytes!("../../../target/trusted-server-out. /// - [`TrustedServerError::InvalidUtf8`] if the embedded TOML file contains invalid UTF-8 /// - [`TrustedServerError::Configuration`] if the configuration is invalid or missing required fields pub fn get_settings() -> Result> { + if let Some(settings) = SETTINGS.get() { + return Ok(settings.clone()); + } + + let settings = load_settings()?; + if SETTINGS.set(settings.clone()).is_err() { + if let Some(settings) = SETTINGS.get() { + return Ok(settings.clone()); + } + } + + Ok(settings) +} + +fn load_settings() -> Result> { let toml_bytes = SETTINGS_DATA; let toml_str = str::from_utf8(toml_bytes).change_context(TrustedServerError::InvalidUtf8 { message: "embedded trusted-server.toml file".to_string(), diff --git a/fastly.toml b/fastly.toml index 9d6c0f26..e38b32d6 100644 --- a/fastly.toml +++ b/fastly.toml @@ -40,6 +40,14 @@ build = """ env = "FASTLY_KEY" [local_server.config_stores] + [local_server.config_stores.trusted_server_config] + format = "inline-toml" + [local_server.config_stores.trusted_server_config.contents] + # "true" / "1" (case-insensitive) enable the EdgeZero path. Missing, + # unreadable, or any other value falls back to the legacy entry point. + # Keep "false" until EdgeZero reaches full functional parity with legacy. + edgezero_enabled = "false" + [local_server.config_stores.jwks_store] format = "inline-toml" [local_server.config_stores.jwks_store.contents]