diff --git a/Cargo.lock b/Cargo.lock index 8e08f3a13..9a2fa3e25 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1356,6 +1356,7 @@ dependencies = [ "async-stream", "async-trait", "base16ct", + "base64", "brotli", "brotli-decompressor", "bytes", diff --git a/crates/edgezero-adapter-axum/src/cli.rs b/crates/edgezero-adapter-axum/src/cli.rs index a062f25bd..88dc734e6 100644 --- a/crates/edgezero-adapter-axum/src/cli.rs +++ b/crates/edgezero-adapter-axum/src/cli.rs @@ -918,6 +918,14 @@ mod tests { } } + #[test] + fn client_identities_are_unsupported() { + assert_eq!( + AXUM_ADAPTER.capability(Capability::OutboundClientIdentity), + CapabilitySupport::Unsupported + ); + } + #[test] fn adapter_capability_matrix_matches_contracts() { let connect = AXUM_ADAPTER.capability(Capability::OutboundConnectTimeout); diff --git a/crates/edgezero-adapter-axum/src/outbound.rs b/crates/edgezero-adapter-axum/src/outbound.rs index 48e1da9c1..d195aa3d1 100644 --- a/crates/edgezero-adapter-axum/src/outbound.rs +++ b/crates/edgezero-adapter-axum/src/outbound.rs @@ -23,10 +23,11 @@ use edgezero_core::outbound::test_support::{ NativeBodyRecorder, native_body_recorder, observe_sdk_read, own_sdk_operation, own_sdk_source, }; use edgezero_core::outbound::{ - OutboundBatch, OutboundBatchDriverEvent, OutboundDispatchRequest, OutboundExchangeOwner, - OutboundFuture, OutboundHead, OutboundHeaderFidelity, OutboundHeaderInput, OutboundHttpClient, - OutboundPending, OutboundPreparedBatch, OutboundRequest, OutboundRequestParts, - OutboundResponse, OutboundResponseContext, OutboundSendMode, OutboundTask, OutboundTime, + ClientIdentityError, OutboundBatch, OutboundBatchDriverEvent, OutboundDispatchRequest, + OutboundExchangeOwner, OutboundFuture, OutboundHead, OutboundHeaderFidelity, + OutboundHeaderInput, OutboundHttpClient, OutboundPending, OutboundPreparedBatch, + OutboundRequest, OutboundRequestParts, OutboundResponse, OutboundResponseContext, + OutboundSendMode, OutboundTask, OutboundTime, }; use edgezero_core::time::{Deadline, DispatchBudget, MonotonicClock, MonotonicInstant}; use futures::channel::{mpsc, oneshot}; @@ -157,6 +158,12 @@ impl AxumOutboundClient { } fn validate_options(request: &OutboundRequest) -> Result<(), EdgeError> { + if let Some(name) = request.client_identity_name() { + return Err(EdgeError::client_identity( + name, + ClientIdentityError::Unsupported { adapter: "axum" }, + )); + } if request.image_optimizer_options().is_some() { return Err(EdgeError::bad_request( "image_optimizer is not supported by axum", @@ -1267,6 +1274,28 @@ mod clock_tests { .expect("zero connect timeout conformance"); } + #[test] + fn client_identity_is_unsupported_without_transport() { + use edgezero_core::outbound::ClientIdentityName; + use futures::FutureExt as _; + let executor_owner = AxumOutboundExecutor::new(); + let client = edgezero_core::HttpClient::with_client( + AxumOutboundClient::try_new(executor_owner.handle()).expect("client"), + ); + let request = OutboundRequest::get("https://127.0.0.1:9/mtls") + .expect("request") + .client_identity(ClientIdentityName::new("mtls").expect("name")); + let error = client + .send(request) + .now_or_never() + .expect("rejected before any transport") + .expect_err("axum cannot present client identities"); + assert_eq!( + error.client_identity_error(), + Some(&ClientIdentityError::Unsupported { adapter: "axum" }) + ); + } + #[test] fn unsupported_optimizer_precedes_expiry_without_transport() { use edgezero_core::outbound::test_support::check_unsupported_image_optimizer_preflight; diff --git a/crates/edgezero-adapter-cloudflare/src/cli.rs b/crates/edgezero-adapter-cloudflare/src/cli.rs index f81265529..230d1d2f1 100644 --- a/crates/edgezero-adapter-cloudflare/src/cli.rs +++ b/crates/edgezero-adapter-cloudflare/src/cli.rs @@ -1613,6 +1613,10 @@ mod tests { CapabilitySupport::Native, ), (Capability::OutboundCacheBypass, CapabilitySupport::Native), + ( + Capability::OutboundClientIdentity, + CapabilitySupport::Unsupported, + ), ( Capability::OutboundImageOptimizer, CapabilitySupport::Unsupported, diff --git a/crates/edgezero-adapter-cloudflare/src/outbound.rs b/crates/edgezero-adapter-cloudflare/src/outbound.rs index 6419774f3..56153c75b 100644 --- a/crates/edgezero-adapter-cloudflare/src/outbound.rs +++ b/crates/edgezero-adapter-cloudflare/src/outbound.rs @@ -34,6 +34,11 @@ use edgezero_core::error::{BadGatewayReason, BudgetSource}; all(feature = "cloudflare", target_arch = "wasm32"), feature = "test-utils" ))] +use edgezero_core::outbound::ClientIdentityError; +#[cfg(any( + all(feature = "cloudflare", target_arch = "wasm32"), + feature = "test-utils" +))] use edgezero_core::outbound::OutboundRequest; #[cfg(feature = "test-utils")] use edgezero_core::outbound::{OutboundSendMode, validate_for_dispatch}; @@ -3843,6 +3848,14 @@ fn timeout_error(cause: BudgetSource) -> EdgeError { feature = "test-utils" ))] fn validate_supported_options(request: &OutboundRequest) -> Result<(), EdgeError> { + if let Some(name) = request.client_identity_name() { + return Err(EdgeError::client_identity( + name, + ClientIdentityError::Unsupported { + adapter: "cloudflare", + }, + )); + } if request.image_optimizer_options().is_some() { return Err(EdgeError::bad_request( "image_optimizer is not supported by cloudflare", diff --git a/crates/edgezero-adapter-cloudflare/tests/contract.rs b/crates/edgezero-adapter-cloudflare/tests/contract.rs index e3e48af7c..048c4ccfb 100644 --- a/crates/edgezero-adapter-cloudflare/tests/contract.rs +++ b/crates/edgezero-adapter-cloudflare/tests/contract.rs @@ -1982,6 +1982,22 @@ mod native_tests { use futures_util::stream; use std::time::Duration; + #[test] + fn client_identity_is_unsupported_before_other_preflight() { + let request = OutboundRequest::get("https://example.com/mtls") + .unwrap() + .client_identity(edgezero_core::ClientIdentityName::new("mtls").unwrap()) + .body(Body::from_stream(stream::pending())) + .timeout(Duration::ZERO); + let error = validate_batch_request_for_test(&request).expect_err("unsupported"); + assert_eq!( + error.client_identity_error(), + Some(&edgezero_core::ClientIdentityError::Unsupported { + adapter: "cloudflare" + }) + ); + } + #[test] fn image_optimizer_rejection_precedes_other_preflight() { let request = OutboundRequest::get("https://example.com/image") diff --git a/crates/edgezero-adapter-fastly/src/cli.rs b/crates/edgezero-adapter-fastly/src/cli.rs index 6815312a1..749d50941 100644 --- a/crates/edgezero-adapter-fastly/src/cli.rs +++ b/crates/edgezero-adapter-fastly/src/cli.rs @@ -39,6 +39,7 @@ use edgezero_adapter::scaffold::{ ManifestSpec, ReadmeInfo, TemplateRegistration, register_adapter_blueprint, }; use edgezero_core::env_config::{EnvConfig, merge_env_defaults}; +use edgezero_core::manifest::Manifest; use edgezero_core::{Capability, CapabilitySupport, PlatformMetadata}; use walkdir::WalkDir; @@ -2041,6 +2042,7 @@ impl Adapter for FastlyCliAdapter { Capability::IngressAdmission | Capability::OutboundAuthorityOverride | Capability::OutboundCacheBypass + | Capability::OutboundClientIdentity | Capability::OutboundConnectTimeout | Capability::OutboundFailureDiagnostics | Capability::OutboundFlexiblePhaseBudget @@ -2227,6 +2229,10 @@ impl Adapter for FastlyCliAdapter { validate_fastly_config_key(logical_store_id, key, staging, local) } + fn validate_client_identities(&self, manifest: &Manifest) -> Result<(), String> { + validate_fastly_client_identities(manifest) + } + fn preflight_deploy( &self, context: &AdapterDeployContext, @@ -5913,6 +5919,36 @@ fn effective_deploy_environment(context: &AdapterDeployContext) -> Result Result<(), String> { + let unresolved: Vec = manifest + .capabilities + .outbound + .client_identities + .iter() + .filter_map(|(name, identity)| { + let mut missing = Vec::new(); + if identity.resolved_config_store(&manifest.stores).is_none() { + missing.push("config store"); + } + if identity.resolved_secret_store(&manifest.stores).is_none() { + missing.push("secret store"); + } + (!missing.is_empty()).then(|| format!("`{name}` (no {})", missing.join(" or "))) + }) + .collect(); + if unresolved.is_empty() { + return Ok(()); + } + Err(format!( + "adapter 'fastly' reads client identity bindings from a config store and a secret store, \ + and these identities cannot resolve one: {}. Declare [stores.config] and [stores.secrets], \ + or name the stores with `config-store` and `secret-store`.", + unresolved.join(", ") + )) +} + fn validate_fastly_config_key( logical_store_id: &str, key: &str, @@ -6979,6 +7015,51 @@ mod tests { assert!(FASTLY_BLUEPRINT.logging.endpoint.is_none()); } + #[test] + fn client_identities_need_resolvable_config_and_secret_stores() { + use edgezero_core::manifest::ManifestLoader; + + let resolvable = ManifestLoader::load_from_str( + "[capabilities.outbound.client-identities.defaulted]\n\ + [capabilities.outbound.client-identities.explicit]\n\ + config-store = \"app_config\"\nsecret-store = \"keys\"\n\ + [stores.config]\nids = [\"app_config\"]\n\ + [stores.secrets]\nids = [\"keys\"]\n", + ); + assert_eq!( + FastlyCliAdapter.validate_client_identities(resolvable.manifest()), + Ok(()) + ); + + let no_secrets = ManifestLoader::load_from_str( + "[capabilities.outbound.client-identities.mtls]\n\ + [stores.config]\nids = [\"app_config\"]\n", + ); + let no_secret_error = FastlyCliAdapter + .validate_client_identities(no_secrets.manifest()) + .expect_err("missing secret store"); + assert!( + no_secret_error.contains("`mtls` (no secret store)"), + "{no_secret_error}" + ); + + let no_stores = + ManifestLoader::load_from_str("[capabilities.outbound.client-identities.mtls]\n"); + let no_store_error = FastlyCliAdapter + .validate_client_identities(no_stores.manifest()) + .expect_err("missing both stores"); + assert!( + no_store_error.contains("`mtls` (no config store or secret store)"), + "{no_store_error}" + ); + + let none = ManifestLoader::load_from_str("[app]\nname = \"plain\"\n"); + assert_eq!( + FastlyCliAdapter.validate_client_identities(none.manifest()), + Ok(()) + ); + } + #[test] fn adapter_capability_matrix_matches_contracts() { adapter_capability_matrix_matches_outbound_spec(); @@ -7079,6 +7160,10 @@ mod tests { CapabilitySupport::BestEffort, ), (Capability::OutboundCacheBypass, CapabilitySupport::Native), + ( + Capability::OutboundClientIdentity, + CapabilitySupport::Native, + ), ( Capability::OutboundImageOptimizer, CapabilitySupport::BestEffort, diff --git a/crates/edgezero-adapter-fastly/src/config_store.rs b/crates/edgezero-adapter-fastly/src/config_store.rs index 6f791cc62..4e1605a80 100644 --- a/crates/edgezero-adapter-fastly/src/config_store.rs +++ b/crates/edgezero-adapter-fastly/src/config_store.rs @@ -43,7 +43,11 @@ impl FastlyConfigStore { unsafe_code, reason = "the pinned ABI receives a live initialized slice and cannot resize it" )] - fn read_entry(&self, key: &str, limit: u64) -> Result, ConfigStoreError> { + pub(crate) fn read_entry( + &self, + key: &str, + limit: u64, + ) -> Result, ConfigStoreError> { let read_limit = limit.min(MAX_ENTRY_BYTES); match &self.inner { FastlyConfigStoreBackend::Fastly(handle) => { @@ -90,7 +94,7 @@ impl FastlyConfigStore { unsafe_code, reason = "the pinned host ABI writes only the supplied handle out-parameter" )] - fn try_open_optional(name: &str) -> Result, ConfigStoreError> { + pub(crate) fn try_open_optional(name: &str) -> Result, ConfigStoreError> { let mut handle = fastly_shared::INVALID_CONFIG_STORE_HANDLE; // SAFETY: the UTF-8 name slice and initialized out-parameter remain live // for this synchronous call. Config Store exposes no close operation. diff --git a/crates/edgezero-adapter-fastly/src/outbound.rs b/crates/edgezero-adapter-fastly/src/outbound.rs index c26f58d30..37716030a 100644 --- a/crates/edgezero-adapter-fastly/src/outbound.rs +++ b/crates/edgezero-adapter-fastly/src/outbound.rs @@ -20,6 +20,8 @@ ) )] +#[cfg(any(feature = "fastly", test))] +mod client_identity; #[cfg(feature = "fastly")] mod image_optimizer; @@ -42,10 +44,12 @@ use edgezero_core::error::EdgeError; use edgezero_core::error::{BadGatewayReason, BudgetSource}; #[cfg(test)] use edgezero_core::outbound::OutboundBatchDriverEvent; +#[cfg(any(feature = "fastly", feature = "test-utils", test))] +use edgezero_core::outbound::OutboundCachePolicy; #[cfg(feature = "test-utils")] use edgezero_core::outbound::validate_for_dispatch; #[cfg(any(feature = "fastly", feature = "test-utils"))] -use edgezero_core::outbound::{OutboundRequest, OutboundSendMode}; +use edgezero_core::outbound::{ClientIdentityError, OutboundRequest, OutboundSendMode}; #[cfg(any(feature = "fastly", test))] use edgezero_core::time::{DispatchBudget, MonotonicInstant}; @@ -259,7 +263,7 @@ mod fastly_impl { use std::io::{Read as _, Result as IoResult, Write}; use std::net::IpAddr; use std::rc::Rc; - use std::sync::{Mutex, OnceLock}; + use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use async_stream::stream; @@ -279,6 +283,9 @@ mod fastly_impl { NativeBodyOwner, NativeBodyRecorder, native_body_recorder, own_sdk_operation, own_sdk_resource, }; + use edgezero_core::outbound::{ + ClientCertificateChain, ClientIdentityMetadata, ClientIdentityPolicy, + }; #[cfg(test)] use edgezero_core::outbound::{ HttpClient, OutboundProxyMarker, ResponseDecoding, ResponseMode, normalize_for_dispatch, @@ -307,6 +314,7 @@ mod fastly_impl { use futures_util::{FutureExt as _, StreamExt as _}; use sha2::{Digest as _, Sha256}; + use super::client_identity; use super::progress::{HeadPoll, Progress, Transport}; use super::{timeout_error, validate_supported_options}; @@ -541,6 +549,7 @@ mod fastly_impl { #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct BackendIdentity { + client_identity: Option<(String, [u8; 32])>, host: String, phase_ms: u64, connect_ms: Option, @@ -557,6 +566,7 @@ mod fastly_impl { } struct RequestPlan { + client_identity: Option<(ClientIdentityMetadata, Arc)>, identity: Result, context: OutboundResponseContext, parts: OutboundRequestParts, @@ -567,11 +577,16 @@ mod fastly_impl { let budget = request.budget(); let mut identity = backend_identity_view(request.request(), budget).map(|(settings, ())| settings); + let client_identity = request + .client_identity() + .cloned() + .zip(request.client_identity_policy().cloned()); let (parts, context) = request.into_parts(); if let Ok(settings) = &mut identity { settings.phase_ms = backend_timer_ms(parts.timeout.unwrap_or(budget.duration)); } Self { + client_identity, identity, context, parts, @@ -579,6 +594,10 @@ mod fastly_impl { } fn is_registered(&self, cache: &HashMap) -> bool { + // An identity backend's name depends on the certificate read during dispatch. + if self.client_identity.is_some() { + return false; + } self.identity.as_ref().is_ok_and(|identity| { cache .get(&backend_name(identity)) @@ -609,6 +628,7 @@ mod fastly_impl { /// Native outbound HTTP implementation for Fastly Compute. pub struct FastlyOutboundClient { + bindings: Arc, time: OutboundTime, } @@ -619,11 +639,22 @@ mod fastly_impl { Self::with_time(native_time(MonotonicClock::default())) } + /// A client for one dispatch that shares this request's identity bindings. + fn sharing(&self, time: OutboundTime) -> Self { + Self { + bindings: Arc::clone(&self.bindings), + time, + } + } + /// Builds a client that evaluates every outbound lifetime against `clock`. #[must_use] #[inline] pub fn with_time(time: OutboundTime) -> Self { - Self { time } + Self { + bindings: Arc::default(), + time, + } } fn ensure_backend( @@ -633,6 +664,7 @@ mod fastly_impl { budget: DispatchBudget, batch_started_at: Option, observation: Option>, + certificate: Option<(&ClientIdentityMetadata, &ClientCertificateChain)>, ) -> Result { let registry = BACKENDS.get_or_init(|| Mutex::new(HashMap::new())); let record = observation.clone(); @@ -663,6 +695,25 @@ mod fastly_impl { builder = builder.sni_hostname(&settings.host); } } + if let Some((metadata, chain)) = certificate { + // The key is opened only here, when a backend must be registered. + let key = client_identity::open_private_key( + metadata, + self.time.clock(), + budget.deadline, + ) + .map_err(|failure| { + client_identity::binding_error(metadata, failure, || { + timeout_error(budget.cause) + }) + })?; + builder = builder.provide_client_certificate(chain.pem(), key); + log::debug!( + "registering client identity backend for `{}` (leaf sha256 {})", + metadata.name(), + encode_string(&chain.leaf_fingerprint()) + ); + } register_backend_while_live(batch_started_at, budget, self.time.clock(), || { registration.run(|| { let result = builder.finish(); @@ -688,6 +739,7 @@ mod fastly_impl { fn configure_plan(&self, plan: RequestPlan) -> Result { let RequestPlan { + client_identity, identity: planned_identity, context, mut parts, @@ -695,7 +747,32 @@ mod fastly_impl { context.scope().check()?; let observation = observation::for_scope(context.scope()); let budget = context.budget(); - let identity = planned_identity?; + let mut identity = planned_identity?; + let certificate = + match &client_identity { + None => None, + Some((metadata, policy)) => { + let reader = client_identity::FastlyConfigEntries { + clock: context.clock(), + deadline: budget.deadline, + }; + let binding = self.bindings.resolve(metadata, policy, &reader).map_err( + |failure| { + client_identity::binding_error(metadata, failure, || { + timeout_error(budget.cause) + }) + }, + )?; + binding.hosts.check(&parts.uri).map_err(|reason| { + EdgeError::client_identity(metadata.name(), reason) + })?; + identity.client_identity = Some(( + metadata.name().as_str().to_owned(), + binding.chain.chain_fingerprint(), + )); + Some((metadata, binding)) + } + }; if !parts.headers.contains_key(ACCEPT_ENCODING) { parts .headers @@ -704,8 +781,16 @@ mod fastly_impl { budget_remaining(budget, context.clock())?; let batch_start = (context.mode() == OutboundSendMode::Batch).then_some(context.entered_at()); - let backend = - self.ensure_backend(identity, &parts, budget, batch_start, observation)?; + let backend = self.ensure_backend( + identity, + &parts, + budget, + batch_start, + observation, + certificate + .as_ref() + .map(|(metadata, binding)| (*metadata, &binding.chain)), + )?; budget_remaining(budget, context.clock())?; Ok(PreparedRequest { backend, @@ -729,12 +814,10 @@ mod fastly_impl { let time = context.time().clone(); let configured = super::effective_connect_ms(parts.connect_timeout, budget.duration).is_some(); - let fastly_request = build_fastly_request( - &parts.method, - &parts.uri, - &parts.headers, - parts.cache_policy, - ); + let cache_policy = + super::effective_cache_policy(parts.client_identity.is_some(), parts.cache_policy); + let fastly_request = + build_fastly_request(&parts.method, &parts.uri, &parts.headers, cache_policy); let max_request_body_bytes = parts.max_request_body_bytes; let (payload, _scope) = parts.body.into_parts(); let response = match payload { @@ -807,11 +890,12 @@ mod fastly_impl { } fn pipeline( + &self, plan: RequestPlan, progress: &NativeProgress, ) -> OutboundFuture { let failure = plan.context.exchange_failure(); - let client = Self::with_time(plan.context.time().clone()); + let client = self.sharing(plan.context.time().clone()); let exchange_progress = progress.with_exchange_failure(failure.clone()); Box::pin(async move { let budget = plan.context.budget(); @@ -864,7 +948,7 @@ mod fastly_impl { #[inline] fn dispatch_head(&self, request: OutboundDispatchRequest) -> OutboundFuture { - let client = Self::with_time(request.time().clone()); + let client = self.sharing(request.time().clone()); let selected_progress = super::scope::native_progress( request.scope(), request.time(), @@ -902,7 +986,7 @@ mod fastly_impl { .with_exchange_failure(failure.clone()); super::scope::begin( &scope, - Self::pipeline(plan, &progress), + self.pipeline(plan, &progress), &progress, &time, entered, @@ -961,7 +1045,7 @@ mod fastly_impl { .map(|(index, plan)| { let budget = plan.context.budget(); let failure = plan.context.exchange_failure(); - let future = Self::pipeline(plan, &progress); + let future = self.pipeline(plan, &progress); let clock = time.clock().clone(); async move { let outcome = future.await; @@ -1028,6 +1112,7 @@ mod fastly_impl { .ok_or_else(|| EdgeError::bad_request("outbound request URI has no scheme"))?; Ok(( BackendIdentity { + client_identity: None, host: request.host_name().to_owned(), phase_ms: backend_timer_ms(budget.duration), // Keep the configured tuple stable across aggregate-budget ladder rungs. @@ -1052,7 +1137,7 @@ mod fastly_impl { )] fn backend_name(identity: &BackendIdentity) -> String { // Timer derivation, ladder or canonical-key changes require a new identity version - // and matching golden/readback evidence; never reuse b31v1 for a changed policy. + // and matching golden/readback evidence; never reuse a version for a changed policy. v2 adds the client identity. let mut hasher = Sha256::new(); for field in [&identity.scheme, &identity.host, &identity.wire_authority] { hasher.update(field.as_bytes()); @@ -1065,7 +1150,13 @@ mod fastly_impl { hasher.update(b"connect-ms-v1"); hasher.update(connect_ms.to_be_bytes()); } - format!("ez_b31v1_{}", encode_string(&hasher.finalize())) + if let Some((name, chain_fingerprint)) = &identity.client_identity { + hasher.update(b"client-identity-v1"); + hasher.update(name.as_bytes()); + hasher.update([0_u8]); + hasher.update(chain_fingerprint); + } + format!("ez_b31v2_{}", encode_string(&hasher.finalize())) } fn backend_timer_ms(anchor: Duration) -> u64 { @@ -5841,6 +5932,7 @@ mod fastly_impl { #[test] fn backend_identity_uses_every_canonical_property() { let first = BackendIdentity { + client_identity: None, phase_ms: 128, connect_ms: None, host: "example.com".to_owned(), @@ -5849,9 +5941,11 @@ mod fastly_impl { tls: true, wire_authority: "example.com".to_owned(), }; + // v2 adds the client identity to the hashed key. Without one, the hashed bytes are + // unchanged, so only the version prefix moved from ez_b31v1_. assert_eq!( backend_name(&first), - "ez_b31v1_a165932b532b7ff063ee219444cb3cb093847ee427d4f76b54a68909b2e279fc" + "ez_b31v2_a165932b532b7ff063ee219444cb3cb093847ee427d4f76b54a68909b2e279fc" ); let mut second = first.clone(); second.phase_ms = 256; @@ -5873,6 +5967,89 @@ mod fastly_impl { assert_ne!(backend_name(&first), backend_name(&second)); } + #[test] + fn identity_without_a_runtime_binding_fails_before_backend_registration() { + use edgezero_core::manifest::ManifestLoader; + use edgezero_core::outbound::{ + ClientIdentityError, ClientIdentityMaterial, ClientIdentityName, + }; + let manifest = ManifestLoader::load_from_str( + "[capabilities.outbound.client-identities.mtls]\n\ + [stores.config]\nids = [\"absent_config\"]\n\ + [stores.secrets]\nids = [\"absent_secrets\"]\n", + ); + let policy = Arc::new(ClientIdentityPolicy::from_manifest(manifest.manifest())); + let time = native_time(MonotonicClock::default()); + let request = OutboundRequest::get("https://pbs.example/auction") + .expect("request") + .client_identity(ClientIdentityName::new("mtls").expect("name")); + let dispatch = testing::dispatch_with_policy(request, time.clone(), policy); + let Err(error) = FastlyOutboundClient::with_time(time).configure(dispatch) else { + panic!("a missing binding must fail before registration"); + }; + assert_eq!( + error.client_identity_error(), + Some(&ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Store + }) + ); + } + + #[test] + fn backend_name_covers_the_client_identity_and_whole_chain() { + let request = OutboundRequest::get("https://pbs.example/").expect("request"); + let budget = clock_budget(MonotonicInstant::now(), Duration::from_secs(1)); + let (plain, _) = backend_identity(request, budget).expect("identity"); + let mut identified = plain.clone(); + identified.client_identity = Some(("mtls".to_owned(), [1_u8; 32])); + assert_ne!(backend_name(&plain), backend_name(&identified)); + + let same = identified.clone(); + assert_eq!(backend_name(&identified), backend_name(&same)); + + let mut other_name = identified.clone(); + other_name.client_identity = Some(("other".to_owned(), [1_u8; 32])); + assert_ne!(backend_name(&identified), backend_name(&other_name)); + + let mut rotated = identified.clone(); + rotated.client_identity = Some(("mtls".to_owned(), [2_u8; 32])); + assert_ne!(backend_name(&identified), backend_name(&rotated)); + } + + #[test] + fn changed_chain_registers_a_new_backend_in_a_warm_registry() { + let start = MonotonicInstant::now(); + let budget = clock_budget(start, Duration::from_secs(1)); + let clock = constant_clock(start); + let request = OutboundRequest::get("https://pbs.example/").expect("request"); + let (mut identity, _) = backend_identity(request, budget).expect("identity"); + identity.client_identity = Some(("mtls".to_owned(), [1_u8; 32])); + let registry = Mutex::new(HashMap::new()); + let registered = RefCell::new(Vec::new()); + let register = |settings: &BackendIdentity| { + cached_backend( + ®istry, + settings.clone(), + budget, + &clock, + None, + |name, _| { + registered.borrow_mut().push(name.to_owned()); + Ok(Ok(name.to_owned())) + }, + ) + .expect("backend") + }; + let first = register(&identity); + assert_eq!(register(&identity), first, "a warm backend is reused"); + let mut rotated = identity.clone(); + rotated.client_identity = Some(("mtls".to_owned(), [2_u8; 32])); + let second = register(&rotated); + assert_ne!(second, first); + assert_eq!(registered.borrow().clone(), [first.clone(), second]); + assert!(registry.lock().expect("registry").contains_key(&first)); + } + #[test] fn backend_authority_preserves_explicit_port() { let mut request = @@ -6995,11 +7172,38 @@ pub use fastly_impl::{DYNAMIC_BACKENDS_DISABLED_MESSAGE, FastlyOutboundClient}; #[cfg(feature = "fastly")] pub(crate) use fastly_impl::{drive_callback, native_time}; +/// Identity responses are never cached: Fastly's default cache key is the URL and +/// `Host`, without the backend or certificate, so a cached identity response could +/// reach a request without the identity. +#[cfg(any(feature = "fastly", test))] +fn effective_cache_policy( + has_client_identity: bool, + requested: OutboundCachePolicy, +) -> OutboundCachePolicy { + if has_client_identity { + OutboundCachePolicy::Bypass + } else { + requested + } +} + #[cfg(any(feature = "fastly", feature = "test-utils"))] fn validate_supported_options( request: &OutboundRequest, mode: OutboundSendMode, ) -> Result<(), EdgeError> { + if let Some(name) = request.client_identity_name() + && (request.image_optimizer_options().is_some() + || matches!( + request.cache_policy_setting(), + OutboundCachePolicy::PlatformDefaultWithSurrogateKey(_) + )) + { + return Err(EdgeError::client_identity( + name, + ClientIdentityError::Unsupported { adapter: "fastly" }, + )); + } if request.image_optimizer_options().is_some() && matches!(mode, OutboundSendMode::Batch | OutboundSendMode::Begin) { @@ -7068,6 +7272,66 @@ mod send_failure_policy_tests { } } + #[test] + #[cfg(any(feature = "fastly", feature = "test-utils"))] + fn client_identity_rejects_optimizer_and_surrogate_keys_in_every_mode() { + use edgezero_core::http::HeaderValue; + use edgezero_core::{ClientIdentityName, OutboundImageOptimizerOptions}; + let identified = || { + OutboundRequest::get("https://pbs.example/auction") + .expect("request") + .client_identity(ClientIdentityName::new("mtls").expect("name")) + }; + let unsupported = [ + identified().image_optimizer(OutboundImageOptimizerOptions::new()), + identified().cache_policy(OutboundCachePolicy::PlatformDefaultWithSurrogateKey( + HeaderValue::from_static("auction"), + )), + ]; + let modes = [ + OutboundSendMode::Send, + OutboundSendMode::Follow, + OutboundSendMode::Begin, + OutboundSendMode::Batch, + ]; + for request in &unsupported { + for mode in modes { + let error = validate_supported_options(request, mode).expect_err("unsupported"); + assert_eq!( + error.client_identity_error(), + Some(&ClientIdentityError::Unsupported { adapter: "fastly" }) + ); + } + } + for policy in [ + OutboundCachePolicy::PlatformDefault, + OutboundCachePolicy::Bypass, + ] { + let request = identified().cache_policy(policy); + for mode in modes { + validate_supported_options(&request, mode).expect("identity with plain caching"); + } + } + } + + #[test] + fn client_identity_requests_always_bypass_the_cache() { + use edgezero_core::http::HeaderValue; + let tagged = + OutboundCachePolicy::PlatformDefaultWithSurrogateKey(HeaderValue::from_static("tag")); + for requested in [ + OutboundCachePolicy::PlatformDefault, + OutboundCachePolicy::Bypass, + tagged.clone(), + ] { + assert_eq!( + effective_cache_policy(true, requested.clone()), + OutboundCachePolicy::Bypass + ); + assert_eq!(effective_cache_policy(false, requested.clone()), requested); + } + } + fn scripted_optimizer_return( duration: Duration, cause: BudgetSource, diff --git a/crates/edgezero-adapter-fastly/src/outbound/client_identity.rs b/crates/edgezero-adapter-fastly/src/outbound/client_identity.rs new file mode 100644 index 000000000..848e0ae11 --- /dev/null +++ b/crates/edgezero-adapter-fastly/src/outbound/client_identity.rs @@ -0,0 +1,262 @@ +//! Fastly client-identity binding. +//! +//! The certificate chain and hosts list live in the identity's config store, +//! which has no per-request read limit. Only the private key lives in its +//! Secret Store, opened as a handle and never read as plaintext. The config half +//! is resolved at most once per inbound request; the key is opened only when a +//! backend has to be registered. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard}; + +use edgezero_core::error::EdgeError; +use edgezero_core::outbound::{ + ClientCertificateChain, ClientIdentityError, ClientIdentityHosts, ClientIdentityMaterial, + ClientIdentityMetadata, ClientIdentityPolicy, +}; + +#[cfg(feature = "fastly")] +use crate::chunked_config::{SyncHostCallError, run_sync_host_call}; +#[cfg(feature = "fastly")] +use crate::config_store::FastlyConfigStore; +#[cfg(feature = "fastly")] +use edgezero_core::config_store::ConfigStoreError; +#[cfg(feature = "fastly")] +use edgezero_core::{Deadline, MonotonicClock}; +#[cfg(feature = "fastly")] +use fastly::secret_store::{Secret, SecretStore}; + +/// Longest accepted certificate entry, Fastly's config value limit. +pub(super) const MAX_CERTIFICATE_BYTES: u64 = 8_000; +/// Longest accepted hosts entry. +pub(super) const MAX_HOSTS_BYTES: u64 = 4_000; + +/// The config-store half of a binding, shared by every dispatch in one inbound request. +#[derive(Clone, Debug)] +pub(super) struct ConfigBinding { + pub chain: ClientCertificateChain, + pub hosts: ClientIdentityHosts, +} + +/// Why one config entry could not be read. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum ConfigReadError { + DeadlineExceeded, + StoreMissing, + TooLarge, + Unavailable, +} + +/// Why a binding could not be resolved. +#[derive(Debug)] +pub(super) enum BindingFailure { + /// The read deadline expired; never cached. + DeadlineExceeded, + /// Determined by the stored data; cached for the rest of the inbound request. + Material(ClientIdentityError), + /// The store could not be reached; never cached. + Unavailable, +} + +/// Reads one config entry of at most `limit` bytes from a logical config store. +pub(super) trait ConfigEntryReader { + fn read(&self, store: &str, key: &str, limit: u64) -> Result, ConfigReadError>; +} + +type BindingEntries = HashMap, ClientIdentityError>>; + +/// Bindings resolved during one inbound request, keyed by identity name. +#[derive(Debug, Default)] +pub(super) struct BindingCache { + entries: Mutex, +} + +impl BindingCache { + fn lock(&self) -> Result, BindingFailure> { + self.entries + .lock() + .map_err(|_poisoned| BindingFailure::Unavailable) + } + + /// Returns the identity's config binding, reading it on first use in this request. + pub(super) fn resolve( + &self, + metadata: &ClientIdentityMetadata, + policy: &ClientIdentityPolicy, + reader: &dyn ConfigEntryReader, + ) -> Result, BindingFailure> { + let key = metadata.name().as_str(); + if let Some(cached) = self.lock()?.get(key) { + return cached.clone().map_err(BindingFailure::Material); + } + let loaded = load_config_binding(metadata, policy, reader); + let cacheable = match &loaded { + Ok(binding) => Some(Ok(Arc::clone(binding))), + Err(BindingFailure::Material(reason)) => Some(Err(reason.clone())), + Err(BindingFailure::DeadlineExceeded | BindingFailure::Unavailable) => None, + }; + if let Some(entry) = cacheable { + self.lock()?.insert(key.to_owned(), entry); + } + loaded + } +} + +/// Config key of the identity's certificate chain. +pub(super) fn certificate_key(metadata: &ClientIdentityMetadata) -> String { + format!("{}.certificate", metadata.name()) +} + +/// Config key of the identity's hosts list. +pub(super) fn hosts_key(metadata: &ClientIdentityMetadata) -> String { + format!("{}.hosts", metadata.name()) +} + +fn load_config_binding( + metadata: &ClientIdentityMetadata, + policy: &ClientIdentityPolicy, + reader: &dyn ConfigEntryReader, +) -> Result, BindingFailure> { + let store = metadata.config_store().ok_or(BindingFailure::Material( + ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Store, + }, + ))?; + let hosts_text = read_entry( + reader, + store, + &hosts_key(metadata), + MAX_HOSTS_BYTES, + ClientIdentityMaterial::Hosts, + )?; + let pem = read_entry( + reader, + store, + &certificate_key(metadata), + MAX_CERTIFICATE_BYTES, + ClientIdentityMaterial::Certificate, + )?; + let hosts = + ClientIdentityHosts::parse(&hosts_text, policy).map_err(BindingFailure::Material)?; + let chain = ClientCertificateChain::parse(&pem).map_err(BindingFailure::Material)?; + Ok(Arc::new(ConfigBinding { chain, hosts })) +} + +/// Opens the identity's private key as a Secret Store handle, without plaintext. +/// +/// Called only when a backend must be registered, so a request reusing a +/// registered backend spends no Secret Store read. +#[cfg(feature = "fastly")] +pub(super) fn open_private_key( + metadata: &ClientIdentityMetadata, + clock: &MonotonicClock, + deadline: Deadline, +) -> Result { + let missing = |which| BindingFailure::Material(ClientIdentityError::MaterialMissing { which }); + let alias = metadata + .secret_store() + .ok_or_else(|| missing(ClientIdentityMaterial::Store))?; + let store = run_sync_host_call(clock, deadline, || { + SecretStore::open(alias).map_err(|_error| missing(ClientIdentityMaterial::Store)) + }) + .map_err(sync_failure)?; + let key = format!("{}.private-key", metadata.name()); + let secret = run_sync_host_call(clock, deadline, || { + store + .try_get(&key) + .map_err(|_error| BindingFailure::Unavailable) + }) + .map_err(sync_failure)?; + secret.ok_or_else(|| missing(ClientIdentityMaterial::Key)) +} + +/// Reads binding entries from Fastly config stores under the dispatch deadline. +#[cfg(feature = "fastly")] +pub(super) struct FastlyConfigEntries<'clock> { + pub clock: &'clock MonotonicClock, + pub deadline: Deadline, +} + +#[cfg(feature = "fastly")] +impl ConfigEntryReader for FastlyConfigEntries<'_> { + fn read(&self, store: &str, key: &str, limit: u64) -> Result, ConfigReadError> { + let opened = run_sync_host_call(self.clock, self.deadline, || { + FastlyConfigStore::try_open_optional(store) + }) + .map_err(|error| config_failure(&error))? + .ok_or(ConfigReadError::StoreMissing)?; + run_sync_host_call(self.clock, self.deadline, || opened.read_entry(key, limit)) + .map_err(|error| config_failure(&error)) + } +} + +#[cfg(feature = "fastly")] +fn config_failure(error: &SyncHostCallError) -> ConfigReadError { + match error { + SyncHostCallError::DeadlineExceeded + | SyncHostCallError::Backend(ConfigStoreError::DeadlineExceeded) => { + ConfigReadError::DeadlineExceeded + } + SyncHostCallError::Backend(ConfigStoreError::ValueTooLarge) => ConfigReadError::TooLarge, + SyncHostCallError::Backend( + ConfigStoreError::Internal { .. } + | ConfigStoreError::InvalidKey { .. } + | ConfigStoreError::Unavailable { .. } + | _, + ) => ConfigReadError::Unavailable, + } +} + +#[cfg(feature = "fastly")] +fn sync_failure(error: SyncHostCallError) -> BindingFailure { + match error { + SyncHostCallError::Backend(failure) => failure, + SyncHostCallError::DeadlineExceeded => BindingFailure::DeadlineExceeded, + } +} + +fn read_entry( + reader: &dyn ConfigEntryReader, + store: &str, + key: &str, + limit: u64, + which: ClientIdentityMaterial, +) -> Result { + match reader.read(store, key, limit) { + Ok(Some(value)) => Ok(value), + Ok(None) => Err(BindingFailure::Material( + ClientIdentityError::MaterialMissing { which }, + )), + Err(ConfigReadError::TooLarge) => Err(BindingFailure::Material( + ClientIdentityError::MaterialInvalid { which }, + )), + Err(ConfigReadError::StoreMissing) => Err(BindingFailure::Material( + ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Store, + }, + )), + Err(ConfigReadError::DeadlineExceeded) => Err(BindingFailure::DeadlineExceeded), + Err(ConfigReadError::Unavailable) => Err(BindingFailure::Unavailable), + } +} + +/// Maps a binding failure for `metadata` to the request's error. +pub(super) fn binding_error( + metadata: &ClientIdentityMetadata, + failure: BindingFailure, + timeout: impl FnOnce() -> EdgeError, +) -> EdgeError { + match failure { + BindingFailure::Material(reason) => EdgeError::client_identity(metadata.name(), reason), + BindingFailure::DeadlineExceeded => timeout(), + BindingFailure::Unavailable => EdgeError::client_identity( + metadata.name(), + ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Store, + }, + ), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/edgezero-adapter-fastly/src/outbound/client_identity/tests.rs b/crates/edgezero-adapter-fastly/src/outbound/client_identity/tests.rs new file mode 100644 index 000000000..b6c208d47 --- /dev/null +++ b/crates/edgezero-adapter-fastly/src/outbound/client_identity/tests.rs @@ -0,0 +1,296 @@ +use std::cell::RefCell; +use std::collections::HashMap; + +use edgezero_core::error::EdgeError; +use edgezero_core::http::StatusCode; +use edgezero_core::manifest::ManifestLoader; +use edgezero_core::outbound::{ + ClientIdentityError, ClientIdentityMaterial, ClientIdentityMetadata, ClientIdentityName, + ClientIdentityPolicy, +}; + +use super::{ + BindingCache, BindingFailure, ConfigEntryReader, ConfigReadError, MAX_CERTIFICATE_BYTES, + MAX_HOSTS_BYTES, binding_error, certificate_key, hosts_key, +}; + +const MANIFEST: &str = r#" +[capabilities.outbound.client-identities.mtls] +config-store = "certs" +secret-store = "keys" + +[stores.config] +ids = ["certs"] + +[stores.secrets] +ids = ["keys"] +"#; + +type Entries = HashMap<(String, String), Result, ConfigReadError>>; + +/// A config reader that serves fixed entries and records every read. +struct FakeReader { + entries: Entries, + reads: RefCell>, +} + +impl FakeReader { + fn new( + entries: impl IntoIterator, ConfigReadError>)>, + ) -> Self { + Self { + entries: entries + .into_iter() + .map(|(key, value)| (("certs".to_owned(), key.to_owned()), value)) + .collect(), + reads: RefCell::new(Vec::new()), + } + } + + fn read_count(&self) -> usize { + self.reads.borrow().len() + } +} + +impl ConfigEntryReader for FakeReader { + fn read(&self, store: &str, key: &str, limit: u64) -> Result, ConfigReadError> { + self.reads + .borrow_mut() + .push((store.to_owned(), key.to_owned(), limit)); + self.entries + .get(&(store.to_owned(), key.to_owned())) + .cloned() + .unwrap_or(Ok(None)) + } +} + +fn policy() -> ClientIdentityPolicy { + ClientIdentityPolicy::from_manifest(ManifestLoader::load_from_str(MANIFEST).manifest()) +} + +fn metadata(policy: &ClientIdentityPolicy, name: &str) -> ClientIdentityMetadata { + policy + .identity(&ClientIdentityName::new(name).expect("name")) + .expect("declared") + .clone() +} + +fn certificate() -> String { + "-----BEGIN CERTIFICATE-----\nbGVhZiBkZXI=\n-----END CERTIFICATE-----\n".to_owned() +} + +fn complete() -> FakeReader { + FakeReader::new([ + ("mtls.hosts", Ok(Some("https://pbs.example\n".to_owned()))), + ("mtls.certificate", Ok(Some(certificate()))), + ]) +} + +fn material(failure: BindingFailure) -> ClientIdentityError { + match failure { + BindingFailure::Material(reason) => reason, + BindingFailure::DeadlineExceeded | BindingFailure::Unavailable => { + panic!("expected a material failure, got {failure:?}") + } + } +} + +#[test] +fn entry_names_follow_the_identity_name() { + let policy = policy(); + let identity = metadata(&policy, "mtls"); + assert_eq!(certificate_key(&identity), "mtls.certificate"); + assert_eq!(hosts_key(&identity), "mtls.hosts"); +} + +#[test] +fn binding_is_read_once_per_inbound_request() { + let policy = policy(); + let identity = metadata(&policy, "mtls"); + let reader = complete(); + let cache = BindingCache::default(); + + let first = cache.resolve(&identity, &policy, &reader).expect("binding"); + assert_eq!( + first.hosts.origins().collect::>(), + [("pbs.example", 443)] + ); + assert_eq!( + reader.reads.borrow().clone(), + [ + ("certs".to_owned(), "mtls.hosts".to_owned(), MAX_HOSTS_BYTES), + ( + "certs".to_owned(), + "mtls.certificate".to_owned(), + MAX_CERTIFICATE_BYTES + ), + ] + ); + + let second = cache.resolve(&identity, &policy, &reader).expect("cached"); + assert_eq!( + second.chain.chain_fingerprint(), + first.chain.chain_fingerprint() + ); + assert_eq!(reader.read_count(), 2, "the second dispatch reads nothing"); + + let next_request = BindingCache::default(); + let _reread = next_request + .resolve(&identity, &policy, &reader) + .expect("reread"); + assert_eq!( + reader.read_count(), + 4, + "the next inbound request reads again" + ); +} + +#[test] +fn material_failures_map_and_are_cached() { + let policy = policy(); + let identity = metadata(&policy, "mtls"); + let cases = [ + ( + FakeReader::new([("mtls.certificate", Ok(Some(certificate())))]), + ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Hosts, + }, + ), + ( + FakeReader::new([("mtls.hosts", Ok(Some("https://pbs.example".to_owned())))]), + ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Certificate, + }, + ), + ( + FakeReader::new([ + ("mtls.hosts", Ok(Some("https://pbs.example".to_owned()))), + ("mtls.certificate", Err(ConfigReadError::TooLarge)), + ]), + ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Certificate, + }, + ), + ( + FakeReader::new([("mtls.hosts", Err(ConfigReadError::TooLarge))]), + ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Hosts, + }, + ), + ( + FakeReader::new([ + ("mtls.hosts", Ok(Some("https://*.example".to_owned()))), + ("mtls.certificate", Ok(Some(certificate()))), + ]), + ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Hosts, + }, + ), + ( + FakeReader::new([ + ("mtls.hosts", Ok(Some("https://pbs.example".to_owned()))), + ("mtls.certificate", Ok(Some("not a certificate".to_owned()))), + ]), + ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Certificate, + }, + ), + ( + FakeReader::new([("mtls.hosts", Err(ConfigReadError::StoreMissing))]), + ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Store, + }, + ), + ]; + for (reader, expected) in cases { + let cache = BindingCache::default(); + let failure = cache + .resolve(&identity, &policy, &reader) + .expect_err("material failure"); + assert_eq!(material(failure), expected); + let reads = reader.read_count(); + let again = cache + .resolve(&identity, &policy, &reader) + .expect_err("cached failure"); + assert_eq!(material(again), expected); + assert_eq!(reader.read_count(), reads, "{expected:?} is cached"); + } +} + +#[test] +fn deadline_and_unavailable_reads_are_not_cached() { + let policy = policy(); + let identity = metadata(&policy, "mtls"); + for transient in [ + ConfigReadError::DeadlineExceeded, + ConfigReadError::Unavailable, + ] { + let reader = FakeReader::new([("mtls.hosts", Err(transient))]); + let cache = BindingCache::default(); + let failure = cache + .resolve(&identity, &policy, &reader) + .expect_err("transient"); + assert!( + !matches!(failure, BindingFailure::Material(_)), + "{failure:?}" + ); + let _retry = cache + .resolve(&identity, &policy, &reader) + .expect_err("still transient"); + assert_eq!(reader.read_count(), 2, "{transient:?} is read again"); + } +} + +#[test] +fn identity_without_a_config_store_is_missing_its_store() { + let policy = ClientIdentityPolicy::from_manifest( + ManifestLoader::load_from_str("[capabilities.outbound.client-identities.storeless]\n") + .manifest(), + ); + let identity = metadata(&policy, "storeless"); + let reader = complete(); + let failure = BindingCache::default() + .resolve(&identity, &policy, &reader) + .expect_err("no store"); + assert_eq!( + material(failure), + ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Store + } + ); + assert_eq!(reader.read_count(), 0); +} + +#[test] +fn binding_failures_become_request_errors() { + let policy = policy(); + let identity = metadata(&policy, "mtls"); + let timeout = || EdgeError::gateway_timeout("deadline"); + + let error = binding_error( + &identity, + BindingFailure::Material(ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Key, + }), + timeout, + ); + assert_eq!(error.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + error.client_identity_error(), + Some(&ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Key + }) + ); + + let deadline = binding_error(&identity, BindingFailure::DeadlineExceeded, timeout); + assert_eq!(deadline.status(), StatusCode::GATEWAY_TIMEOUT); + assert!(deadline.client_identity_error().is_none()); + + let unavailable = binding_error(&identity, BindingFailure::Unavailable, timeout); + assert_eq!( + unavailable.client_identity_error(), + Some(&ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Store + }) + ); +} diff --git a/crates/edgezero-adapter-fastly/src/outbound/testing.rs b/crates/edgezero-adapter-fastly/src/outbound/testing.rs index b5d20cec6..4324fa372 100644 --- a/crates/edgezero-adapter-fastly/src/outbound/testing.rs +++ b/crates/edgezero-adapter-fastly/src/outbound/testing.rs @@ -5,11 +5,15 @@ use futures_util::future::pending; use std::cell::RefCell; use std::iter::repeat_with; use std::rc::Rc; +#[cfg(feature = "fastly")] +use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; #[cfg(any(feature = "fastly", feature = "test-utils"))] use std::task::{Context, Waker}; use std::time::Duration; +#[cfg(feature = "fastly")] +use edgezero_core::ClientIdentityPolicy; use edgezero_core::http::HeaderValue; use edgezero_core::{ Deadline, EdgeError, HttpClient, IndependentOutboundProgress, MonotonicClock, MonotonicInstant, @@ -123,6 +127,30 @@ pub(super) fn scripted( HttpClient::with_client(capture) } +/// Like [`dispatch`], through a client that carries a client identity policy. +#[cfg(feature = "fastly")] +pub(super) fn dispatch_with_policy( + request: OutboundRequest, + time: OutboundTime, + policy: Arc, +) -> OutboundDispatchRequest { + let mut future = HttpClient::with_client(Capture::new(time, CaptureMode::Dispatch)) + .with_client_identity_policy(policy) + .send(request); + assert!( + future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + .is_pending() + ); + DISPATCH.with(|saved| { + saved + .borrow_mut() + .take() + .expect("facade dispatched test request") + }) +} + #[cfg(any(feature = "fastly", feature = "test-utils"))] pub(super) fn dispatch(request: OutboundRequest, time: OutboundTime) -> OutboundDispatchRequest { let mut future = diff --git a/crates/edgezero-adapter-spin/src/cli.rs b/crates/edgezero-adapter-spin/src/cli.rs index ff00d80fd..a5e723c55 100644 --- a/crates/edgezero-adapter-spin/src/cli.rs +++ b/crates/edgezero-adapter-spin/src/cli.rs @@ -1498,6 +1498,10 @@ mod tests { CapabilitySupport::Native, ), (Capability::OutboundCacheBypass, CapabilitySupport::Native), + ( + Capability::OutboundClientIdentity, + CapabilitySupport::Unsupported, + ), ( Capability::OutboundImageOptimizer, CapabilitySupport::Unsupported, diff --git a/crates/edgezero-adapter-spin/src/outbound.rs b/crates/edgezero-adapter-spin/src/outbound.rs index 15a4d2bcf..431ce8606 100644 --- a/crates/edgezero-adapter-spin/src/outbound.rs +++ b/crates/edgezero-adapter-spin/src/outbound.rs @@ -39,7 +39,9 @@ mod head; #[cfg(any(test, all(feature = "spin", target_arch = "wasm32")))] mod scheduling; #[cfg(any(feature = "test-utils", all(feature = "spin", target_arch = "wasm32")))] -use edgezero_core::outbound::{OutboundRequest, OutboundSendMode, validate_for_dispatch}; +use edgezero_core::outbound::{ + ClientIdentityError, OutboundRequest, OutboundSendMode, validate_for_dispatch, +}; #[cfg(all(feature = "spin", any(feature = "test-utils", target_arch = "wasm32")))] use edgezero_core::error::{BadGatewayReason, BudgetSource}; @@ -1531,6 +1533,12 @@ fn validate_batch_request(request: &OutboundRequest) -> Result<(), EdgeError> { #[cfg(any(feature = "test-utils", all(feature = "spin", target_arch = "wasm32")))] fn validate_request(request: &OutboundRequest, mode: OutboundSendMode) -> Result<(), EdgeError> { + if let Some(name) = request.client_identity_name() { + return Err(EdgeError::client_identity( + name, + ClientIdentityError::Unsupported { adapter: "spin" }, + )); + } if request.image_optimizer_options().is_some() { return Err(EdgeError::bad_request( "image_optimizer is not supported by spin", @@ -1568,6 +1576,25 @@ mod exchange_tests { request_timeouts, run_exchange, settle_reset_content, should_emit_response_chunk, }; + #[cfg(feature = "test-utils")] + #[test] + fn client_identity_is_unsupported_in_every_mode() { + let request = edgezero_core::OutboundRequest::get("https://origin.example.com/mtls") + .expect("request") + .client_identity(edgezero_core::ClientIdentityName::new("mtls").expect("name")); + for mode in [ + edgezero_core::OutboundSendMode::Send, + edgezero_core::OutboundSendMode::Begin, + edgezero_core::OutboundSendMode::Batch, + ] { + let error = super::validate_request(&request, mode).expect_err("unsupported"); + assert_eq!( + error.client_identity_error(), + Some(&edgezero_core::ClientIdentityError::Unsupported { adapter: "spin" }) + ); + } + } + #[cfg(feature = "test-utils")] #[test] fn tagged_default_is_an_accepted_cache_noop() { diff --git a/crates/edgezero-adapter/src/registry.rs b/crates/edgezero-adapter/src/registry.rs index cfb8f90f4..ae87b1b1f 100644 --- a/crates/edgezero-adapter/src/registry.rs +++ b/crates/edgezero-adapter/src/registry.rs @@ -2,6 +2,7 @@ use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use std::sync::{LazyLock, PoisonError, RwLock}; +use edgezero_core::manifest::Manifest; use edgezero_core::{Capability, CapabilitySupport, PlatformMetadata}; static REGISTRY: LazyLock>> = @@ -793,6 +794,19 @@ pub trait Adapter: Sync + Send { Ok(()) } + /// Reject manifest client identities this adapter cannot bind. + /// + /// Runs in the same CLI step that enforces required capabilities, with the + /// verified manifest. Adapters that read an identity's binding from stores + /// check here that those stores resolve. Default: no checks. + /// + /// # Errors + /// Returns a human-readable error naming each identity the adapter cannot bind. + #[inline] + fn validate_client_identities(&self, _manifest: &Manifest) -> Result<(), String> { + Ok(()) + } + /// Validate the final config key selected by CLI and environment precedence /// before config push or diff performs provider I/O. /// diff --git a/crates/edgezero-cli/src/adapter.rs b/crates/edgezero-cli/src/adapter.rs index d9c0a029a..87a3b5a10 100644 --- a/crates/edgezero-cli/src/adapter.rs +++ b/crates/edgezero-cli/src/adapter.rs @@ -502,7 +502,7 @@ pub(crate) fn ensure_capabilities( ), } } - Ok(()) + adapter.validate_client_identities(verified_manifest) } fn produces_current_runtime(action: Action) -> bool { @@ -864,7 +864,8 @@ mod tests { Adapter, AdapterAction, AdapterExecutionTarget, register_adapter, }; use edgezero_core::manifest::{ - Capability, CapabilitySupport, ManifestContract, ManifestLoader, ResolvedEnvironmentBinding, + Capability, CapabilitySupport, Manifest, ManifestContract, ManifestLoader, + ResolvedEnvironmentBinding, }; use edgezero_core::test_env::EnvOverride; use std::env; @@ -889,6 +890,7 @@ mod tests { name: "gate-native", support: CapabilitySupport::Native, }; + static IDENTITY_GATE_ADAPTER: IdentityGateAdapter = IdentityGateAdapter; static UNSUPPORTED_ADAPTER: GateAdapter = GateAdapter { name: "gate-unsupported", support: CapabilitySupport::Unsupported, @@ -899,6 +901,35 @@ mod tests { support: CapabilitySupport, } + /// Rejects any manifest that declares a client identity. + struct IdentityGateAdapter; + + #[expect( + clippy::missing_trait_methods, + reason = "identity-gate fixture overrides only the relevant trait methods" + )] + impl Adapter for IdentityGateAdapter { + fn capability(&self, _capability: Capability) -> CapabilitySupport { + CapabilitySupport::Native + } + + fn execute(&self, _action: AdapterAction, _args: &[String]) -> Result<(), String> { + Ok(()) + } + + fn name(&self) -> &'static str { + "gate-identity" + } + + fn validate_client_identities(&self, manifest: &Manifest) -> Result<(), String> { + if manifest.capabilities.outbound.client_identities.is_empty() { + Ok(()) + } else { + Err("fixture rejects client identities".to_owned()) + } + } + } + struct EnvironmentAdapter; #[expect( @@ -1223,6 +1254,31 @@ mod tests { } } + #[test] + fn capability_gate_runs_adapter_client_identity_validation() { + register_adapter(&IDENTITY_GATE_ADAPTER); + let without = capability_manifest("required = [\"outbound-http\"]"); + assert_eq!( + ensure_capabilities( + "gate-identity", + ManifestContract::from_opt(Some(without.manifest())) + ), + Ok(()) + ); + + let with = ManifestLoader::load_from_str( + "[capabilities]\noptional = [\"outbound-client-identity\"]\n\ + [capabilities.outbound.client-identities.mtls]\n[adapters.gate]\n", + ); + assert_eq!( + ensure_capabilities( + "gate-identity", + ManifestContract::from_opt(Some(with.manifest())) + ), + Err("fixture rejects client identities".to_owned()) + ); + } + #[test] fn capability_gate_fails_closed_for_malformed_contract() { let result = ensure_capabilities( diff --git a/crates/edgezero-core/Cargo.toml b/crates/edgezero-core/Cargo.toml index d5fadb179..73c66da50 100644 --- a/crates/edgezero-core/Cargo.toml +++ b/crates/edgezero-core/Cargo.toml @@ -40,6 +40,7 @@ serde_json = { workspace = true } serde_path_to_error = { workspace = true } serde_urlencoded = { workspace = true } base16ct = { workspace = true } +base64 = { workspace = true } sha2 = { workspace = true } thiserror = { workspace = true } toml = { workspace = true } diff --git a/crates/edgezero-core/src/app.rs b/crates/edgezero-core/src/app.rs index 702cf6a40..c9cbbd42f 100644 --- a/crates/edgezero-core/src/app.rs +++ b/crates/edgezero-core/src/app.rs @@ -19,6 +19,7 @@ use crate::ingress::{ use crate::key_value_store::KvError; use crate::logging::BOOT_LOG_TARGET; use crate::manifest::{BakedManifest, ResolvedLoggingConfig}; +use crate::outbound::{ClientIdentityPolicy, HttpClient}; use crate::platform::PlatformMetadata; use crate::record_store::{RecordKeyLayout, RecordLayout, RecordStoreRequirements}; use crate::response_egress::{ @@ -62,6 +63,7 @@ pub enum FrameworkErrorDetail { /// Lightweight container around a `RouterService` that can be extended via hook implementations. pub struct App { admitted_error_response_finalizer: Option, + client_identity_policy: Arc, config_extraction_limits: ConfigExtractionLimits, detached_response_egress_decision_factory: DetachedResponseEgressDecisionFactory, error_response_renderer: ErrorResponseRenderer, @@ -223,6 +225,14 @@ impl App { Self::from_router::(A::routes()?, platform) } + /// Declared client identities and the outbound allowlist, built once from the + /// baked manifest. Dispatch attaches it to each request's `HttpClient`. + #[must_use] + #[inline] + pub fn client_identity_policy(&self) -> &Arc { + &self.client_identity_policy + } + #[must_use] #[inline] pub fn config_extraction_limits(&self) -> ConfigExtractionLimits { @@ -361,11 +371,14 @@ impl App { async fn dispatch_admitted_with_request_facts( &self, prepared: PreparedIngress, - request: Request, + mut request: Request, detail: FrameworkErrorDetail, geo: GeoOutcome, client_info: Option, ) -> ResponseEgressEnvelope { + if let Some(client) = request.extensions_mut().get_mut::() { + client.attach_client_identity_policy(&self.client_identity_policy); + } let request_method = request.method().clone(); let request_start = prepared.request_start(); let route = prepared.route_metadata().cloned(); @@ -498,6 +511,7 @@ impl App { A: Hooks, { let mut app = Self::with_name_and_platform(router, A::name(), platform); + app.client_identity_policy = Arc::new(ClientIdentityPolicy::from_baked(A::manifest())); A::configure(&mut app)?; if app.platform() != platform { return Err(EdgeError::internal(anyhow::anyhow!( @@ -866,6 +880,7 @@ impl App { { Self { admitted_error_response_finalizer: None, + client_identity_policy: Arc::new(ClientIdentityPolicy::default()), config_extraction_limits: ConfigExtractionLimits::default(), detached_response_egress_decision_factory: Arc::new(|head| { DetachedResponseEgressDecision::Send { diff --git a/crates/edgezero-core/src/context.rs b/crates/edgezero-core/src/context.rs index 22a5939e6..901ed6e55 100644 --- a/crates/edgezero-core/src/context.rs +++ b/crates/edgezero-core/src/context.rs @@ -21,7 +21,7 @@ use crate::http::{ }; use crate::ingress::{AdmittedIngress, IngressGrant, RequestIngress}; use crate::ja4::CapturedJa4; -use crate::outbound::{ForwardedReadDeadline, HttpClient}; +use crate::outbound::{ClientIdentityError, ForwardedReadDeadline, HttpClient}; use crate::params::PathParams; use crate::router::RouteMetadata; use crate::store_registry::{ @@ -178,6 +178,7 @@ impl InputGuard { enum StoredError { BadGateway(String, BadGatewayReason, Option), BadRequest(String, Option), + ClientIdentity(String, ClientIdentityError), ConfigOutOfDate(String, String), GatewayTimeout(String, BudgetSource, Option), Internal(String, Option), @@ -242,6 +243,9 @@ impl StoredError { message, field_path, } => Self::StoreExtraction(*reason, message.clone(), field_path.clone()), + EdgeError::ClientIdentity { name, reason } => { + Self::ClientIdentity(name.clone(), reason.clone()) + } EdgeError::UriTooLong { message } => Self::UriTooLong(message.clone()), EdgeError::Validation { message } => Self::Validation(message.clone()), } @@ -292,6 +296,10 @@ impl StoredError { Self::StoreExtraction(reason, message, field_path) => { EdgeError::store_extraction(*reason, message.clone(), field_path.clone()) } + Self::ClientIdentity(name, reason) => EdgeError::ClientIdentity { + name: name.clone(), + reason: reason.clone(), + }, Self::UriTooLong(message) => EdgeError::uri_too_long(message.clone()), Self::Validation(message) => EdgeError::validation(message.clone()), } diff --git a/crates/edgezero-core/src/error.rs b/crates/edgezero-core/src/error.rs index 7801efc78..b5e15382d 100644 --- a/crates/edgezero-core/src/error.rs +++ b/crates/edgezero-core/src/error.rs @@ -11,6 +11,7 @@ use crate::http::{ HeaderMap, HeaderValue, Method, Response, StatusCode, header::{ALLOW, CONTENT_TYPE, RETRY_AFTER}, }; +use crate::outbound::{ClientIdentityError, ClientIdentityName}; use crate::response::{IntoResponse, response_with_body}; use crate::response_egress_framing::ResponseEgressFramingError; @@ -156,6 +157,13 @@ pub enum EdgeError { message: String, provider_detail: Option, }, + /// A request that selects a client identity was refused before network I/O. + /// The reason chooses the HTTP status. + #[error("client identity `{name}`: {reason}")] + ClientIdentity { + name: String, + reason: ClientIdentityError, + }, /// The blob's `data` shape disagrees with the deployed `C` /// type. Re-running ` config push` for the deployed /// code revision fixes it. HTTP 503, kind @@ -285,6 +293,41 @@ impl EdgeError { } } + /// A client-identity refusal. + #[inline] + #[must_use] + pub fn client_identity(name: &ClientIdentityName, reason: ClientIdentityError) -> Self { + Self::ClientIdentity { + name: name.as_str().to_owned(), + reason, + } + } + + /// The client-identity reason, when this error refused an identity request. + #[inline] + #[must_use] + pub fn client_identity_error(&self) -> Option<&ClientIdentityError> { + match self { + Self::ClientIdentity { reason, .. } => Some(reason), + Self::BadGateway { .. } + | Self::BadRequest { .. } + | Self::ConfigOutOfDate { .. } + | Self::GatewayTimeout { .. } + | Self::Internal { .. } + | Self::MethodNotAllowed { .. } + | Self::NotFound { .. } + | Self::NotImplemented { .. } + | Self::PayloadTooLarge { .. } + | Self::RequestHeaderFieldsTooLarge { .. } + | Self::RequestTimeout { .. } + | Self::ResponseTooLarge { .. } + | Self::ServiceUnavailable { .. } + | Self::StoreExtraction { .. } + | Self::UriTooLong { .. } + | Self::Validation { .. } => None, + } + } + /// Construct from an explicit `(message, field_path)` pair. /// Used by the secret walk and validator paths. `field_path` /// SHOULD be a dotted path naming the offending field; pass @@ -365,6 +408,7 @@ impl EdgeError { | EdgeError::RequestTimeout { .. } | EdgeError::ResponseTooLarge { .. } | EdgeError::MethodNotAllowed { .. } + | EdgeError::ClientIdentity { .. } | EdgeError::StoreExtraction { .. } | EdgeError::UriTooLong { .. } | EdgeError::Validation { .. } @@ -425,6 +469,7 @@ impl EdgeError { | EdgeError::RequestTimeout { .. } | EdgeError::ResponseTooLarge { .. } | EdgeError::ServiceUnavailable { .. } + | EdgeError::ClientIdentity { .. } | EdgeError::StoreExtraction { .. } | EdgeError::UriTooLong { .. } | EdgeError::Validation { .. } => None, @@ -478,6 +523,7 @@ impl EdgeError { EdgeError::ResponseTooLarge { .. } => "response_too_large", EdgeError::ServiceUnavailable { .. } => "service_unavailable", EdgeError::StoreExtraction { reason, .. } => reason.wire_kind(), + EdgeError::ClientIdentity { reason, .. } => reason.wire_kind(), EdgeError::UriTooLong { .. } => "uri_too_long", EdgeError::Validation { .. } => "validation", } @@ -508,6 +554,9 @@ impl EdgeError { } EdgeError::Internal { source, .. } => format!("internal error: {source}"), EdgeError::PayloadTooLarge { .. } => "request body too large".to_owned(), + EdgeError::ClientIdentity { name, reason } => { + format!("client identity `{name}`: {reason}") + } } } @@ -574,6 +623,7 @@ impl EdgeError { | Self::RequestTimeout { .. } | Self::ResponseTooLarge { .. } | Self::ServiceUnavailable { .. } + | Self::ClientIdentity { .. } | Self::StoreExtraction { .. } | Self::UriTooLong { .. } | Self::Validation { .. } => None, @@ -688,6 +738,7 @@ impl EdgeError { EdgeError::NotImplemented { .. } => StatusCode::NOT_IMPLEMENTED, EdgeError::PayloadTooLarge { .. } => StatusCode::PAYLOAD_TOO_LARGE, EdgeError::StoreExtraction { reason, .. } => reason.wire_status(), + EdgeError::ClientIdentity { reason, .. } => reason.wire_status(), EdgeError::UriTooLong { .. } => StatusCode::URI_TOO_LONG, EdgeError::Internal { .. } => StatusCode::INTERNAL_SERVER_ERROR, } @@ -737,6 +788,7 @@ impl EdgeError { Self::StoreExtraction { reason, .. } => Some(*reason), Self::BadGateway { .. } | Self::BadRequest { .. } + | Self::ClientIdentity { .. } | Self::ConfigOutOfDate { .. } | Self::GatewayTimeout { .. } | Self::Internal { .. } @@ -790,6 +842,7 @@ impl EdgeError { | EdgeError::RequestHeaderFieldsTooLarge { .. } | EdgeError::RequestTimeout { .. } | EdgeError::ServiceUnavailable { .. } + | EdgeError::ClientIdentity { .. } | EdgeError::StoreExtraction { .. } | EdgeError::UriTooLong { .. } | EdgeError::Validation { .. } => self.message(), @@ -1355,6 +1408,7 @@ mod tests { | EdgeError::RequestTimeout { .. } | EdgeError::ResponseTooLarge { .. } | EdgeError::ServiceUnavailable { .. } + | EdgeError::ClientIdentity { .. } | EdgeError::StoreExtraction { .. } | EdgeError::UriTooLong { .. } | EdgeError::PayloadTooLarge { .. } diff --git a/crates/edgezero-core/src/lib.rs b/crates/edgezero-core/src/lib.rs index fea81ca13..935176e93 100644 --- a/crates/edgezero-core/src/lib.rs +++ b/crates/edgezero-core/src/lib.rs @@ -94,18 +94,19 @@ pub use manifest::{ canonicalize_outbound_host, }; pub use outbound::{ - ContentTypeIneligibility, ContentTypeProvenance, DEFAULT_MAX_DECODER_BYTES, - DEFAULT_MAX_RESPONSE_BYTES, DEFAULT_OUTBOUND_REQUEST_BODY_BYTES, HttpClient, - IndependentOutboundProgress, OutboundBatch, OutboundBatchAccumulator, OutboundBatchCheck, - OutboundBatchContext, OutboundBatchDriverEvent, OutboundBatchFailure, - OutboundBatchInsertFailure, OutboundBatchItem, OutboundBatchMergeFailure, OutboundBatchNext, - OutboundBatchResults, OutboundBatchTermination, OutboundCachePolicy, OutboundCollectedSlot, - OutboundCropFocus, OutboundDispatchRequest, OutboundExchangeFailure, OutboundExchangeOwner, - OutboundFollowFailure, OutboundFollowResult, OutboundFuture, OutboundHead, - OutboundHeaderFidelity, OutboundHeaderInput, OutboundHttpClient, OutboundImageFormat, - OutboundImageOptimizerOptions, OutboundImageOptimizerRegion, OutboundLocationEvidence, - OutboundPending, OutboundPreparedBatch, OutboundProgressRuntime, OutboundProxyMarker, - OutboundRedirectAction, OutboundRedirectContext, OutboundRedirectLimit, + ClientCertificateChain, ClientIdentityError, ClientIdentityHosts, ClientIdentityMaterial, + ClientIdentityMetadata, ClientIdentityName, ClientIdentityPolicy, ContentTypeIneligibility, + ContentTypeProvenance, DEFAULT_MAX_DECODER_BYTES, DEFAULT_MAX_RESPONSE_BYTES, + DEFAULT_OUTBOUND_REQUEST_BODY_BYTES, HttpClient, IndependentOutboundProgress, OutboundBatch, + OutboundBatchAccumulator, OutboundBatchCheck, OutboundBatchContext, OutboundBatchDriverEvent, + OutboundBatchFailure, OutboundBatchInsertFailure, OutboundBatchItem, OutboundBatchMergeFailure, + OutboundBatchNext, OutboundBatchResults, OutboundBatchTermination, OutboundCachePolicy, + OutboundCollectedSlot, OutboundCropFocus, OutboundDispatchRequest, OutboundExchangeFailure, + OutboundExchangeOwner, OutboundFollowFailure, OutboundFollowResult, OutboundFuture, + OutboundHead, OutboundHeaderFidelity, OutboundHeaderInput, OutboundHttpClient, + OutboundImageFormat, OutboundImageOptimizerOptions, OutboundImageOptimizerRegion, + OutboundLocationEvidence, OutboundPending, OutboundPreparedBatch, OutboundProgressRuntime, + OutboundProxyMarker, OutboundRedirectAction, OutboundRedirectContext, OutboundRedirectLimit, OutboundRedirectStopReason, OutboundRequest, OutboundRequestParts, OutboundResizeFilter, OutboundResponse, OutboundResponseContext, OutboundScope, OutboundScopeKind, OutboundScopeOwner, OutboundSendMode, OutboundSlotResult, OutboundTask, OutboundTime, diff --git a/crates/edgezero-core/src/manifest.rs b/crates/edgezero-core/src/manifest.rs index f849d211c..fb45e495e 100644 --- a/crates/edgezero-core/src/manifest.rs +++ b/crates/edgezero-core/src/manifest.rs @@ -11,6 +11,9 @@ use std::sync::Arc; use std::{env, fs, io}; use validator::{Validate, ValidationError}; +/// Longest accepted client identity name. +pub const MAX_CLIENT_IDENTITY_NAME_LEN: usize = 64; + #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct AtomicHost { pub host: HostPat, @@ -19,6 +22,32 @@ pub struct AtomicHost { } impl AtomicHost { + /// Whether this canonical allowlist entry admits one concrete origin. + /// + /// `host` must already be canonical: lowercase ASCII, with IPv6 literals in + /// brackets as [`canonicalize_outbound_host`] renders them. A wildcard + /// subdomain admits subdomains only, never its apex. + #[inline] + #[must_use] + pub fn permits(&self, scheme: Scheme, host: &str, port: u16) -> bool { + if self.scheme != scheme { + return false; + } + let port_admitted = match self.port { + Port::Any => true, + Port::Exact(exact) => exact == port, + }; + let host_admitted = match &self.host { + HostPat::Any => true, + HostPat::Exact(exact) => exact == host, + HostPat::WildcardSubdomain(suffix) => host + .strip_suffix(suffix.as_str()) + .and_then(|prefix| prefix.strip_suffix('.')) + .is_some_and(|label| !label.is_empty()), + }; + port_admitted && host_admitted + } + fn render_host_and_port(&self, scheme: &str, host: &str) -> String { let mut rendered = format!("{scheme}://{host}"); match self.port { @@ -96,6 +125,8 @@ pub enum Capability { OutboundBatchCompletionOrder, OutboundBatchSlotIsolation, OutboundCacheBypass, + /// Presents a declared TLS client certificate on outbound requests that select it. + OutboundClientIdentity, OutboundCompleteResourceAccounting, OutboundConnectTimeout, OutboundDeadlines, @@ -142,6 +173,7 @@ impl Capability { Self::OutboundBatchCompletionOrder => "outbound-batch-completion-order", Self::OutboundBatchSlotIsolation => "outbound-batch-slot-isolation", Self::OutboundCacheBypass => "outbound-cache-bypass", + Self::OutboundClientIdentity => "outbound-client-identity", Self::OutboundCompleteResourceAccounting => "outbound-complete-resource-accounting", Self::OutboundConnectTimeout => "outbound-connect-timeout", Self::OutboundDeadlines => "outbound-deadlines", @@ -345,6 +377,7 @@ impl ManifestLoader { #[validate(schema(function = "validate_manifest_adapter_keys_case_unique"))] #[validate(schema(function = "validate_manifest_adapter_geo_placement"))] #[validate(schema(function = "validate_manifest_adapter_client_metadata_placement"))] +#[validate(schema(function = "validate_manifest_client_identity_stores"))] #[validate(schema( function = "validate_manifest_fastly_logging", skip_on_field_errors = false @@ -399,11 +432,65 @@ pub struct ManifestCapabilities { #[serde(deny_unknown_fields)] #[non_exhaustive] pub struct ManifestOutboundCapability { + /// Named TLS client identities, keyed by identity name. Only logical store + /// IDs live here; hosts, certificates and keys are bound at runtime. + #[serde( + default, + rename = "client-identities", + skip_serializing_if = "BTreeMap::is_empty" + )] + #[validate(custom(function = "validate_client_identity_names"))] + pub client_identities: BTreeMap, #[serde(default)] #[validate(length(min = 1_u64), custom(function = "validate_outbound_hosts"))] pub hosts: Option>, } +/// One `[capabilities.outbound.client-identities.]` entry. +/// +/// Both stores are optional. An omitted store resolves to that kind's declared +/// default; adapters that read their binding from stores reject an identity +/// whose store cannot be resolved. +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +#[non_exhaustive] +pub struct ClientIdentityDeclaration { + #[serde( + default, + rename = "config-store", + skip_serializing_if = "Option::is_none" + )] + pub config_store: Option, + #[serde( + default, + rename = "secret-store", + skip_serializing_if = "Option::is_none" + )] + pub secret_store: Option, +} + +impl ClientIdentityDeclaration { + /// The logical `[stores.config]` ID this identity reads from, if one resolves. + #[inline] + #[must_use] + pub fn resolved_config_store<'manifest>( + &'manifest self, + stores: &'manifest ManifestStores, + ) -> Option<&'manifest str> { + resolve_identity_store(self.config_store.as_deref(), stores.config.as_ref()) + } + + /// The logical `[stores.secrets]` ID this identity reads from, if one resolves. + #[inline] + #[must_use] + pub fn resolved_secret_store<'manifest>( + &'manifest self, + stores: &'manifest ManifestStores, + ) -> Option<&'manifest str> { + resolve_identity_store(self.secret_store.as_deref(), stores.secrets.as_ref()) + } +} + impl Manifest { /// Look up a `[adapters.]` entry by adapter name, matching /// case-insensitively against the manifest's declared keys. @@ -1220,6 +1307,37 @@ impl serde::Serialize for LogLevel { } } +fn resolve_identity_store<'manifest>( + explicit: Option<&'manifest str>, + declaration: Option<&'manifest StoreDeclaration>, +) -> Option<&'manifest str> { + let stores = declaration?; + match explicit { + Some(id) => stores + .ids + .iter() + .any(|declared| declared == id) + .then_some(id), + None => Some(stores.default_id()).filter(|id| !id.is_empty()), + } +} + +/// Whether `name` is a valid client identity name: 1 to 64 characters of +/// `[a-z0-9-]`, not starting or ending with `-`. +/// +/// Derived entry names such as `.certificate` are then valid Fastly +/// secret names and config keys. +#[inline] +#[must_use] +pub fn is_valid_client_identity_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= MAX_CLIENT_IDENTITY_NAME_LEN + && !name.starts_with('-') + && !name.ends_with('-') + && name + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') +} /// Canonicalizes one outbound host declaration into atomic scheme/host/port entries. /// /// # Errors @@ -1479,6 +1597,66 @@ fn validate_capabilities_disjoint( Ok(()) } +fn validate_client_identity_names( + identities: &BTreeMap, +) -> Result<(), ValidationError> { + if let Some(name) = identities + .keys() + .find(|name| !is_valid_client_identity_name(name)) + { + let mut error = ValidationError::new("client_identity_name"); + error.message = Some( + format!( + "client identity `{name}` must be 1 to {MAX_CLIENT_IDENTITY_NAME_LEN} characters of \ + [a-z0-9-], not starting or ending with `-`" + ) + .into(), + ); + return Err(error); + } + Ok(()) +} + +fn validate_manifest_client_identity_stores(manifest: &Manifest) -> Result<(), ValidationError> { + let stores = &manifest.stores; + for (name, identity) in &manifest.capabilities.outbound.client_identities { + for (kind, explicit, declaration) in [ + ( + "secret-store", + identity.secret_store.as_deref(), + stores.secrets.as_ref(), + ), + ( + "config-store", + identity.config_store.as_deref(), + stores.config.as_ref(), + ), + ] { + let Some(id) = explicit else { continue }; + let declared = declaration.is_some_and(|declared_stores| { + declared_stores.ids.iter().any(|declared| declared == id) + }); + if !declared { + let mut error = ValidationError::new("client_identity_unknown_store"); + error.message = Some( + format!( + "client identity `{name}` names {kind} `{id}`, which is not declared in \ + [stores.{}]", + if kind == "secret-store" { + "secrets" + } else { + "config" + } + ) + .into(), + ); + return Err(error); + } + } + } + Ok(()) +} + fn validate_outbound_hosts(hosts: &[String]) -> Result<(), ValidationError> { for host in hosts { if let Err(error) = canonicalize_outbound_host(host) { @@ -2047,6 +2225,7 @@ required = [ "outbound-batch-completion-order", "outbound-batch-slot-isolation", "outbound-cache-bypass", + "outbound-client-identity", "outbound-complete-resource-accounting", "outbound-connect-timeout", "outbound-deadlines", @@ -2083,6 +2262,7 @@ hosts = ["*", "HTTPS://Example.COM", "api.example.com:8443"] Capability::OutboundBatchCompletionOrder, Capability::OutboundBatchSlotIsolation, Capability::OutboundCacheBypass, + Capability::OutboundClientIdentity, Capability::OutboundCompleteResourceAccounting, Capability::OutboundConnectTimeout, Capability::OutboundDeadlines, @@ -2123,6 +2303,7 @@ hosts = ["*", "HTTPS://Example.COM", "api.example.com:8443"] "outbound-batch-completion-order", "outbound-batch-slot-isolation", "outbound-cache-bypass", + "outbound-client-identity", "outbound-complete-resource-accounting", "outbound-connect-timeout", "outbound-deadlines", @@ -2171,6 +2352,142 @@ hosts = ["*", "HTTPS://Example.COM", "api.example.com:8443"] } } + #[test] + fn client_identities_parse_resolve_and_round_trip() { + let source = r#" +[capabilities.outbound.client-identities.prebid-server] +secret-store = "keys" +config-store = "certs" + +[capabilities.outbound.client-identities.defaulted] + +[stores.secrets] +ids = ["default", "keys"] +default = "default" + +[stores.config] +ids = ["app_config", "certs"] +default = "app_config" +"#; + let loader = ManifestLoader::try_load_from_str(source).expect("identity manifest"); + let manifest = loader.manifest(); + let identities = &manifest.capabilities.outbound.client_identities; + assert_eq!(identities.len(), 2); + + let explicit = &identities["prebid-server"]; + assert_eq!( + explicit.resolved_secret_store(&manifest.stores), + Some("keys") + ); + assert_eq!( + explicit.resolved_config_store(&manifest.stores), + Some("certs") + ); + let defaulted = &identities["defaulted"]; + assert_eq!( + defaulted.resolved_secret_store(&manifest.stores), + Some("default") + ); + assert_eq!( + defaulted.resolved_config_store(&manifest.stores), + Some("app_config") + ); + + let serialized = toml::to_string(manifest).expect("serialize identity manifest"); + let reparsed = ManifestLoader::try_load_from_str(&serialized).expect("round trip"); + assert_eq!( + &reparsed.manifest().capabilities.outbound.client_identities, + identities + ); + } + + #[test] + fn client_identities_need_no_stores_and_stay_out_of_empty_manifests() { + let loader = + ManifestLoader::try_load_from_str("[capabilities.outbound.client-identities.mtls]\n") + .expect("identity without stores"); + let manifest = loader.manifest(); + let identity = &manifest.capabilities.outbound.client_identities["mtls"]; + assert_eq!(identity.resolved_secret_store(&manifest.stores), None); + assert_eq!(identity.resolved_config_store(&manifest.stores), None); + + let without = + ManifestLoader::try_load_from_str("[capabilities.outbound]\nhosts = [\"*\"]\n") + .expect("manifest without identities"); + let serialized = toml::to_string(without.manifest()).expect("serialize"); + assert!( + !serialized.contains("client-identities"), + "an empty identity table must not change serialized manifests: {serialized}" + ); + } + + #[test] + fn client_identities_reject_invalid_names_stores_and_fields() { + let too_long = format!( + "[capabilities.outbound.client-identities.{}]\n", + "a".repeat(MAX_CLIENT_IDENTITY_NAME_LEN + 1) + ); + let invalid = [ + "[capabilities.outbound.client-identities.Upper]\n", + "[capabilities.outbound.client-identities.-lead]\n", + "[capabilities.outbound.client-identities.trail-]\n", + "[capabilities.outbound.client-identities.under_score]\n", + "[capabilities.outbound.client-identities.\"dot.ted\"]\n", + "[capabilities.outbound.client-identities.\"\"]\n", + too_long.as_str(), + "[capabilities.outbound.client-identities.mtls]\nsecret-store = \"missing\"\n\ + [stores.secrets]\nids = [\"default\"]\n", + "[capabilities.outbound.client-identities.mtls]\nsecret-store = \"default\"\n", + "[capabilities.outbound.client-identities.mtls]\nconfig-store = \"missing\"\n\ + [stores.config]\nids = [\"app_config\"]\n", + "[capabilities.outbound.client-identities.mtls]\ncertificate = \"pem\"\n", + "[capabilities.outbound.client-identities.mtls]\nhosts = [\"https://a.example\"]\n", + ]; + for source in invalid { + assert!( + ManifestLoader::try_load_from_str(source).is_err(), + "manifest unexpectedly accepted: {source}" + ); + } + + let longest = "a".repeat(MAX_CLIENT_IDENTITY_NAME_LEN); + for valid in ["a", "prebid-server", "x9", longest.as_str()] { + assert!(is_valid_client_identity_name(valid), "{valid}"); + } + } + + #[test] + fn atomic_host_permits_concrete_origins() { + let entry = |source: &str| { + canonicalize_outbound_host(source) + .expect("allowlist entry") + .remove(0) + }; + + let exact = entry("https://pbs.example.com"); + assert!(exact.permits(Scheme::Https, "pbs.example.com", 443)); + assert!(!exact.permits(Scheme::Https, "pbs.example.com", 8443)); + assert!(!exact.permits(Scheme::Http, "pbs.example.com", 443)); + assert!(!exact.permits(Scheme::Https, "other.example.com", 443)); + + let any_port = entry("https://pbs.example.com:*"); + assert!(any_port.permits(Scheme::Https, "pbs.example.com", 8443)); + + let wildcard = entry("https://*.example.com"); + assert!(wildcard.permits(Scheme::Https, "pbs.example.com", 443)); + assert!(wildcard.permits(Scheme::Https, "a.b.example.com", 443)); + assert!(!wildcard.permits(Scheme::Https, "example.com", 443)); + assert!(!wildcard.permits(Scheme::Https, "badexample.com", 443)); + + let any = entry("https://*:*"); + assert!(any.permits(Scheme::Https, "anything.test", 1)); + assert!(!any.permits(Scheme::Http, "anything.test", 1)); + + let ipv6 = entry("https://[::1]:8443"); + assert!(ipv6.permits(Scheme::Https, "[::1]", 8443)); + assert!(!ipv6.permits(Scheme::Https, "[::2]", 8443)); + } + #[test] fn capability_manifest_rejects_reserved_key_at_every_depth_and_case() { let valid = diff --git a/crates/edgezero-core/src/outbound.rs b/crates/edgezero-core/src/outbound.rs index 4e618d7c9..4e8fbbc40 100644 --- a/crates/edgezero-core/src/outbound.rs +++ b/crates/edgezero-core/src/outbound.rs @@ -4,6 +4,7 @@ )] mod batch; +mod client_identity; mod dispatch; mod exchange; mod head; @@ -63,7 +64,12 @@ pub use batch::{ OutboundBatchMergeFailure, OutboundBatchNext, OutboundBatchResults, OutboundBatchTermination, OutboundCollectedSlot, OutboundPreparedBatch, }; -pub(crate) use dispatch::ForwardedReadDeadline; +pub(crate) use client_identity::is_https; +pub use client_identity::{ + ClientCertificateChain, ClientIdentityError, ClientIdentityHosts, ClientIdentityMaterial, + ClientIdentityMetadata, ClientIdentityName, ClientIdentityPolicy, +}; +pub(crate) use dispatch::{ForwardedReadDeadline, ResolvedClientIdentity}; pub use exchange::OutboundExchangeFailure; pub use redirect::{ OutboundFollowFailure, OutboundFollowResult, OutboundRedirectAction, OutboundRedirectContext, @@ -135,6 +141,7 @@ pub enum OutboundSendMode { /// Providers inspect or consume this value, never construct or reset it. #[derive(Debug)] pub struct OutboundDispatchRequest { + client_identity: Option, context: OutboundResponseContext, request: OutboundRequest, } @@ -309,6 +316,7 @@ pub(crate) struct BudgetInputs { pub struct OutboundRequest { body: Body, cache_policy: OutboundCachePolicy, + client_identity: Option, connect_timeout: Option, deadline: Option, headers: HeaderMap, @@ -342,6 +350,7 @@ pub struct OutboundRequest { pub struct OutboundRequestParts { pub body: Body, pub cache_policy: OutboundCachePolicy, + pub client_identity: Option, pub connect_timeout: Option, pub deadline: Option, pub headers: HeaderMap, @@ -434,6 +443,7 @@ pub enum OutboundCachePolicy { #[derive(Clone)] pub struct HttpClient { + client_identity_policy: Option>, inner: Arc, proxy_marker_enabled: bool, } @@ -611,6 +621,13 @@ impl ResponseHeaderLimiter { } impl HttpClient { + /// Gives this client the app's identity policy unless it already has one. + pub(crate) fn attach_client_identity_policy(&mut self, policy: &Arc) { + if self.client_identity_policy.is_none() { + self.client_identity_policy = Some(Arc::clone(policy)); + } + } + /// Settles permitted GET/HEAD streams, then schedules the complete exchange. /// /// # Errors @@ -638,6 +655,14 @@ impl HttpClient { ) } + /// The identity policy requests from this client are checked against. + /// `None` means every client identity is undeclared. + #[must_use] + #[inline] + pub fn client_identity_policy(&self) -> Option<&Arc> { + self.client_identity_policy.as_ref() + } + /// Inspects effective marker policy without validation or I/O. #[must_use] #[inline] @@ -680,6 +705,7 @@ impl HttpClient { #[inline] pub fn new(client: Arc) -> Self { Self { + client_identity_policy: None, inner: client, proxy_marker_enabled: true, } @@ -850,6 +876,15 @@ impl HttpClient { Self::new(Arc::new(client)) } + /// Sets this client's identity policy. Dispatch keeps an explicit policy + /// instead of the app's. + #[must_use] + #[inline] + pub fn with_client_identity_policy(mut self, policy: Arc) -> Self { + self.client_identity_policy = Some(policy); + self + } + /// Sets the marker default for this handle; explicit per-request settings win. #[must_use] #[inline] @@ -1139,6 +1174,25 @@ impl OutboundRequest { (self.uri.scheme_str() == Some("https")).then(|| self.host_name()) } + /// Presents this declared client identity's certificate on the TLS connection. + /// + /// The request fails before any network I/O when the identity is undeclared, + /// the URI is not HTTPS, the adapter cannot present it, or the origin is not + /// in the identity's runtime hosts. Redirect hops keep the identity and are + /// checked again. + #[must_use] + #[inline] + pub fn client_identity(mut self, name: ClientIdentityName) -> Self { + self.client_identity = Some(name); + self + } + + #[must_use] + #[inline] + pub fn client_identity_name(&self) -> Option<&ClientIdentityName> { + self.client_identity.as_ref() + } + /// Sets an independent connect-phase ceiling; zero is rejected at preflight. #[must_use] #[inline] @@ -1171,6 +1225,7 @@ impl OutboundRequest { Ok(Self { body: parts.body, cache_policy: parts.cache_policy, + client_identity: parts.client_identity, connect_timeout: parts .connect_timeout .map(|timeout| timeout.min(DEADLINE_FAR_FUTURE)), @@ -1346,6 +1401,7 @@ impl OutboundRequest { OutboundRequestParts { body: self.body, cache_policy: self.cache_policy, + client_identity: self.client_identity, connect_timeout: self.connect_timeout, deadline: self.deadline, headers: self.headers, @@ -1571,6 +1627,7 @@ impl OutboundRequest { Self { body: Body::empty(), cache_policy: OutboundCachePolicy::PlatformDefault, + client_identity: None, connect_timeout: None, deadline: None, headers: HeaderMap::new(), diff --git a/crates/edgezero-core/src/outbound/client_identity.rs b/crates/edgezero-core/src/outbound/client_identity.rs new file mode 100644 index 000000000..2583fe13f --- /dev/null +++ b/crates/edgezero-core/src/outbound/client_identity.rs @@ -0,0 +1,544 @@ +//! Outbound TLS client identities. +//! +//! An application declares identities by name in its manifest and selects one +//! on an outbound request. Core owns the names, the per-app policy built from the +//! baked manifest, the host rules, the certificate-chain fingerprint and the +//! error type. Adapters own support checks and the runtime binding. + +use std::collections::BTreeMap; +use std::error::Error; +use std::fmt; +use std::net::Ipv6Addr; +use std::str::{FromStr as _, from_utf8}; + +use base16ct::lower::encode_string; +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD; +use sha2::{Digest as _, Sha256}; + +use crate::error::EdgeError; +use crate::http::{StatusCode, Uri}; +use crate::manifest::{ + AtomicHost, BakedManifest, HostPat, MAX_CLIENT_IDENTITY_NAME_LEN, Manifest, Port, Scheme, + canonicalize_outbound_host, is_valid_client_identity_name, +}; + +const HTTPS_DEFAULT_PORT: u16 = 443; +const PEM_CERTIFICATE_BEGIN: &str = "-----BEGIN CERTIFICATE-----"; +const PEM_CERTIFICATE_END: &str = "-----END CERTIFICATE-----"; + +/// A client certificate chain parsed from its PEM entry. +/// +/// Only `CERTIFICATE` blocks are kept, in entry order. `EdgeZero` does not check +/// expiry, extended key usage or the matching key; the origin's handshake does. +#[derive(Clone, Eq, PartialEq)] +pub struct ClientCertificateChain { + chain_fingerprint: [u8; 32], + leaf_fingerprint: [u8; 32], + pem: String, +} + +impl ClientCertificateChain { + /// SHA-256 over every certificate in order, each DER length-prefixed. Any + /// change to the chain, intermediates included, changes it. + #[inline] + #[must_use] + pub fn chain_fingerprint(&self) -> [u8; 32] { + self.chain_fingerprint + } + + /// SHA-256 of the leaf certificate's DER, as `openssl x509 -fingerprint -sha256` shows it. + #[inline] + #[must_use] + pub fn leaf_fingerprint(&self) -> [u8; 32] { + self.leaf_fingerprint + } + + /// Parses every `CERTIFICATE` block in `pem`. + /// + /// # Errors + /// Returns [`ClientIdentityError::MaterialInvalid`] for `Certificate` when + /// there is no block, a block is unterminated, or a block is not base64 DER. + #[inline] + pub fn parse(pem: &str) -> Result { + let certificates = decode_certificate_blocks(pem)?; + let Some(leaf) = certificates.first() else { + return Err(invalid_certificate()); + }; + let leaf_fingerprint: [u8; 32] = Sha256::digest(leaf).into(); + let mut normalized = String::new(); + for der in &certificates { + normalized.push_str(PEM_CERTIFICATE_BEGIN); + normalized.push('\n'); + let encoded = STANDARD.encode(der); + for line in encoded.as_bytes().chunks(64) { + normalized.push_str(from_utf8(line).unwrap_or_default()); + normalized.push('\n'); + } + normalized.push_str(PEM_CERTIFICATE_END); + normalized.push('\n'); + } + Ok(Self { + chain_fingerprint: chain_fingerprint(&certificates), + leaf_fingerprint, + pem: normalized, + }) + } + + /// The chain re-encoded as `CERTIFICATE` blocks only. + #[inline] + #[must_use] + pub fn pem(&self) -> &str { + &self.pem + } +} + +impl fmt::Debug for ClientCertificateChain { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ClientCertificateChain") + .field("leaf_fingerprint", &encode_string(&self.leaf_fingerprint)) + .finish_non_exhaustive() + } +} + +/// Why a request that selects a client identity was not sent. +/// +/// Every reason is raised before network I/O. A handshake the origin rejects is a +/// transport failure, not one of these. +#[derive(Clone, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum ClientIdentityError { + /// The request's origin is not in the identity's hosts. `origin` is + /// `https://host:port`, never a path or query. + HostNotAllowed { + origin: String, + redirect: bool, + }, + MaterialInvalid { + which: ClientIdentityMaterial, + }, + MaterialMissing { + which: ClientIdentityMaterial, + }, + RequiresHttps, + Undeclared, + /// The adapter cannot present an identity, or the request combines one with + /// an option that cannot carry it. + Unsupported { + adapter: &'static str, + }, +} + +impl ClientIdentityError { + pub(crate) fn wire_kind(&self) -> &'static str { + match self { + Self::RequiresHttps | Self::Undeclared | Self::Unsupported { .. } => "internal", + Self::MaterialInvalid { .. } + | Self::MaterialMissing { .. } + | Self::HostNotAllowed { + redirect: false, .. + } => "service_unavailable", + Self::HostNotAllowed { redirect: true, .. } => "bad_gateway", + } + } + + /// HTTP status for this reason. + #[inline] + #[must_use] + pub fn wire_status(&self) -> StatusCode { + match self { + Self::RequiresHttps | Self::Undeclared | Self::Unsupported { .. } => { + StatusCode::INTERNAL_SERVER_ERROR + } + Self::MaterialInvalid { .. } + | Self::MaterialMissing { .. } + | Self::HostNotAllowed { + redirect: false, .. + } => StatusCode::SERVICE_UNAVAILABLE, + Self::HostNotAllowed { redirect: true, .. } => StatusCode::BAD_GATEWAY, + } + } +} + +impl fmt::Display for ClientIdentityError { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::HostNotAllowed { + origin, + redirect: false, + } => write!(f, "{origin} is not in the identity's hosts"), + Self::HostNotAllowed { + origin, + redirect: true, + } => write!( + f, + "redirect to {origin}, which is not in the identity's hosts" + ), + Self::MaterialInvalid { which } => write!(f, "{} is invalid", which.as_str()), + Self::MaterialMissing { which } => write!(f, "{} is missing", which.as_str()), + Self::RequiresHttps => f.write_str("requests that select an identity must use https"), + Self::Undeclared => f.write_str("identity is not declared in the manifest"), + Self::Unsupported { adapter } => { + write!( + f, + "{adapter} cannot present a client identity on this request" + ) + } + } + } +} + +#[expect( + clippy::missing_trait_methods, + reason = "ClientIdentityError has no source or backtrace beyond Display" +)] +impl Error for ClientIdentityError {} + +/// The origins an identity may be presented to, parsed from its runtime hosts entry. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClientIdentityHosts { + origins: Vec<(String, u16)>, +} + +impl ClientIdentityHosts { + /// Longest accepted hosts entry, in bytes. + pub const MAX_BYTES: usize = 4_000; + + /// Checks that `uri` targets one of these origins. Only the URI's scheme, + /// host and port count; a `Host` override does not. + /// + /// # Errors + /// Returns [`ClientIdentityError::RequiresHttps`] for a non-HTTPS URI and + /// [`ClientIdentityError::HostNotAllowed`] for an unlisted origin. + #[inline] + pub fn check(&self, uri: &Uri) -> Result<(), ClientIdentityError> { + let (host, port) = https_origin(uri)?; + if self + .origins + .iter() + .any(|(listed_host, listed_port)| *listed_host == host && *listed_port == port) + { + Ok(()) + } else { + Err(ClientIdentityError::HostNotAllowed { + origin: format!("https://{host}:{port}"), + redirect: false, + }) + } + } + + /// The listed origins as `(host, port)`, hosts in canonical form. + #[inline] + pub fn origins(&self) -> impl Iterator { + self.origins + .iter() + .map(|(host, port)| (host.as_str(), *port)) + } + + /// Parses a hosts entry: one `https://host` or `https://host:port` per line, + /// in the outbound allowlist's host grammar, with no wildcards. Blank lines + /// are ignored. Every origin must be admitted by the policy's allowlist. + /// + /// # Errors + /// Returns [`ClientIdentityError::MaterialInvalid`] for `Hosts` when the entry + /// is oversized, empty, malformed, or names an origin outside the allowlist. + #[inline] + pub fn parse(text: &str, policy: &ClientIdentityPolicy) -> Result { + if text.len() > Self::MAX_BYTES { + return Err(invalid_hosts()); + } + let mut origins: Vec<(String, u16)> = Vec::new(); + for line in text.lines().map(str::trim).filter(|line| !line.is_empty()) { + let origin = parse_exact_https_origin(line)?; + if !policy.allows_https_origin(&origin.0, origin.1) { + return Err(invalid_hosts()); + } + if !origins.contains(&origin) { + origins.push(origin); + } + } + if origins.is_empty() { + return Err(invalid_hosts()); + } + Ok(Self { origins }) + } +} + +/// Which part of an identity's runtime binding failed. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[non_exhaustive] +pub enum ClientIdentityMaterial { + Certificate, + Hosts, + Key, + Store, +} + +impl ClientIdentityMaterial { + const fn as_str(self) -> &'static str { + match self { + Self::Certificate => "certificate", + Self::Hosts => "hosts list", + Self::Key => "private key", + Self::Store => "store", + } + } +} + +/// One declared identity, with its logical stores resolved from the manifest. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClientIdentityMetadata { + config_store: Option, + name: ClientIdentityName, + secret_store: Option, +} + +impl ClientIdentityMetadata { + /// Logical `[stores.config]` ID, if one resolved. + #[inline] + #[must_use] + pub fn config_store(&self) -> Option<&str> { + self.config_store.as_deref() + } + + #[inline] + #[must_use] + pub fn name(&self) -> &ClientIdentityName { + &self.name + } + + /// Logical `[stores.secrets]` ID, if one resolved. + #[inline] + #[must_use] + pub fn secret_store(&self) -> Option<&str> { + self.secret_store.as_deref() + } +} + +/// A validated client identity name: 1 to 64 characters of `[a-z0-9-]`, not +/// starting or ending with `-`. +#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct ClientIdentityName(String); + +impl ClientIdentityName { + #[inline] + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } + + /// # Errors + /// Returns a bad-request error when `name` breaks the manifest naming rules. + #[inline] + pub fn new(name: &str) -> Result { + if is_valid_client_identity_name(name) { + Ok(Self(name.to_owned())) + } else { + Err(EdgeError::bad_request(format!( + "client identity name must be 1 to {MAX_CLIENT_IDENTITY_NAME_LEN} characters of \ + [a-z0-9-], not starting or ending with `-`" + ))) + } + } +} + +impl fmt::Debug for ClientIdentityName { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("ClientIdentityName").field(&self.0).finish() + } +} + +impl fmt::Display for ClientIdentityName { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +/// The identities an application declares, plus its outbound allowlist. +/// +/// Built once per [`App`](crate::app::App) from the baked manifest and attached +/// to each request's [`HttpClient`](crate::HttpClient) at dispatch. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct ClientIdentityPolicy { + allowlist: Vec, + identities: BTreeMap, +} + +impl ClientIdentityPolicy { + /// Whether the outbound allowlist admits this HTTPS origin. + #[inline] + #[must_use] + pub fn allows_https_origin(&self, host: &str, port: u16) -> bool { + self.allowlist + .iter() + .any(|entry| entry.permits(Scheme::Https, host, port)) + } + + /// Policy for a baked manifest. Absent and malformed manifests yield an + /// empty policy, so every identity request fails as undeclared. + #[inline] + #[must_use] + pub fn from_baked(baked: BakedManifest) -> Self { + match baked { + BakedManifest::Present(manifest) => Self::from_manifest(manifest), + BakedManifest::Absent | BakedManifest::Malformed(_) => Self::default(), + } + } + + /// Policy for a validated manifest. + #[inline] + #[must_use] + pub fn from_manifest(manifest: &Manifest) -> Self { + let outbound = &manifest.capabilities.outbound; + let identities = outbound + .client_identities + .iter() + .filter(|(declared_name, _)| is_valid_client_identity_name(declared_name)) + .map(|(declared_name, declaration)| { + let name = ClientIdentityName(declared_name.clone()); + let metadata = ClientIdentityMetadata { + config_store: declaration + .resolved_config_store(&manifest.stores) + .map(str::to_owned), + name: name.clone(), + secret_store: declaration + .resolved_secret_store(&manifest.stores) + .map(str::to_owned), + }; + (name, metadata) + }) + .collect(); + let allowlist = outbound.hosts.as_deref().map_or_else( + || { + vec![AtomicHost { + host: HostPat::Any, + port: Port::Any, + scheme: Scheme::Https, + }] + }, + |entries| { + entries + .iter() + .filter_map(|entry| canonicalize_outbound_host(entry).ok()) + .flatten() + .collect() + }, + ); + Self { + allowlist, + identities, + } + } + + #[inline] + #[must_use] + pub fn identity(&self, name: &ClientIdentityName) -> Option<&ClientIdentityMetadata> { + self.identities.get(name) + } + + #[inline] + #[must_use] + pub fn is_empty(&self) -> bool { + self.identities.is_empty() + } +} + +#[expect( + clippy::big_endian_bytes, + reason = "the chain fingerprint uses a fixed byte order independent of the host architecture" +)] +fn chain_fingerprint(certificates: &[Vec]) -> [u8; 32] { + let mut chain = Sha256::new(); + for der in certificates { + chain.update(u64::try_from(der.len()).unwrap_or(u64::MAX).to_be_bytes()); + chain.update(der); + } + chain.finalize().into() +} + +fn decode_certificate_blocks(pem: &str) -> Result>, ClientIdentityError> { + let mut certificates = Vec::new(); + let mut current: Option = None; + for line in pem.lines().map(str::trim) { + match (&mut current, line) { + (None, PEM_CERTIFICATE_BEGIN) => current = Some(String::new()), + (None, _) => {} + (Some(body), PEM_CERTIFICATE_END) => { + let der = STANDARD + .decode(body.as_bytes()) + .map_err(|_error| invalid_certificate())?; + if der.is_empty() { + return Err(invalid_certificate()); + } + certificates.push(der); + current = None; + } + (Some(_), _) if line.starts_with("-----") => return Err(invalid_certificate()), + (Some(body), _) => body.push_str(line), + } + } + if current.is_some() { + return Err(invalid_certificate()); + } + Ok(certificates) +} + +/// Canonical `(host, port)` of an HTTPS URI: lowercase ASCII, IPv6 bracketed. +fn https_origin(uri: &Uri) -> Result<(String, u16), ClientIdentityError> { + if !is_https(uri) { + return Err(ClientIdentityError::RequiresHttps); + } + let raw_host = uri.host().ok_or(ClientIdentityError::RequiresHttps)?; + let unbracketed = raw_host + .strip_prefix('[') + .and_then(|inner| inner.strip_suffix(']')) + .unwrap_or(raw_host); + let host = Ipv6Addr::from_str(unbracketed).map_or_else( + |_error| raw_host.to_ascii_lowercase(), + |address| format!("[{address}]"), + ); + Ok((host, uri.port_u16().unwrap_or(HTTPS_DEFAULT_PORT))) +} + +fn invalid_certificate() -> ClientIdentityError { + ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Certificate, + } +} + +fn invalid_hosts() -> ClientIdentityError { + ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Hosts, + } +} + +/// Whether `uri` is HTTPS. Shared by core's preflight and the host check. +pub(crate) fn is_https(uri: &Uri) -> bool { + uri.scheme_str() + .is_some_and(|scheme| scheme.eq_ignore_ascii_case("https")) +} + +/// One hosts-entry line as an exact HTTPS origin in the allowlist grammar. +fn parse_exact_https_origin(line: &str) -> Result<(String, u16), ClientIdentityError> { + let explicit_https = line + .get(..8) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case("https://")); + if !explicit_https { + return Err(invalid_hosts()); + } + let mut parsed = canonicalize_outbound_host(line).map_err(|_error| invalid_hosts())?; + let (Some(entry), None) = (parsed.pop(), parsed.pop()) else { + return Err(invalid_hosts()); + }; + match (entry.host, entry.port, entry.scheme) { + (HostPat::Exact(host), Port::Exact(port), Scheme::Https) => Ok((host, port)), + _ => Err(invalid_hosts()), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/edgezero-core/src/outbound/client_identity/tests.rs b/crates/edgezero-core/src/outbound/client_identity/tests.rs new file mode 100644 index 000000000..602170abf --- /dev/null +++ b/crates/edgezero-core/src/outbound/client_identity/tests.rs @@ -0,0 +1,779 @@ +#![allow( + clippy::shadow_reuse, + clippy::shadow_unrelated, + reason = "table-driven cases reuse request, result and fixture bindings" +)] + +use std::cell::RefCell; +use std::future::pending; +use std::rc::Rc; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::Duration; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD; +use futures::executor::block_on; +use futures::future::ready; +use futures_util::stream; +use sha2::{Digest as _, Sha256}; + +use super::{ + ClientCertificateChain, ClientIdentityError, ClientIdentityHosts, ClientIdentityMaterial, + ClientIdentityName, ClientIdentityPolicy, +}; +use crate::app::{App, Hooks}; +use crate::body::Body; +use crate::context::RequestContext; +use crate::error::EdgeError; +use crate::http::{HeaderMap, HeaderValue, Method, StatusCode, Uri, request_builder}; +use crate::ingress::{IngressFraming, IngressHeadAccounting}; +use crate::manifest::{BakedManifest, ManifestLoader}; +use crate::outbound::{ + HttpClient, IndependentOutboundProgress, OutboundBatch, OutboundBatchDriverEvent, + OutboundCollectedSlot, OutboundDispatchRequest, OutboundExchangeOwner, OutboundFollowFailure, + OutboundFuture, OutboundHead, OutboundHeaderFidelity, OutboundHeaderInput, OutboundHttpClient, + OutboundPending, OutboundPreparedBatch, OutboundProgressRuntime, OutboundRedirectAction, + OutboundRedirectContext, OutboundRedirectLimit, OutboundRequest, OutboundSendMode, + OutboundTime, +}; +use crate::platform::PlatformMetadata; +use crate::router::RouterService; +use crate::time::{Deadline, MonotonicClock}; + +const IDENTITY_MANIFEST: &str = r#" +[capabilities.outbound] +hosts = ["https://*:*"] + +[capabilities.outbound.client-identities.mtls] +config-store = "certs" +secret-store = "keys" + +[stores.config] +ids = ["certs"] + +[stores.secrets] +ids = ["keys"] +"#; + +const HOSTS: &str = "https://a.example\nhttps://b.example:8443\n"; + +static MANIFEST: LazyLock = + LazyLock::new(|| ManifestLoader::load_from_str(IDENTITY_MANIFEST)); + +type SentLog = Arc)>>>; + +/// What the probe route saw on the request's `HttpClient`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Observed { + NoClient, + Policy { declares_identities: bool }, +} + +std::thread_local! { + static OBSERVED_POLICY: RefCell> = const { RefCell::new(None) }; +} + +/// A fake adapter that runs the identity host check the way a real adapter does +/// and records every request it would have sent. +struct IdentityClient { + hosts: &'static str, + sent: SentLog, +} + +struct IdentityHooks; + +impl IdentityClient { + fn respond(&self, request: OutboundDispatchRequest) -> Result { + if let Some(identity) = request.client_identity() { + let policy = request + .client_identity_policy() + .expect("policy with identity"); + ClientIdentityHosts::parse(self.hosts, policy) + .and_then(|hosts| hosts.check(request.request().uri())) + .map_err(|reason| EdgeError::client_identity(identity.name(), reason))?; + } + if let Ok(mut sent) = self.sent.lock() { + sent.push(( + request.request().uri().clone(), + request + .request() + .client_identity_name() + .map(|selected| selected.as_str().to_owned()), + )); + } + match request.request().uri().path() { + "/to-listed" => head( + request, + StatusCode::FOUND, + Some("https://b.example:8443/end"), + ), + "/to-unlisted" => head( + request, + StatusCode::FOUND, + Some("https://evil.example/end?q=1"), + ), + _ => head(request, StatusCode::OK, None), + } + } +} + +impl OutboundHttpClient for IdentityClient { + fn begin(&self, request: OutboundDispatchRequest) -> Result { + let outcome = self + .respond(request) + .and_then(|response_head| block_on(response_head.finish())); + Ok(OutboundPending::new( + Box::pin(ready(outcome)), + OutboundExchangeOwner::new(|| {}), + )) + } + + fn dispatch_head(&self, request: OutboundDispatchRequest) -> OutboundFuture { + Box::pin(ready(self.respond(request))) + } + + fn progress(&self) -> Rc { + Rc::new(IndependentOutboundProgress) + } + + fn start_batch_until(&self, batch: OutboundPreparedBatch) -> OutboundBatch { + let (context, slots) = batch.into_slots(); + let items = slots + .into_iter() + .map(|(index, request)| OutboundBatchDriverEvent::Item { + index, + completed_at: context.clock().now(), + outcome: self + .respond(request) + .and_then(|response_head| block_on(response_head.finish())), + }) + .collect::>(); + OutboundBatch::from_driver( + context, + stream::iter(items), + OutboundExchangeOwner::new(|| {}), + ) + } + + fn time(&self) -> OutboundTime { + OutboundTime::new(MonotonicClock::default(), |_deadline, _clock| { + Box::pin(pending()) + }) + } + + fn validate_supported_options( + &self, + _request: &OutboundRequest, + _mode: OutboundSendMode, + ) -> Result<(), EdgeError> { + Ok(()) + } +} + +#[expect( + clippy::missing_trait_methods, + reason = "the probe app needs only a manifest and one route" +)] +impl Hooks for IdentityHooks { + fn manifest() -> BakedManifest { + BakedManifest::Present(MANIFEST.manifest()) + } + + fn routes() -> Result { + async fn probe(ctx: RequestContext) -> Result { + let observed = + ctx.http_client() + .map_or(Observed::NoClient, |client| Observed::Policy { + declares_identities: client + .client_identity_policy() + .is_some_and(|attached| !attached.is_empty()), + }); + OBSERVED_POLICY.with(|slot| *slot.borrow_mut() = Some(observed)); + Ok("ok".to_owned()) + } + Ok(RouterService::builder().get("/probe", probe).build()) + } +} + +fn policy() -> Arc { + Arc::new(ClientIdentityPolicy::from_manifest(MANIFEST.manifest())) +} + +fn name() -> ClientIdentityName { + ClientIdentityName::new("mtls").expect("valid name") +} + +fn identity_client(hosts: &'static str) -> (HttpClient, SentLog) { + let sent = Arc::new(Mutex::new(Vec::new())); + let client = HttpClient::with_client(IdentityClient { + hosts, + sent: Arc::clone(&sent), + }) + .with_client_identity_policy(policy()); + (client, sent) +} + +fn get(uri: &str) -> OutboundRequest { + OutboundRequest::get(uri) + .expect("request") + .client_identity(name()) +} + +fn identity_reason(error: &EdgeError) -> &ClientIdentityError { + error + .client_identity_error() + .unwrap_or_else(|| panic!("expected a client identity error, got {error:?}")) +} + +fn head( + request: OutboundDispatchRequest, + status: StatusCode, + location: Option<&'static str>, +) -> Result { + let (_parts, context) = request.into_parts(); + let mut headers = HeaderMap::new(); + if let Some(target) = location { + headers.insert("location", HeaderValue::from_static(target)); + } + OutboundHead::new( + status, + OutboundHeaderInput::new( + "test", + headers, + OutboundHeaderFidelity::AdapterVisibleFields, + ), + Box::pin(stream::empty()), + context, + OutboundExchangeOwner::new(|| {}), + ) +} + +// --- names and policy ------------------------------------------------------- + +#[test] +fn names_follow_the_manifest_rules() { + for valid in ["a", "prebid-server", "x9"] { + let parsed = ClientIdentityName::new(valid).expect("valid name"); + assert_eq!(parsed.as_str(), valid); + assert_eq!(parsed.to_string(), valid); + } + for invalid in ["", "Upper", "-lead", "trail-", "under_score", "dot.ted"] { + let error = ClientIdentityName::new(invalid).expect_err("invalid name"); + assert_eq!(error.status(), StatusCode::BAD_REQUEST, "{invalid}"); + } + let _too_long = ClientIdentityName::new(&"a".repeat(65)).expect_err("too long"); + + let round_trip = + OutboundRequest::from_parts(get("https://a.example/").into_parts()).expect("from parts"); + assert_eq!(round_trip.client_identity_name(), Some(&name())); + assert_eq!( + OutboundRequest::get("https://a.example/") + .expect("request") + .client_identity_name(), + None + ); +} + +#[test] +fn policy_resolves_stores_and_defaults_the_allowlist() { + let policy = policy(); + let identity = policy.identity(&name()).expect("declared identity"); + assert_eq!(identity.name(), &name()); + assert_eq!(identity.config_store(), Some("certs")); + assert_eq!(identity.secret_store(), Some("keys")); + assert!(policy.allows_https_origin("anything.example", 1)); + + let unlisted = ClientIdentityName::new("other").expect("valid name"); + assert!(policy.identity(&unlisted).is_none()); + + let default_hosts = + ManifestLoader::load_from_str("[capabilities.outbound.client-identities.mtls]\n"); + let default_policy = ClientIdentityPolicy::from_manifest(default_hosts.manifest()); + assert!(default_policy.allows_https_origin("pbs.example", 443)); + let identity = default_policy.identity(&name()).expect("declared"); + assert_eq!(identity.config_store(), None); + assert_eq!(identity.secret_store(), None); + + assert!(ClientIdentityPolicy::from_baked(BakedManifest::Absent).is_empty()); + assert!(ClientIdentityPolicy::from_baked(BakedManifest::Malformed("corrupt")).is_empty()); + assert!( + !ClientIdentityPolicy::from_baked(BakedManifest::Present(MANIFEST.manifest())).is_empty() + ); +} + +// --- hosts entry -------------------------------------------------------------- + +#[test] +fn hosts_entry_parses_exact_https_origins() { + let hosts = ClientIdentityHosts::parse( + "\n HTTPS://PBS.Example.com \nhttps://b.example:8443\n\nhttps://[::1]:9443\nhttps://pbs.example.com:443\n", + &policy(), + ) + .expect("valid hosts"); + assert_eq!( + hosts.origins().collect::>(), + [ + ("pbs.example.com", 443), + ("b.example", 8443), + ("[::1]", 9443) + ] + ); +} + +#[test] +fn hosts_entry_rejects_everything_outside_the_grammar() { + let oversized = format!( + "https://{}.example\n", + "a".repeat(ClientIdentityHosts::MAX_BYTES) + ); + let invalid = [ + "", + " \n\n ", + "http://pbs.example", + "pbs.example", + "https://pbs.example/path", + "https://pbs.example?query=1", + "https://user@pbs.example", + "https://*.example", + "https://pbs.example:*", + "https://*", + "*", + "https://pbs.ex\u{e4}mple", + oversized.as_str(), + ]; + for entry in invalid { + assert_eq!( + ClientIdentityHosts::parse(entry, &policy()), + Err(ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Hosts + }), + "{entry:?}" + ); + } +} + +#[test] +fn hosts_entry_must_stay_inside_the_outbound_allowlist() { + let narrow = ManifestLoader::load_from_str( + "[capabilities.outbound]\nhosts = [\"https://*.example.com\"]\n\ + [capabilities.outbound.client-identities.mtls]\n", + ); + let policy = ClientIdentityPolicy::from_manifest(narrow.manifest()); + let _inside = ClientIdentityHosts::parse("https://pbs.example.com", &policy) + .expect("inside the allowlist"); + for outside in [ + "https://example.com", + "https://pbs.example.org", + "https://pbs.example.com\nhttps://pbs.example.org", + ] { + assert_eq!( + ClientIdentityHosts::parse(outside, &policy), + Err(ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Hosts + }), + "{outside}" + ); + } +} + +#[test] +fn host_check_compares_scheme_host_and_port_only() { + let hosts = ClientIdentityHosts::parse(HOSTS, &policy()).expect("hosts"); + for allowed in [ + "https://a.example/path?q=1", + "https://A.EXAMPLE:443/", + "https://b.example:8443/x", + ] { + assert_eq!( + hosts.check(&allowed.parse::().expect("uri")), + Ok(()), + "{allowed}" + ); + } + assert_eq!( + hosts.check(&"https://b.example/x".parse::().expect("uri")), + Err(ClientIdentityError::HostNotAllowed { + origin: "https://b.example:443".to_owned(), + redirect: false + }) + ); + assert_eq!( + hosts.check(&"http://a.example/".parse::().expect("uri")), + Err(ClientIdentityError::RequiresHttps) + ); + let ipv6 = ClientIdentityHosts::parse("https://[::1]:9443", &policy()).expect("ipv6"); + assert_eq!( + ipv6.check(&"https://[0:0::1]:9443/".parse::().expect("uri")), + Ok(()) + ); +} + +// --- certificate chain ---------------------------------------------------------- + +fn pem_block(label: &str, der: &[u8]) -> String { + format!( + "-----BEGIN {label}-----\n{}\n-----END {label}-----\n", + STANDARD.encode(der) + ) +} + +#[test] +fn certificate_chain_fingerprints_the_leaf_and_the_whole_chain() { + let leaf = b"leaf certificate der".as_slice(); + let intermediate = b"intermediate der".as_slice(); + let other_intermediate = b"replacement intermediate der".as_slice(); + let chain = ClientCertificateChain::parse(&format!( + "subject=CN=leaf\n{}{}", + pem_block("CERTIFICATE", leaf), + pem_block("CERTIFICATE", intermediate) + )) + .expect("chain"); + let expected_leaf: [u8; 32] = Sha256::digest(leaf).into(); + assert_eq!(chain.leaf_fingerprint(), expected_leaf); + + let replaced = ClientCertificateChain::parse(&format!( + "{}{}", + pem_block("CERTIFICATE", leaf), + pem_block("CERTIFICATE", other_intermediate) + )) + .expect("replaced chain"); + assert_eq!(replaced.leaf_fingerprint(), chain.leaf_fingerprint()); + assert_ne!(replaced.chain_fingerprint(), chain.chain_fingerprint()); + + let leaf_only = + ClientCertificateChain::parse(&pem_block("CERTIFICATE", leaf)).expect("leaf only"); + assert_ne!(leaf_only.chain_fingerprint(), chain.chain_fingerprint()); + + let reparsed = ClientCertificateChain::parse(chain.pem()).expect("normalized pem"); + assert_eq!(reparsed, chain); + assert!(!format!("{chain:?}").contains("BEGIN")); +} + +#[test] +fn certificate_chain_keeps_only_certificate_blocks() { + let chain = ClientCertificateChain::parse(&format!( + "{}{}", + pem_block("PRIVATE KEY", b"not for the certificate entry"), + pem_block("CERTIFICATE", b"leaf") + )) + .expect("chain"); + assert!(!chain.pem().contains("PRIVATE KEY")); + assert_eq!(chain.pem().matches("BEGIN CERTIFICATE").count(), 1); +} + +#[test] +fn certificate_chain_rejects_malformed_entries() { + let invalid = [ + String::new(), + "no pem here".to_owned(), + pem_block("PRIVATE KEY", b"key only"), + "-----BEGIN CERTIFICATE-----\nAAAA\n".to_owned(), + "-----BEGIN CERTIFICATE-----\n!!!!\n-----END CERTIFICATE-----\n".to_owned(), + "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n".to_owned(), + "-----BEGIN CERTIFICATE-----\nAAAA\n-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n" + .to_owned(), + ]; + for entry in &invalid { + assert_eq!( + ClientCertificateChain::parse(entry), + Err(ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Certificate + }), + "{entry:?}" + ); + } +} + +// --- errors --------------------------------------------------------------------- + +#[test] +fn errors_choose_status_and_kind_and_never_show_paths() { + let cases = [ + ( + ClientIdentityError::Undeclared, + StatusCode::INTERNAL_SERVER_ERROR, + "internal", + ), + ( + ClientIdentityError::RequiresHttps, + StatusCode::INTERNAL_SERVER_ERROR, + "internal", + ), + ( + ClientIdentityError::Unsupported { adapter: "spin" }, + StatusCode::INTERNAL_SERVER_ERROR, + "internal", + ), + ( + ClientIdentityError::MaterialMissing { + which: ClientIdentityMaterial::Key, + }, + StatusCode::SERVICE_UNAVAILABLE, + "service_unavailable", + ), + ( + ClientIdentityError::MaterialInvalid { + which: ClientIdentityMaterial::Certificate, + }, + StatusCode::SERVICE_UNAVAILABLE, + "service_unavailable", + ), + ( + ClientIdentityError::HostNotAllowed { + origin: "https://x.example:443".to_owned(), + redirect: false, + }, + StatusCode::SERVICE_UNAVAILABLE, + "service_unavailable", + ), + ( + ClientIdentityError::HostNotAllowed { + origin: "https://x.example:443".to_owned(), + redirect: true, + }, + StatusCode::BAD_GATEWAY, + "bad_gateway", + ), + ]; + for (reason, status, kind) in cases { + let error = EdgeError::client_identity(&name(), reason.clone()); + assert_eq!(error.status(), status, "{reason:?}"); + assert_eq!(error.kind(), kind, "{reason:?}"); + assert_eq!(identity_reason(&error), &reason); + assert!( + error.message().starts_with("client identity `mtls`: "), + "{error}" + ); + } + + let hosts = ClientIdentityHosts::parse(HOSTS, &policy()).expect("hosts"); + let reason = hosts + .check( + &"https://evil.example/secret/path?token=abc" + .parse::() + .expect("uri"), + ) + .expect_err("unlisted"); + let rendered = format!( + "{reason} {reason:?} {}", + EdgeError::client_identity(&name(), reason.clone()) + ); + assert!(rendered.contains("https://evil.example:443"), "{rendered}"); + assert!(!rendered.contains("secret"), "{rendered}"); + assert!(!rendered.contains("token"), "{rendered}"); + assert!( + EdgeError::bad_request("plain") + .client_identity_error() + .is_none() + ); +} + +// --- dispatch through HttpClient ---------------------------------------------------- + +#[test] +fn undeclared_and_non_https_requests_never_reach_the_adapter() { + let (client, sent) = identity_client(HOSTS); + let undeclared = ClientIdentityName::new("other").expect("valid name"); + let error = block_on( + client.send( + OutboundRequest::get("https://a.example/") + .expect("request") + .client_identity(undeclared), + ), + ) + .expect_err("undeclared"); + assert_eq!(identity_reason(&error), &ClientIdentityError::Undeclared); + + let error = block_on(client.send(get("http://a.example/"))).expect_err("http"); + assert_eq!(identity_reason(&error), &ClientIdentityError::RequiresHttps); + + let without_policy = HttpClient::with_client(IdentityClient { + hosts: HOSTS, + sent: Arc::clone(&sent), + }); + let error = block_on(without_policy.send(get("https://a.example/"))).expect_err("no policy"); + assert_eq!(identity_reason(&error), &ClientIdentityError::Undeclared); + + assert!(sent.lock().expect("sent").is_empty()); +} + +#[test] +fn listed_origins_are_sent_with_the_identity_and_others_are_refused() { + let (client, sent) = identity_client(HOSTS); + let response = block_on(client.send(get("https://a.example/ok"))).expect("listed"); + assert_eq!(response.status(), StatusCode::OK); + + let overridden = get("https://a.example/ok") + .host_authority_override("pbs.internal") + .expect("override"); + block_on(client.send(overridden)).expect("override keeps the connection origin"); + + let error = block_on(client.send(get("https://evil.example/"))).expect_err("unlisted"); + assert_eq!(error.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + identity_reason(&error), + &ClientIdentityError::HostNotAllowed { + origin: "https://evil.example:443".to_owned(), + redirect: false + } + ); + + let _plain = + block_on(client.send(OutboundRequest::get("https://evil.example/").expect("plain"))) + .expect("requests without an identity are unaffected"); + + let recorded = sent.lock().expect("sent"); + assert_eq!(recorded.len(), 3); + assert_eq!(recorded[0].1.as_deref(), Some("mtls")); + assert_eq!(recorded[2].1, None); +} + +#[expect( + clippy::unnecessary_wraps, + reason = "redirect policies return a Result by contract" +)] +fn follow_all(_context: &mut OutboundRedirectContext<'_>) -> Result { + Ok(OutboundRedirectAction::FollowPrepared) +} + +#[test] +fn redirects_keep_the_identity_and_recheck_every_hop() { + let limit = OutboundRedirectLimit::new(5).expect("limit"); + + let (client, sent) = identity_client(HOSTS); + let followed = block_on(client.follow(get("https://a.example/to-listed"), limit, follow_all)) + .expect("followed"); + assert_eq!(followed.redirects_followed(), 1); + let recorded = sent.lock().expect("sent").clone(); + assert_eq!(recorded.len(), 2); + assert!( + recorded + .iter() + .all(|(_, identity)| identity.as_deref() == Some("mtls")) + ); + assert_eq!(recorded[1].0, "https://b.example:8443/end"); + + let (client, sent) = identity_client(HOSTS); + let failure = block_on(client.follow(get("https://a.example/to-unlisted"), limit, follow_all)) + .expect_err("unlisted redirect"); + let OutboundFollowFailure::Hop { index, error } = failure else { + panic!("expected a hop failure"); + }; + assert_eq!(index, 1); + assert_eq!(error.status(), StatusCode::BAD_GATEWAY); + assert_eq!( + identity_reason(&error), + &ClientIdentityError::HostNotAllowed { + origin: "https://evil.example:443".to_owned(), + redirect: true + } + ); + assert_eq!( + sent.lock().expect("sent").len(), + 1, + "the unlisted hop is never sent" + ); +} + +#[test] +fn batch_slots_fail_alone() { + let (client, sent) = identity_client(HOSTS); + let cutoff = Deadline::after(Duration::from_secs(60)); + let results = block_on(client.send_all_until( + vec![ + get("https://a.example/one"), + get("https://evil.example/two"), + OutboundRequest::get("https://a.example/three") + .expect("request") + .client_identity(ClientIdentityName::new("other").expect("name")), + get("https://b.example:8443/four"), + ], + cutoff, + )) + .expect("batch"); + let (slots, _termination) = results.into_parts(); + let outcomes: Vec<_> = slots + .into_iter() + .map(|slot| match slot { + OutboundCollectedSlot::Resolved(result) => result, + OutboundCollectedSlot::AlreadyDelivered | OutboundCollectedSlot::Unresolved => { + panic!("every slot resolves") + } + }) + .collect(); + let _first = outcomes[0].outcome.as_ref().expect("listed slot"); + assert!(matches!( + outcomes[1].outcome.as_ref().map_err(identity_reason), + Err(ClientIdentityError::HostNotAllowed { .. }) + )); + assert!(matches!( + outcomes[2].outcome.as_ref().map_err(identity_reason), + Err(ClientIdentityError::Undeclared) + )); + let _fourth = outcomes[3].outcome.as_ref().expect("listed slot"); + assert_eq!(sent.lock().expect("sent").len(), 2); +} + +// --- dispatch attaches the app policy -------------------------------------------- + +fn dispatch_probe(app: &App, client: Option) -> Option { + OBSERVED_POLICY.with(|slot| *slot.borrow_mut() = None); + let mut request = request_builder() + .method(Method::GET) + .uri("/probe") + .body(Body::empty()) + .expect("request"); + if let Some(supplied) = client { + request.extensions_mut().insert(supplied); + } + let _outcome = block_on(app.dispatch_ingress( + request, + app.monotonic_now(), + IngressHeadAccounting::HostManaged, + IngressFraming::HostManaged, + )) + .expect("dispatch"); + OBSERVED_POLICY.with(|slot| slot.borrow_mut().take()) +} + +#[test] +fn dispatch_attaches_the_app_policy_to_the_request_client() { + let app = App::build::(PlatformMetadata::default()).expect("app"); + assert!(!app.client_identity_policy().is_empty()); + + let bare = HttpClient::with_client(IdentityClient { + hosts: HOSTS, + sent: Arc::new(Mutex::new(Vec::new())), + }); + assert!(bare.client_identity_policy().is_none()); + assert_eq!( + dispatch_probe(&app, Some(bare)), + Some(Observed::Policy { + declares_identities: true + }) + ); + + let explicit = HttpClient::with_client(IdentityClient { + hosts: HOSTS, + sent: Arc::new(Mutex::new(Vec::new())), + }) + .with_client_identity_policy(Arc::new(ClientIdentityPolicy::default())); + assert_eq!( + dispatch_probe(&app, Some(explicit)), + Some(Observed::Policy { + declares_identities: false + }), + "an explicit policy is kept" + ); + + assert_eq!( + dispatch_probe(&app, None), + Some(Observed::NoClient), + "no client is created" + ); + + assert_eq!( + app.client_identity_policy().as_ref(), + &ClientIdentityPolicy::from_manifest(MANIFEST.manifest()) + ); +} diff --git a/crates/edgezero-core/src/outbound/dispatch.rs b/crates/edgezero-core/src/outbound/dispatch.rs index 8f4c4a9dd..3141cf5ac 100644 --- a/crates/edgezero-core/src/outbound/dispatch.rs +++ b/crates/edgezero-core/src/outbound/dispatch.rs @@ -5,10 +5,13 @@ use std::task::Poll; use futures_util::StreamExt as _; use futures_util::future::poll_fn; +use std::sync::Arc; + use super::{ - HttpClient, Method, OutboundDispatchRequest, OutboundRequest, OutboundRequestParts, - OutboundResponseContext, OutboundScope, OutboundSendMode, OutboundTime, ResponseBodyPolicy, - ResponseHeaderLimiter, normalize_for_dispatch, validate_for_dispatch, + ClientIdentityError, ClientIdentityMetadata, ClientIdentityPolicy, HttpClient, Method, + OutboundDispatchRequest, OutboundRequest, OutboundRequestParts, OutboundResponseContext, + OutboundScope, OutboundSendMode, OutboundTime, ResponseBodyPolicy, ResponseHeaderLimiter, + is_https, normalize_for_dispatch, validate_for_dispatch, }; use crate::error::EdgeError; use crate::http::StatusCode; @@ -22,6 +25,13 @@ pub(super) struct DispatchBounds { pub original_chain_deadline: Option, } +/// A declared identity selected by a request, with the policy that declared it. +#[derive(Clone, Debug)] +pub(crate) struct ResolvedClientIdentity { + metadata: ClientIdentityMetadata, + policy: Arc, +} + /// Private forwarding metadata, not a second body or a public policy override. #[derive(Clone)] pub(crate) struct ForwardedReadDeadline(Deadline); @@ -42,6 +52,25 @@ impl OutboundDispatchRequest { self.context.budget } + /// The declared identity this request selects, already checked to be + /// declared and HTTPS. Adapters resolve its runtime binding. + #[must_use] + #[inline] + pub fn client_identity(&self) -> Option<&ClientIdentityMetadata> { + self.client_identity + .as_ref() + .map(|resolved| &resolved.metadata) + } + + /// The policy that declared [`Self::client_identity`], for parsing its hosts entry. + #[must_use] + #[inline] + pub fn client_identity_policy(&self) -> Option<&Arc> { + self.client_identity + .as_ref() + .map(|resolved| &resolved.policy) + } + #[must_use] #[inline] pub fn clock(&self) -> &MonotonicClock { @@ -79,6 +108,35 @@ impl OutboundDispatchRequest { } } +/// Undeclared and non-HTTPS identity requests fail here, in core, before any adapter I/O. +fn resolve_client_identity( + client: &HttpClient, + request: &OutboundRequest, +) -> Result, EdgeError> { + let Some(name) = request.client_identity_name() else { + return Ok(None); + }; + let Some((policy, metadata)) = client + .client_identity_policy() + .and_then(|policy| policy.identity(name).map(|metadata| (policy, metadata))) + else { + return Err(EdgeError::client_identity( + name, + ClientIdentityError::Undeclared, + )); + }; + if !is_https(request.uri()) { + return Err(EdgeError::client_identity( + name, + ClientIdentityError::RequiresHttps, + )); + } + Ok(Some(ResolvedClientIdentity { + metadata: metadata.clone(), + policy: Arc::clone(policy), + })) +} + pub(super) fn prepare( client: &HttpClient, mut request: OutboundRequest, @@ -90,6 +148,7 @@ pub(super) fn prepare( ) -> Result { scope.check()?; client.inner.validate_supported_options(&request, mode)?; + let client_identity = resolve_client_identity(client, &request)?; scope.check()?; validate_for_dispatch(&request, mode)?; let budget = dispatch_budget_inputs( @@ -132,7 +191,11 @@ pub(super) fn prepare( scope, time, }; - Ok(OutboundDispatchRequest { context, request }) + Ok(OutboundDispatchRequest { + client_identity, + context, + request, + }) } pub(super) async fn settle( diff --git a/crates/edgezero-core/src/outbound/redirect.rs b/crates/edgezero-core/src/outbound/redirect.rs index 07634203a..8591f5aeb 100644 --- a/crates/edgezero-core/src/outbound/redirect.rs +++ b/crates/edgezero-core/src/outbound/redirect.rs @@ -7,8 +7,8 @@ use url::Url; use super::dispatch::{self, DispatchBounds}; use super::{ - HttpClient, OutboundDispatchRequest, OutboundHead, OutboundRequest, OutboundResponse, - OutboundScope, OutboundSendMode, OutboundTime, canonicalize_url, head, scope, + ClientIdentityError, HttpClient, OutboundDispatchRequest, OutboundHead, OutboundRequest, + OutboundResponse, OutboundScope, OutboundSendMode, OutboundTime, canonicalize_url, head, scope, }; use crate::body::Body; use crate::error::{BadGatewayReason, EdgeError}; @@ -107,9 +107,10 @@ impl FollowChain { } fn hop(&self, error: EdgeError) -> OutboundFollowFailure { + let index = self.index.get(); OutboundFollowFailure::Hop { - index: self.index.get(), - error, + index, + error: mark_redirect_host_refusal(error, index), } } @@ -385,6 +386,32 @@ where }) } +/// An upstream redirect, not the application, chose a hop's origin, so an +/// unlisted redirect target is reported as a redirect failure. +fn mark_redirect_host_refusal(error: EdgeError, index: usize) -> EdgeError { + if index == 0 { + return error; + } + if let EdgeError::ClientIdentity { + name, + reason: + ClientIdentityError::HostNotAllowed { + origin, + redirect: false, + }, + } = error + { + return EdgeError::ClientIdentity { + name, + reason: ClientIdentityError::HostNotAllowed { + origin, + redirect: true, + }, + }; + } + error +} + fn followable(status: StatusCode) -> bool { matches!(status.as_u16(), 301 | 302 | 303 | 307 | 308) } @@ -418,6 +445,7 @@ fn replay_request(request: &OutboundRequest) -> (OutboundRequest, bool) { let OutboundRequest { body, cache_policy, + client_identity, connect_timeout, deadline, headers, @@ -449,6 +477,7 @@ fn replay_request(request: &OutboundRequest) -> (OutboundRequest, bool) { OutboundRequest { body: replayed_body, cache_policy: cache_policy.clone(), + client_identity: client_identity.clone(), connect_timeout: *connect_timeout, deadline: *deadline, headers: headers.clone(), diff --git a/crates/edgezero-core/src/response_egress_framing.rs b/crates/edgezero-core/src/response_egress_framing.rs index 028771c59..a9b44f630 100644 --- a/crates/edgezero-core/src/response_egress_framing.rs +++ b/crates/edgezero-core/src/response_egress_framing.rs @@ -277,6 +277,7 @@ pub fn response_egress_source_error_category(error: &EdgeError) -> &'static str BadGatewayReason::Unspecified => "bad_gateway_unspecified", }, EdgeError::BadRequest { .. } => "bad_request", + EdgeError::ClientIdentity { .. } => "client_identity", EdgeError::ConfigOutOfDate { .. } => "config_out_of_date", EdgeError::GatewayTimeout { .. } => "gateway_timeout", EdgeError::Internal { .. } => "internal", diff --git a/crates/edgezero-test-harness/Cargo.lock b/crates/edgezero-test-harness/Cargo.lock index 7b554f048..4ccb85f6a 100644 --- a/crates/edgezero-test-harness/Cargo.lock +++ b/crates/edgezero-test-harness/Cargo.lock @@ -8,6 +8,90 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "untrusted 0.7.1", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + [[package]] name = "bitflags" version = "2.11.1" @@ -32,6 +116,18 @@ dependencies = [ "objc2", ] +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -44,6 +140,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -80,9 +185,35 @@ checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162" dependencies = [ "dispatch2", "nix", - "windows-sys", + "windows-sys 0.61.2", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "digest" version = "0.10.7" @@ -105,6 +236,23 @@ dependencies = [ "objc2", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "edgezero-test-harness" version = "0.1.0" @@ -114,11 +262,13 @@ dependencies = [ "mio", "nix", "quote", + "rcgen", + "rustls", "serde_json", "serde_yaml_ng", "sha2", "socket2", - "syn", + "syn 2.0.119", "tempfile", "toml", ] @@ -136,7 +286,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -145,6 +295,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + [[package]] name = "flate2" version = "1.1.9" @@ -155,6 +311,12 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "generic-array" version = "0.14.7" @@ -165,6 +327,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -198,6 +371,22 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.186" @@ -216,6 +405,12 @@ version = "2.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -234,7 +429,7 @@ checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -249,6 +444,50 @@ dependencies = [ "libc", ] +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "objc2" version = "0.6.4" @@ -264,12 +503,43 @@ version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "proc-macro2" version = "1.0.106" @@ -294,6 +564,43 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "aws-lc-rs", + "pem", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted 0.9.0", + "windows-sys 0.52.0", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + [[package]] name = "rustix" version = "1.1.5" @@ -304,7 +611,42 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted 0.9.0", ] [[package]] @@ -320,6 +662,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -339,7 +682,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -388,6 +731,12 @@ dependencies = [ "digest", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "simd-adler32" version = "0.3.10" @@ -401,9 +750,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -415,6 +770,28 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -422,10 +799,60 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", ] [[package]] @@ -485,6 +912,18 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "version_check" version = "0.9.5" @@ -503,6 +942,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -512,12 +960,110 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "aws-lc-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + [[package]] name = "zmij" version = "1.0.21" diff --git a/crates/edgezero-test-harness/Cargo.toml b/crates/edgezero-test-harness/Cargo.toml index 837d8186e..614c2151c 100644 --- a/crates/edgezero-test-harness/Cargo.toml +++ b/crates/edgezero-test-harness/Cargo.toml @@ -8,6 +8,8 @@ publish = false resolver = "2" [dependencies] +rcgen = { version = "=0.14.10", default-features = false, features = ["aws_lc_rs", "crypto", "pem"] } +rustls = { version = "=0.23.46", default-features = false, features = ["aws_lc_rs", "std", "tls12"] } ctrlc = { version = "3.5.2", features = ["termination"] } flate2 = { version = "=1.1.9", default-features = false, features = ["rust_backend"] } mio = { version = "=1.2.1", default-features = false, features = ["net", "os-poll"] } diff --git a/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock b/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock index 61cd28627..2757a9236 100644 --- a/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock +++ b/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock @@ -104,6 +104,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bitflags" version = "1.3.2" @@ -422,6 +428,7 @@ dependencies = [ "async-stream", "async-trait", "base16ct", + "base64", "brotli", "brotli-decompressor", "bytes", diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock index b9a601443..05a95619b 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock +++ b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock @@ -609,6 +609,7 @@ dependencies = [ "async-stream", "async-trait", "base16ct", + "base64", "brotli", "brotli-decompressor", "bytes", diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-fastly/Cargo.toml b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-fastly/Cargo.toml index b15008d63..aed791def 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-fastly/Cargo.toml +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-fastly/Cargo.toml @@ -10,6 +10,7 @@ qualification = ["progress"] progress = ["fixture-core/qualification", "fixture-core/native-body-witness", "edgezero-adapter-fastly/test-utils"] readiness = ["dep:fastly-sys"] records = ["edgezero-core/test-utils"] +client-identity = [] [dependencies] edgezero-core.workspace = true @@ -91,5 +92,10 @@ name = "fixture-fastly-record-contract" path = "src/bin/record_contract.rs" required-features = ["records"] +[[bin]] +name = "fixture-fastly-client-identity" +path = "src/bin/client_identity.rs" +required-features = ["client-identity"] + [lints] workspace = true diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-fastly/src/bin/client_identity.rs b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-fastly/src/bin/client_identity.rs new file mode 100644 index 000000000..95ad5dcc3 --- /dev/null +++ b/crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-fastly/src/bin/client_identity.rs @@ -0,0 +1,145 @@ +//! Client identity contract fixture. +//! +//! Sends outbound requests that select a declared TLS client identity through the +//! managed `run_app` path, so core attaches the identity policy at dispatch and +//! the Fastly adapter resolves the runtime binding from Viceroy's local stores. +//! The target origin comes from the `x-fixture-backend` header. Every case answers 200 +//! with a JSON report; the harness checks origin-side records separately. +//! +//! The manifest is loaded into `Hooks::manifest()` directly rather than through +//! `app!`, because this fixture workspace has no `edgezero.toml` app layout for +//! the macro to read. The policy path from `Hooks::manifest()` onward is the same. + +use std::sync::LazyLock; + +use edgezero_core::OutboundImageOptimizerOptions; +use edgezero_core::app::Hooks; +use edgezero_core::context::RequestContext; +use edgezero_core::error::EdgeError; +use edgezero_core::manifest::{BakedManifest, ManifestLoader}; +use edgezero_core::outbound::{ + ClientIdentityName, HttpClient, OutboundFollowFailure, OutboundRedirectAction, + OutboundRedirectContext, OutboundRedirectLimit, OutboundRequest, +}; +use edgezero_core::router::RouterService; +use serde_json::{Value, json}; + +const MANIFEST: &str = r#" +[capabilities.outbound.client-identities.fixture-mtls] +config-store = "fixture_mtls_config" +secret-store = "fixture_mtls_secrets" + +[stores.config] +ids = ["fixture_mtls_config"] + +[stores.secrets] +ids = ["fixture_mtls_secrets"] +"#; + +static LOADED: LazyLock = LazyLock::new(|| ManifestLoader::load_from_str(MANIFEST)); + +struct ClientIdentityApp; + +impl Hooks for ClientIdentityApp { + fn manifest() -> BakedManifest { + BakedManifest::Present(LOADED.manifest()) + } + + fn routes() -> Result { + Ok(RouterService::builder() + .middleware(fixture_core::launch::Identity) + .get("/identity/{case}", identity_case) + .build()) + } +} + +fn follow_all(_context: &mut OutboundRedirectContext<'_>) -> Result { + Ok(OutboundRedirectAction::FollowPrepared) +} + +fn failure_report(case: &str, error: &EdgeError, hop: Option) -> Value { + json!({ + "case": case, + "outcome": "error", + "status": error.status().as_u16(), + "kind": error.kind(), + "reason": error.client_identity_error().map(|reason| format!("{reason:?}")), + "provider_cause": error.provider_failure_detail().map(|detail| format!("{detail:?}")), + "hop": hop, + }) +} + +async fn send(case: &str, client: &HttpClient, request: OutboundRequest) -> Value { + match client.send(request).await { + Ok(response) => json!({ + "case": case, + "outcome": "response", + "status": response.status().as_u16(), + }), + Err(error) => failure_report(case, &error, None), + } +} + +async fn identity_case(ctx: RequestContext) -> Result { + let case = ctx + .path_params() + .get("case") + .ok_or_else(|| EdgeError::bad_request("missing case"))? + .to_owned(); + let target = ctx + .headers() + .get("x-fixture-backend") + .and_then(|value| value.to_str().ok()) + .ok_or_else(|| EdgeError::bad_request("missing x-fixture-backend"))? + .to_owned(); + let client = ctx + .http_client() + .ok_or_else(|| EdgeError::bad_request("missing outbound client"))?; + let mtls = ClientIdentityName::new("fixture-mtls")?; + let request = OutboundRequest::get(target.as_str())?; + let report = match case.as_str() { + "with" => send(&case, &client, request.client_identity(mtls)).await, + "without" => send(&case, &client, request).await, + "undeclared" => { + let undeclared = ClientIdentityName::new("undeclared-mtls")?; + send(&case, &client, request.client_identity(undeclared)).await + } + "optimizer" => { + let optimized = request + .client_identity(mtls) + .image_optimizer(OutboundImageOptimizerOptions::new()); + send(&case, &client, optimized).await + } + "follow" => { + let limit = OutboundRedirectLimit::new(3)?; + match client + .follow(request.client_identity(mtls), limit, follow_all) + .await + { + Ok(followed) => { + let (response, final_uri, redirects, _stop) = followed.into_parts(); + json!({ + "case": case, + "outcome": "response", + "status": response.status().as_u16(), + "final_uri": final_uri.to_string(), + "redirects": redirects, + }) + } + Err(OutboundFollowFailure::Hop { index, error }) => { + failure_report(&case, &error, Some(index)) + } + Err(OutboundFollowFailure::Policy { .. }) => { + return Err(EdgeError::bad_request("follow policy never rejects")); + } + } + } + _ => return Err(EdgeError::bad_request("unknown case")), + }; + Ok(report.to_string()) +} + +fn main() -> Result<(), fastly::Error> { + fixture_fastly::initialize_launch(env!("CARGO_BIN_NAME")); + edgezero_adapter_fastly::run_app::() +} diff --git a/crates/edgezero-test-harness/src/evidence/cutover/reviewed_owners.json b/crates/edgezero-test-harness/src/evidence/cutover/reviewed_owners.json index 527ed1ed9..b6124025c 100644 --- a/crates/edgezero-test-harness/src/evidence/cutover/reviewed_owners.json +++ b/crates/edgezero-test-harness/src/evidence/cutover/reviewed_owners.json @@ -1,12 +1,12 @@ { "src/main.rs:outbound_lifetimes_selects_exactly_one_explicit_provider": "db8098c65fe1d4c32b4c7572883e02b1267d6ddaa99b751d35a087052409942c", "src/main.rs:outbound_wire_suite_is_explicit_and_selects_one_supported_provider": "5e6bd8b1f347422d0030acab5e43a8c0d9fffbad7f304d7171847fc7e4e04ae7", - "src/main.rs:parse_from": "5c8bd05e2331f4794feccd592bc22308272ce1bb1afeff7a3bea4c9ec1c0f2a9", + "src/main.rs:parse_from": "fc07bdd126287f8a45f2f1f463e3061d1397e9cbed6e93457e692f16d6732935", "src/main.rs:run": "744c16f7b155adb4d27933eed21ab7b6d0adcc40ac81b787e2b8e164b2b78fb5", - "src/runners.rs:fastly": "5ec7f89c5669eb077f5b81cb57a21f62f9d55869ef2f84255155d0442728e330", + "src/runners.rs:fastly": "426eabc88fdbe419e8df00fc1d885ed855a65eb481a27661e6dd01e43c330858", "src/runners.rs:provider": "611830f75cbb95179b853a39f49ba9839a9cb06c2967b769a7d9300a40536f5b", "src/runners/ci.rs:phase_with_exit": "071915332c0cd8d29aeade1fc89ed79d35b38037c76d41e55160c11f7f31e76e", - "src/runners/ci.rs:run": "ce639c2a76850fd428db8319d94de3ec2c7a3c7e96a5963e79f0aec1b2d37d2a", + "src/runners/ci.rs:run": "8d02d3f27d7876dc7a766f5a182a396065315c79e76b3500997ea8e72699ea2c", "src/runners/ci.rs:validate_markers": "961030a703f370ed853d58470d1c3457a234f5b644cf5d7dcf4c683eafbdc007", "src/runners/lifetimes.rs:checks": "3e28e2c40e6b0def8ad07ed2052b915c7dbfc13864580bff0aa907544d441740", "src/runners/lifetimes.rs:combined_count": "aad2bc7bce19a9065cd2d309daa929df638e6808fe9cd1819dd9eb494be2541a", diff --git a/crates/edgezero-test-harness/src/main.rs b/crates/edgezero-test-harness/src/main.rs index 350366483..8caa6fd57 100644 --- a/crates/edgezero-test-harness/src/main.rs +++ b/crates/edgezero-test-harness/src/main.rs @@ -95,6 +95,7 @@ impl Args { "benchmark", "assembly", "record-contract", + "client-identity", "outbound-readiness", "outbound-client-progress", "outbound-progress", @@ -113,6 +114,10 @@ impl Args { a.suite != "record-contract" || a.adapter == "fastly", "record contract requires --adapter fastly", )?; + require( + a.suite != "client-identity" || a.adapter == "fastly", + "client identity contract requires --adapter fastly", + )?; require( !matches!( a.suite.as_str(), @@ -1064,6 +1069,16 @@ mod argument_tests { assert!(Args::parse_from(["--suite", "outbound-wire"].map(str::to_owned)).is_err()); } + #[test] + fn client_identity_suite_selects_only_fastly() { + for adapter in ["fastly", "axum", "cloudflare", "spin", "all"] { + let result = Args::parse_from( + ["--adapter", adapter, "--suite", "client-identity"].map(str::to_owned), + ); + assert_eq!(result.is_ok(), adapter == "fastly", "{adapter}"); + } + } + #[test] fn record_contract_suite_selects_only_fastly() { for adapter in ["fastly", "axum", "cloudflare", "spin", "all"] { diff --git a/crates/edgezero-test-harness/src/runners.rs b/crates/edgezero-test-harness/src/runners.rs index a9a8d3ff5..62738199c 100644 --- a/crates/edgezero-test-harness/src/runners.rs +++ b/crates/edgezero-test-harness/src/runners.rs @@ -2,6 +2,7 @@ use crate::{evidence::*, net::Backend, *}; use std::collections::{BTreeSet, HashMap, HashSet}; mod assembly; pub(crate) mod ci; +mod client_identity; mod framing; mod lifetimes; mod overflow; @@ -381,6 +382,9 @@ pub fn fastly(args: &Args, run: &Path, records: &mut Records) -> Result<()> { if args.suite == "record-contract" { return record_contract::run(&exe, run, records); } + if args.suite == "client-identity" { + return client_identity::run(&exe, run, records); + } if args.suite == "outbound-wire" { return wire::run("fastly", run, records); } diff --git a/crates/edgezero-test-harness/src/runners/ci.rs b/crates/edgezero-test-harness/src/runners/ci.rs index b4901015d..15424ed02 100644 --- a/crates/edgezero-test-harness/src/runners/ci.rs +++ b/crates/edgezero-test-harness/src/runners/ci.rs @@ -258,6 +258,27 @@ pub(crate) fn run(args: &Args, run: &Path, records: &mut Records) -> Result<()> &output.join("events.jsonl"), CI_ARTIFACT_RECORDS, )?)?; + let identity_output = run.join("client-identity"); + phase( + "fastly", + "client-identity", + Command::new(std::env::current_exe()?) + .args([ + "--adapter", + "fastly", + "--suite", + "client-identity", + "--output", + ]) + .arg(&identity_output), + &repository_root(), + run, + records, + )?; + super::client_identity::validate_events(&read_events( + &identity_output.join("events.jsonl"), + CI_ARTIFACT_RECORDS, + )?)?; } return platforms::run(args, run, records); } diff --git a/crates/edgezero-test-harness/src/runners/client_identity.rs b/crates/edgezero-test-harness/src/runners/client_identity.rs new file mode 100644 index 000000000..d7c90608c --- /dev/null +++ b/crates/edgezero-test-harness/src/runners/client_identity.rs @@ -0,0 +1,639 @@ +//! Fastly client-identity (mTLS) contract against host-side origins that require +//! client certificates, under the pinned Viceroy. +//! +//! Certificates are generated per run. The origins record every TCP accept before +//! TLS starts, and separately record the client certificate of each completed +//! handshake, so "never sent" is checked against accepts, not inferred. + +use super::*; +use std::io::{ErrorKind, Read as _, Write as _}; +use std::net::TcpListener; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread::{self, JoinHandle}; + +use rcgen::{ + BasicConstraints, CertificateParams, CertifiedIssuer, DnType, ExtendedKeyUsagePurpose, IsCa, + KeyPair, KeyUsagePurpose, +}; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; +use rustls::server::WebPkiClientVerifier; +use rustls::{RootCertStore, ServerConfig, ServerConnection, StreamOwned}; +use sha2::{Digest as _, Sha256}; + +const BIN: &str = "fixture-fastly-client-identity"; +const IDENTITY: &str = "fixture-mtls"; +const CONFIG_STORE: &str = "fixture_mtls_config"; +const SECRET_STORE: &str = "fixture_mtls_secrets"; +/// Cases each launch scenario runs, in order; the suite event must report the total. +const EXPECTED_CASES: usize = 9; + +/// What one origin observed. +#[derive(Clone, Debug, Default)] +struct OriginRecords { + accepts: usize, + failures: Vec, + handshakes: Vec, +} + +struct Origin { + port: u16, + records: Arc>, + stop: Arc, + thread: Option>, +} + +struct ClientCertificate { + fingerprint: String, + key_pem: String, + pem: String, +} + +impl Origin { + /// Serves HTTPS one connection at a time. `redirect_to` answers `/redirect` + /// with a 302 to that port on localhost. + fn start(config: Arc, redirect_to: Option) -> Result { + let listener = TcpListener::bind(("127.0.0.1", 0))?; + listener.set_nonblocking(true)?; + let port = listener.local_addr()?.port(); + let records = Arc::new(Mutex::new(OriginRecords::default())); + let stop = Arc::new(AtomicBool::new(false)); + let thread = { + let records = Arc::clone(&records); + let stop = Arc::clone(&stop); + thread::spawn(move || { + while !stop.load(Ordering::SeqCst) { + match listener.accept() { + Ok((stream, _)) => { + records.lock().unwrap().accepts += 1; + serve(stream, &config, redirect_to, &records); + } + Err(error) if error.kind() == ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(5)); + } + Err(_) => break, + } + } + }) + }; + Ok(Self { + port, + records, + stop, + thread: Some(thread), + }) + } + + fn snapshot(&self) -> OriginRecords { + self.records.lock().unwrap().clone() + } + + /// Waits briefly for the origin thread to finish recording a connection. + fn settled(&self, accepts: usize) -> OriginRecords { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let records = self.snapshot(); + let finished = records.handshakes.len() + records.failures.len(); + if (records.accepts >= accepts && finished >= records.accepts) + || Instant::now() >= deadline + { + return records; + } + thread::sleep(Duration::from_millis(5)); + } + } +} + +impl Drop for Origin { + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +fn serve( + stream: std::net::TcpStream, + config: &Arc, + redirect_to: Option, + records: &Mutex, +) { + let _ = stream.set_nonblocking(false); + let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); + let _ = stream.set_write_timeout(Some(Duration::from_secs(5))); + let Ok(connection) = ServerConnection::new(Arc::clone(config)) else { + records.lock().unwrap().failures.push("server setup".into()); + return; + }; + let mut tls = StreamOwned::new(connection, stream); + while tls.conn.is_handshaking() { + if let Err(error) = tls.conn.complete_io(&mut tls.sock) { + records.lock().unwrap().failures.push(error.to_string()); + return; + } + } + let presented = tls + .conn + .peer_certificates() + .and_then(|chain| chain.first()) + .map(|leaf| hex(&Sha256::digest(leaf.as_ref()))); + let Some(fingerprint) = presented else { + records + .lock() + .unwrap() + .failures + .push("handshake completed without a client certificate".into()); + return; + }; + records.lock().unwrap().handshakes.push(fingerprint.clone()); + let mut head = Vec::new(); + let mut buffer = [0_u8; 1024]; + while !head.windows(4).any(|window| window == b"\r\n\r\n") && head.len() < 16 * 1024 { + match tls.read(&mut buffer) { + Ok(0) | Err(_) => break, + Ok(read) => head.extend_from_slice(&buffer[..read]), + } + } + let path = String::from_utf8_lossy(&head) + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .unwrap_or("/") + .to_owned(); + let response = match redirect_to { + Some(port) if path == "/redirect" => format!( + "HTTP/1.1 302 Found\r\nlocation: https://localhost:{port}/end\r\ncontent-length: 0\r\nconnection: close\r\n\r\n" + ), + _ => format!( + "HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{fingerprint}", + fingerprint.len() + ), + }; + let _ = tls.write_all(response.as_bytes()); + let _ = tls.flush(); + tls.conn.send_close_notify(); + let _ = tls.conn.complete_io(&mut tls.sock); +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn certificate_authority(name: &str) -> Result> { + let mut params = CertificateParams::new(Vec::::new())?; + params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + params.distinguished_name.push(DnType::CommonName, name); + params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + Ok(CertifiedIssuer::self_signed(params, KeyPair::generate()?)?) +} + +fn client_certificate( + issuer: &CertifiedIssuer<'static, KeyPair>, + name: &str, +) -> Result { + let mut params = CertificateParams::new(Vec::::new())?; + params.distinguished_name.push(DnType::CommonName, name); + params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; + let key = KeyPair::generate()?; + let certificate = params.signed_by(&key, issuer)?; + Ok(ClientCertificate { + fingerprint: hex(&Sha256::digest(certificate.der().as_ref())), + key_pem: key.serialize_pem(), + pem: certificate.pem(), + }) +} + +fn server_config(authority: &CertifiedIssuer<'static, KeyPair>) -> Result> { + let mut params = CertificateParams::new(vec!["localhost".to_owned()])?; + params + .distinguished_name + .push(DnType::CommonName, "localhost"); + params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + let key = KeyPair::generate()?; + let certificate = params.signed_by(&key, authority)?; + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let mut roots = RootCertStore::empty(); + roots.add(CertificateDer::from(authority.der().to_vec()))?; + let verifier = + WebPkiClientVerifier::builder_with_provider(Arc::new(roots), Arc::clone(&provider)) + .build()?; + let config = ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions()? + .with_client_cert_verifier(verifier) + .with_single_cert( + vec![CertificateDer::from(certificate.der().to_vec())], + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.serialize_der())), + )?; + Ok(Arc::new(config)) +} + +/// Writes a Viceroy config whose stores hold one identity binding. +fn write_config(path: &Path, client: &ClientCertificate, hosts: Option<&str>) -> Result<()> { + let mut contents = toml::Table::new(); + contents.insert( + format!("{IDENTITY}.certificate"), + toml::Value::String(client.pem.clone()), + ); + if let Some(origins) = hosts { + contents.insert( + format!("{IDENTITY}.hosts"), + toml::Value::String(origins.to_owned()), + ); + } + let mut config_store = toml::Table::new(); + config_store.insert("format".into(), "inline-toml".into()); + config_store.insert("contents".into(), toml::Value::Table(contents)); + let mut secret = toml::Table::new(); + secret.insert("key".into(), format!("{IDENTITY}.private-key").into()); + secret.insert("data".into(), client.key_pem.clone().into()); + let mut config_stores = toml::Table::new(); + config_stores.insert(CONFIG_STORE.into(), toml::Value::Table(config_store)); + let mut secret_stores = toml::Table::new(); + secret_stores.insert( + SECRET_STORE.into(), + toml::Value::Array(vec![toml::Value::Table(secret)]), + ); + let mut local_server = toml::Table::new(); + local_server.insert("config_stores".into(), toml::Value::Table(config_stores)); + local_server.insert("secret_stores".into(), toml::Value::Table(secret_stores)); + let mut root = toml::Table::new(); + root.insert("manifest_version".into(), 3.into()); + root.insert("name".into(), "client-identity-fixture".into()); + root.insert("language".into(), "rust".into()); + root.insert("local_server".into(), toml::Value::Table(local_server)); + fs::write(path, toml::to_string(&root)?)?; + Ok(()) +} + +/// One fixture call: `case` against `target`. +fn call(port: u16, case: &str, target: &str) -> Result { + let reply = net::request( + port, + &format!("/identity/{case}"), + &token(), + Some(target), + None, + )?; + guest(&reply) +} + +fn reason(report: &Value) -> &str { + report["reason"].as_str().unwrap_or("") +} + +/// Checks one report against origin A before and after the call, and origin B. +type Check<'a> = + Box Result<()> + 'a>; + +struct Expectation<'a> { + case: &'a str, + target: String, + check: Check<'a>, +} + +/// What every launch shares: the runtime, run directory, trusted CA and origins. +struct Launcher<'a> { + certificate_authority: &'a Path, + exe: &'a Path, + origin_a: &'a Origin, + origin_b: &'a Origin, + run: &'a Path, +} + +/// Runs one Viceroy launch and its cases. `before` and `after` are origin A's +/// records around each call; origin B must never see a connection. +fn run_scenario( + launcher: &Launcher<'_>, + scenario: &str, + (client, hosts): (&ClientCertificate, Option<&str>), + expectations: Vec>, + records: &mut Records, +) -> Result { + let Launcher { + certificate_authority, + exe, + origin_a, + origin_b, + run, + } = *launcher; + let config = run.join(format!("{scenario}.fastly.toml")); + write_config(&config, client, hosts)?; + let log = run.join(format!("{scenario}.runtime.log")); + let mut executed = 0; + let outcome = (|| -> Result<()> { + let port = net::port()?; + let mut command = fastly_command(exe, &config, run, "client-identity", port)?; + command.env("SSL_CERT_FILE", certificate_authority); + let mut process = Process::start(&mut command, &log, port)?; + for expectation in &expectations { + let before = origin_a.settled(origin_a.snapshot().accepts); + let report = call(port, expectation.case, &expectation.target)?; + let after = origin_a.settled(before.accepts); + let second = origin_b.snapshot(); + (expectation.check)(&report, &before, &after, &second).map_err(|error| { + format!("{scenario}/{}: {error}; report {report}", expectation.case) + })?; + require(second.accepts == 0, "origin B must never be connected")?; + records.push(json!({ + "event":"fastly-client-identity-case", "status":"pass", + "scenario":scenario, "case":expectation.case, "report":report, + "origin_accepts":after.accepts - before.accepts, + "qualification":false, + }))?; + executed += 1; + } + process.finish()?; + Ok(()) + })(); + settle( + records, + &log, + json!({"adapter":"fastly","suite":"client-identity","scenario":scenario,"qualification":false}), + json!({"phase":"client-identity"}), + outcome, + )?; + Ok(executed) +} + +fn unchanged(before: &OriginRecords, after: &OriginRecords) -> Result<()> { + require( + after.accepts == before.accepts, + "origin A recorded a TCP accept for a request that must fail before I/O", + ) +} + +pub(super) fn validate_events(events: &[Value]) -> Result<()> { + require( + !events.iter().any(|event| event["status"] == "fail"), + "failed client identity evidence", + )?; + let suites = events + .iter() + .filter(|event| event["event"] == "fastly-client-identity") + .collect::>(); + require( + suites.len() == 1 && suites[0]["status"] == "pass" && suites[0]["cases"] == EXPECTED_CASES, + "missing or incomplete client identity suite", + )?; + let cases = events + .iter() + .filter(|event| { + event["event"] == "fastly-client-identity-case" && event["status"] == "pass" + }) + .count(); + require( + cases == EXPECTED_CASES, + "client identity case evidence is incomplete", + ) +} + +pub(super) fn run(exe: &Path, parent: &Path, records: &mut Records) -> Result<()> { + let run = parent.join("client-identity"); + fs::create_dir_all(&run)?; + + let output = Command::new(exe).arg("--version").output()?; + require(output.status.success(), "Viceroy version command failed")?; + let version = String::from_utf8(output.stdout)?.trim().to_owned(); + let pins = fs::read_to_string(repository_root().join(".tool-versions"))?; + let pin = pins + .lines() + .find_map(|line| line.strip_prefix("viceroy ")) + .map(str::trim) + .ok_or("missing Viceroy pin")?; + require( + version.split_whitespace().nth(1) == Some(pin), + "client identity contract requires the pinned Viceroy runtime", + )?; + + let mut build = cargo_build()?; + if let Some(target) = std::env::var_os("CARGO_TARGET_DIR") { + build.env("CARGO_TARGET_DIR", target); + } + let built = build + .args([ + "build", + "--locked", + "--offline", + "--release", + "-p", + "fixture-fastly", + "--features", + "client-identity", + "--bin", + BIN, + "--target", + "wasm32-wasip1", + "--message-format=json-render-diagnostics", + ]) + .stderr(Stdio::from(fs::File::create(run.join("build.log"))?)) + .output()?; + fs::write(run.join("build.jsonl"), &built.stdout)?; + require( + built.status.success(), + "Fastly client identity fixture build failed", + )?; + let wasm = stage(&built_executable(&built.stdout, BIN)?, &run)?; + records.push(json!({ + "event":"build", "adapter":"fastly", "suite":"client-identity", + "variant":"fastly-client-identity", "target":"wasm32-wasip1", + "artifact":artifact(&wasm)?, "runtime":artifact(exe)?, "runtime_version":version, + }))?; + + let authority = certificate_authority("edgezero client identity test CA")?; + let unrelated = certificate_authority("unrelated test CA")?; + let client = client_certificate(&authority, "edgezero fixture client")?; + let replacement = client_certificate(&authority, "edgezero replacement client")?; + let wrong = client_certificate(&unrelated, "edgezero wrong-CA client")?; + let ca_path = run.join("ca.pem"); + fs::write(&ca_path, authority.pem())?; + let config = server_config(&authority)?; + let origin_b = Origin::start(Arc::clone(&config), None)?; + let origin_a = Origin::start(config, Some(origin_b.port))?; + let a = origin_a.port; + let hosts = format!("https://localhost:{a}"); + let launcher = Launcher { + certificate_authority: &ca_path, + exe, + origin_a: &origin_a, + origin_b: &origin_b, + run: &run, + }; + + let primary_fingerprint = client.fingerprint.clone(); + let mut executed = run_scenario( + &launcher, + "primary", + (&client, Some(&hosts)), + vec![ + Expectation { + case: "with", + target: format!("https://localhost:{a}/ok"), + check: Box::new(move |report, before, after, _| { + require( + report["outcome"] == "response" && report["status"] == 200, + "identity request must succeed", + )?; + require(after.accepts == before.accepts + 1, "one connection")?; + require( + after.handshakes.last() == Some(&primary_fingerprint), + "origin must see the configured client certificate", + ) + }), + }, + Expectation { + case: "without", + target: format!("https://localhost:{a}/ok"), + check: Box::new(|report, before, after, _| { + require( + report["outcome"] == "error" && report["reason"].is_null(), + "request without an identity must fail as a transport error", + )?; + require( + after.accepts == before.accepts + 1, + "the handshake is attempted", + )?; + require( + after.handshakes.len() == before.handshakes.len(), + "no client certificate is accepted", + )?; + require( + after.failures.len() > before.failures.len(), + "origin records a failed handshake", + ) + }), + }, + Expectation { + case: "undeclared", + target: format!("https://localhost:{a}/ok"), + check: Box::new(|report, before, after, _| { + require( + report["status"] == 500 && reason(report) == "Undeclared", + "undeclared identity", + )?; + unchanged(before, after) + }), + }, + Expectation { + case: "optimizer", + target: format!("https://localhost:{a}/ok"), + check: Box::new(|report, before, after, _| { + require( + reason(report).starts_with("Unsupported"), + "identity with Image Optimizer is unsupported", + )?; + unchanged(before, after) + }), + }, + Expectation { + case: "with", + target: format!("http://localhost:{a}/ok"), + check: Box::new(|report, before, after, _| { + require( + report["status"] == 500 && reason(report) == "RequiresHttps", + "identity requires https", + )?; + unchanged(before, after) + }), + }, + Expectation { + case: "follow", + target: format!("https://localhost:{a}/redirect"), + check: Box::new(|report, before, after, second| { + require( + report["status"] == 502 && report["hop"] == 1, + "redirect hop fails as a redirect failure", + )?; + require( + reason(report).contains("HostNotAllowed") + && reason(report).contains("redirect: true"), + "unlisted redirect target", + )?; + require( + after.accepts == before.accepts + 1, + "only the first hop is sent", + )?; + require( + second.accepts == 0, + "the unlisted origin is never connected", + ) + }), + }, + ], + records, + )?; + + executed += run_scenario( + &launcher, + "wrong-ca", + (&wrong, Some(&hosts)), + vec![Expectation { + case: "with", + target: format!("https://localhost:{a}/ok"), + check: Box::new(|report, before, after, _| { + require( + report["outcome"] == "error" && report["reason"].is_null(), + "wrong-CA certificate must fail as a transport error", + )?; + require( + after.handshakes.len() == before.handshakes.len(), + "no client certificate is accepted", + )?; + require( + after.failures.len() > before.failures.len(), + "origin rejects the certificate", + ) + }), + }], + records, + )?; + + let replacement_fingerprint = replacement.fingerprint.clone(); + executed += run_scenario( + &launcher, + "replaced", + (&replacement, Some(&hosts)), + vec![Expectation { + case: "with", + target: format!("https://localhost:{a}/ok"), + check: Box::new(move |report, _, after, _| { + require(report["status"] == 200, "replaced certificate must succeed")?; + require( + after.handshakes.last() == Some(&replacement_fingerprint), + "origin must see the replaced certificate", + ) + }), + }], + records, + )?; + + executed += run_scenario( + &launcher, + "missing-hosts", + (&client, None), + vec![Expectation { + case: "with", + target: format!("https://localhost:{a}/ok"), + check: Box::new(|report, before, after, _| { + require( + report["status"] == 503 + && reason(report).contains("MaterialMissing") + && reason(report).contains("Hosts"), + "missing hosts entry", + )?; + unchanged(before, after) + }), + }], + records, + )?; + + require( + executed == EXPECTED_CASES, + "unexpected client identity case count", + )?; + records.push(json!({ + "event":"fastly-client-identity", "adapter":"fastly", "status":"pass", + "cases":executed, "qualification":false, + }))?; + Ok(()) +} diff --git a/docs/guide/adapters/fastly.md b/docs/guide/adapters/fastly.md index 76b0ac7ca..ab42de0be 100644 --- a/docs/guide/adapters/fastly.md +++ b/docs/guide/adapters/fastly.md @@ -259,6 +259,69 @@ response chunks without whole-body collection. Synchronous source polls and host preempted, so downstream streaming and response-egress guarantees remain BestEffort. See [Capabilities](/guide/capabilities) before marking a capability required. +## Client Certificates + +Fastly presents a [client identity](/guide/proxying#client-certificates-mtls) on a dynamic +backend with `provide_client_certificate`. Provision three entries per identity ``: + +| Store | Entry | Contents | +| ----------------------------- | -------------------- | ------------------------------------------------------------------------ | +| Config Store (`config-store`) | `.certificate` | PEM chain, leaf first, at most 8,000 characters | +| Config Store (`config-store`) | `.hosts` | `https://host` or `https://host:port`, one per line, at most 4,000 bytes | +| Secret Store (`secret-store`) | `.private-key` | Unencrypted PEM private key | + +The certificate is public and the hosts list is not secret, so only the key uses the Secret +Store. EdgeZero opens the key as a `Secret` handle and never reads its plaintext. Fastly allows 5 +Secret Store reads per Compute request by default, shared with the application's own reads. The +config entries are read once per inbound request; the key is opened only when a backend must be +registered, so a request that reuses a registered backend spends no Secret Store read. Each +identity backend registration costs one read. + +Hosts use the outbound host grammar without wildcards: ASCII only (write internationalized names +in punycode), a missing port means 443, and every origin must be allowed by +`[capabilities.outbound].hosts`. A chain longer than 8,000 characters fails as `MaterialInvalid`. +EdgeZero checks only that the certificate entry contains PEM `CERTIFICATE` blocks; the origin's +handshake decides expiry, extended key usage and whether the key matches. + +The backend name includes the identity name and a SHA-256 over the whole certificate chain under +the `ez_b31v2_` prefix. Requests with and without an identity, different identities, and any change +to the chain, intermediates included, never share a backend or a pooled connection. Debug logs +show the leaf certificate's SHA-256, which matches `openssl x509 -fingerprint -sha256`. + +`edgezero build`, `serve` and `deploy` reject an identity whose config store or secret store +cannot be resolved from its explicit field or the declared default. + +### Rotation + +Overwrite `.certificate` in the Config Store and `.private-key` in the Secret Store in +quick succession, then confirm with a request. The two writes go to two stores and are not +atomic: a request that reads one new entry and one old entry presents a mismatched pair and fails +its handshake. The next inbound request reads both again, so the window closes once both writes +have propagated. A changed chain registers a new backend, so no request reuses a connection made +with the old certificate. + +### Local Development + +Viceroy reads the binding from `fastly.toml`. Viceroy reports a rejected handshake as a generic +`InternalError` rather than a TLS cause, and trusts the system roots; point `SSL_CERT_FILE` at a +test CA to trust a local origin's server certificate. + +```toml +# [local_server.config_stores.app_config] +# format = "inline-toml" +# [local_server.config_stores.app_config.contents] +# "prebid-server.certificate" = """ +# -----BEGIN CERTIFICATE----- +# ... +# -----END CERTIFICATE----- +# """ +# "prebid-server.hosts" = "https://pbs.example.com" +# +# [[local_server.secret_stores.default]] +# key = "prebid-server.private-key" +# file = "certs/prebid-server.key" +``` + ## Logging Fastly uses endpoint-based logging. Configure logging in `edgezero.toml`: diff --git a/docs/guide/capabilities.md b/docs/guide/capabilities.md index 055225746..93c9c8336 100644 --- a/docs/guide/capabilities.md +++ b/docs/guide/capabilities.md @@ -359,6 +359,7 @@ not included. These limitations block whole-response-lifetime certification. | `outbound-batch-completion-order` | Native | Native | BestEffort⁴ | Native | | `outbound-batch-slot-isolation` | Native | Native | BestEffort⁴ | Native | | `outbound-cache-bypass` | Native | Native | Native | Native | +| `outbound-client-identity` | Unsupported | Unsupported | Native | Unsupported | | `outbound-complete-resource-accounting` | Unsupported[^resource-accounting] | Unsupported[^resource-accounting] | Unsupported[^resource-accounting] | Unsupported[^resource-accounting] | | `outbound-connect-timeout` | BestEffort | BestEffort | Native[^connect-timeout] | BestEffort | | `outbound-header-fidelity` | Native | BestEffort⁸ | Native | BestEffort[^spin-header-fidelity] | @@ -665,6 +666,14 @@ need a build-time destination list. Fastly creates deterministic dynamic backend canonical target. Axum applies the same manifest validation even though the native client does not require provider host registration. +## Client Identities + +`outbound-client-identity` covers presenting a declared TLS client certificate on outbound +requests. Fastly reads the binding from a config store and a secret store and is `Native`. +Cloudflare, Spin and Axum reject identity requests before I/O until their bindings land. An +identity's runtime hosts list must stay inside `[capabilities.outbound].hosts`. See +[Client Certificates (mTLS)](/guide/proxying#client-certificates-mtls). + ## Limits And Accounting Each `OutboundRequest` owns independent limits: diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 67c178f7e..e142a8b91 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -85,6 +85,23 @@ Outbound hosts configure adapter plumbing rather than application authorization. See [Capabilities](/guide/capabilities) for the exact grammar, support matrix, and platform limitations. +### Client identities + +`[capabilities.outbound.client-identities.]` declares a TLS client identity that outbound +requests can select: + +```toml +[capabilities.outbound.client-identities.prebid-server] +config-store = "app_config" # optional; defaults to the [stores.config] default +secret-store = "default" # optional; defaults to the [stores.secrets] default +``` + +Names are 1 to 64 characters of `[a-z0-9-]` and cannot start or end with `-`. A named store must +be declared in `[stores.config]` or `[stores.secrets]`. The manifest requires neither kind of +store, but adapters that read the binding from stores, such as Fastly, reject an identity whose +stores cannot resolve. Hosts, certificates and keys are runtime bindings, not manifest fields. +See [Client Certificates (mTLS)](/guide/proxying#client-certificates-mtls). + ## HTTP Triggers The `[[triggers.http]]` array defines routes: diff --git a/docs/guide/proxying.md b/docs/guide/proxying.md index 3c4d0e87a..a8424f20f 100644 --- a/docs/guide/proxying.md +++ b/docs/guide/proxying.md @@ -173,6 +173,69 @@ metadata on that path, so tagged-default plus optimizer is rejected before uploa provider I/O, not accepted with a silently discarded purge tag. Signed HEAD bypass and a separate signed optimized GET retain their independent existing policies. +## Client Certificates (mTLS) + +An outbound request can present a TLS client certificate by naming a declared client identity. +The application never holds certificate or key bytes; the adapter resolves the name to its own +binding at runtime. + +```toml +[capabilities] +optional = ["outbound-http", "outbound-client-identity"] + +[capabilities.outbound.client-identities.prebid-server] +config-store = "app_config" # optional; defaults to the [stores.config] default +secret-store = "default" # optional; defaults to the [stores.secrets] default +``` + +```rust +use edgezero_core::{ClientIdentityName, OutboundRequest}; + +let identity = ClientIdentityName::new("prebid-server")?; +let request = OutboundRequest::post("https://pbs.example.com/openrtb2/auction")? + .client_identity(identity); +``` + +The manifest holds only the name and its logical stores. The hosts the certificate may be +presented to, the certificate and the key are bound at runtime, so operator configuration stays +out of the compiled binary. Names are 1 to 64 characters of `[a-z0-9-]` and cannot start or end +with `-`. + +On every adapter that supports identities: + +- The identity applies to one request. `HttpClient` has no default identity. +- A request that selects an identity is never sent without it. Every refusal below happens + before network I/O. +- The request's scheme, host and port must match one origin in the identity's runtime hosts + list. `host_authority_override` and the `Host` header are not compared. +- Redirect hops keep the identity and are checked again. A hop to an unlisted origin fails with + `OutboundFollowFailure::Hop { index, .. }` before it is sent. +- Identity responses always bypass the provider's response cache. An identity combined with + `PlatformDefaultWithSurrogateKey` or with Image Optimizer options is unsupported. + +Whether a request without an identity presents a certificate, and whether two identities can +target the same host, depend on the adapter. Spin attaches certificates by component and +destination host, so neither holds there once Spin support lands. + +Refusals surface as `EdgeError::ClientIdentity`; read the reason with +`EdgeError::client_identity_error()`: + +| `ClientIdentityError` | When | Status | +| ------------------------------------ | ------------------------------------------------------------------------------------------------ | ------ | +| `Undeclared` | The name is not declared in the manifest | 500 | +| `RequiresHttps` | The request URI is not `https` | 500 | +| `Unsupported { adapter }` | The adapter cannot present an identity, or an option cannot carry one | 500 | +| `MaterialMissing { which }` | A binding entry or its store is absent | 503 | +| `MaterialInvalid { which }` | A binding entry is malformed, oversized, or lists a host outside `[capabilities.outbound].hosts` | 503 | +| `HostNotAllowed { redirect: false }` | The request's origin is not in the identity's hosts | 503 | +| `HostNotAllowed { redirect: true }` | A redirect hop's origin is not in the identity's hosts | 502 | + +A read that hits the request deadline keeps the ordinary `GatewayTimeout`. An origin that rejects +the handshake is a transport failure with the provider's TLS cause where the provider reports one. + +Only Fastly presents identities today; Cloudflare, Spin and Axum reject them with `Unsupported`. +See [Fastly client certificates](/guide/adapters/fastly#client-certificates) for its binding. + ## Following Redirects `HttpClient::follow` is an explicit per-call choice with a mandatory target policy and hop limit. diff --git a/docs/superpowers/plans/2026-11-23-outbound-client-identity.md b/docs/superpowers/plans/2026-11-23-outbound-client-identity.md new file mode 100644 index 000000000..5f567afc8 --- /dev/null +++ b/docs/superpowers/plans/2026-11-23-outbound-client-identity.md @@ -0,0 +1,326 @@ +# Outbound client identity (mTLS) implementation plan + +Status, 2026-11-23: tasks 0 to 8 implemented through `d1d02171`; local gates and the Fastly ci suite pass. PR #524 is open and task 10 is done. Revised after review: the Fastly binding moved the certificate and hosts to the Config Store and reads it once per inbound request; identity requests bypass the response cache; the fingerprint covers the whole chain; core builds the policy from the baked manifest and attaches it to each request's client at dispatch. + +Worktree: `/home/pav/worktrees/feat-523-outbound-client-identity`, branch `feat/523-outbound-client-identity`, based on `origin/feat/474-portable-record-providers` at `6fb738491584d432516af9e0ec13281f0823ffdd`. The spec commit `2b08eac6` is the first commit on the branch. + +The [agreed design](../specs/2026-11-23-outbound-client-identity-design.md) owns behavior. This file owns implementation tasks and verification. Deliver one EdgeZero PR that closes [#523](https://github.com/IABTechLab/edgezero/issues/523), based on #464, which stacks on #517. The original implementation was tested on #522; the historical evidence below refers to that baseline. + +## Delivery contract + +- Core owns the manifest schema, the identity policy built from `Hooks::manifest()` and attached to each request's `HttpClient` at dispatch, `ClientIdentityName`, the declaration and scheme checks, host parsing and matching, the error type, and redirect handling. Adapters own support checks and runtime binding. +- Fastly reads `.certificate` and `.hosts` from the identity's Config Store, and `.private-key` from its Secret Store as a `fastly::secret_store::Secret` handle only. It does this at most once per identity per inbound request. +- Identity requests always bypass Fastly's response cache. Identity plus a surrogate-key cache policy, or plus Image Optimizer, is `Unsupported`. +- The Fastly backend name covers the identity name and the SHA-256 of the whole certificate chain, under the `ez_b31v2_` prefix. Requests without an identity get new names too, because the prefix changes. +- Cloudflare, Spin and Axum reject identity requests before I/O and report the capability as `Unsupported`. +- Every rule in the spec's dispatch section fails before network I/O. +- Merge evidence is local: native tests, the Fastly Viceroy runner with host-side mutual-TLS origins, and the repository gates. There is no hosted check. + +## Execution order + +```mermaid +flowchart TB + A[0. Facts and baseline] --> B[1. Manifest schema, capability and CLI check] + B --> C[2. Identity policy on App and at dispatch] + C --> D[3. Core request contract, errors and host rules] + D --> E[4. Core dispatch and redirect checks] + E --> F[5. Unsupported adapters] + E --> G[6. Fastly binding, cache bypass and backend naming] + G --> H[7. Viceroy runner and fixture] + F --> I[8. Documentation] + H --> I + I --> J[9. Stable gates and evidence] + J --> K[10. Issue closeout] +``` + +Each numbered unit ends with its focused tests before the next dependent unit starts. Run the affected `cargo test` selections after every code change. New type, function, feature, binary and test names below are planned names, not existing APIs. + +## 0. Confirm facts and establish the baseline + +- [x] Confirm HEAD's parent is `6fb73849` and the worktree is clean apart from this plan. +- [x] Run focused baselines before changes and record counts here: `edgezero-core` outbound, redirect and manifest tests; `edgezero-macros` tests; Fastly native outbound tests, including the `ez_b31v1_` golden-name test near `outbound.rs:5801`; `edgezero-adapter` registry tests; `edgezero-cli` capability tests; and the harness's own unit tests. +- [x] Probe the patched Viceroy from `patches/viceroy` with a throwaway guest and record the results here: + - It reads a certificate and a hosts list from `[local_server.config_stores]`. + - It opens a key from `[local_server.secret_stores]` with `SecretStore::open(alias)` then `try_get(key)`, and passes the `Secret` to `provide_client_certificate` without any plaintext call. + - It registers a dynamic backend against a local rustls origin that requires client certificates, while Viceroy runs with `SSL_CERT_FILE` pointing at the probe CA. + - The handshake succeeds and the origin sees the client certificate. + + Viceroy `0.21.0` builds its roots with `rustls-native-certs` `0.6.3`, which honors `SSL_CERT_FILE`, and it applies `client_cert` for HTTPS backends. The probe confirms both at runtime. +- [x] Confirm `rcgen` with the `aws_lc_rs` feature and `rustls =0.23.46` resolve for the harness's separate workspace. Fetching them updates `crates/edgezero-test-harness/Cargo.lock` intentionally. Every later command runs `--offline`. + +Exit: no fact contradicts the spec. If one does, stop and report it rather than change the design. + +## 1. Manifest schema, capability and CLI check + +Files: `crates/edgezero-core/src/manifest.rs`, `crates/edgezero-adapter/src/registry.rs`, `crates/edgezero-adapter-fastly/src/cli.rs`, `crates/edgezero-cli/src/adapter.rs`. + +- [x] Add `client_identities: BTreeMap` to `ManifestOutboundCapability` (`manifest.rs:401`), serialized as `client-identities`. `ClientIdentityDeclaration { secret_store: Option, config_store: Option }` uses `deny_unknown_fields` and serializes as `secret-store` and `config-store`. +- [x] Validate names as `[a-z0-9-]`, 1 to 64 characters, not starting or ending with `-`. Share this validator with `ClientIdentityName` in task 3. +- [x] Add a `Manifest`-level schema validator beside `validate_capabilities_disjoint`. It requires any named `secret-store` to be declared in `[stores.secrets]`, and any named `config-store` in `[stores.config]`. It does not require either kind of store to exist. +- [x] Add `Capability::OutboundClientIdentity`, written `outbound-client-identity`, to the enum and to `as_str` (`manifest.rs:86`, `:131`). +- [x] Add `AtomicHost::permits(scheme, host, port) -> bool`, so a concrete origin can be tested against a canonical allowlist entry, wildcards included. Unit-test wildcard host, wildcard port, exact match and scheme mismatch. +- [x] Fastly's `capability()` (`edgezero-adapter-fastly/src/cli.rs:2040`) maps the new capability to `Native`. Axum, Cloudflare and Spin keep the `_ => Unsupported` arm. +- [x] Add `Adapter::validate_client_identities(&self, manifest: &Manifest) -> Result<(), String>` to `registry.rs`, defaulting to `Ok(())`. Call it from `ensure_capabilities` (`edgezero-cli/src/adapter.rs:422`) when the baked manifest is present. Fastly's version resolves each identity's secret and config store from its explicit field or the declared default, and names every identity it can't resolve. +- [x] Tests: + - Manifest: valid declarations, explicit and default stores, unknown stores, a manifest with identities and no stores (valid), bad names, an unknown field in an entry, and a round trip. + - Registry: the capability's support level on all four adapters. + - CLI: `required = ["outbound-client-identity"]` fails for Axum, Cloudflare and Spin and passes for Fastly. Fastly's identity check passes with resolvable stores and fails when either store is missing. + +Exit: manifest, registry and CLI tests pass. Nothing at runtime reads the new data yet. + +## 2. Identity policy on App and at dispatch + +Files: `crates/edgezero-core/src/app.rs`, a new `crates/edgezero-core/src/outbound/client_identity.rs`, `crates/edgezero-core/src/outbound.rs` (`HttpClient`). + +- [x] Add `ClientIdentityMetadata { name, secret_store: Option, config_store: Option }` and `ClientIdentityPolicy`. The policy holds the declared identities with their stores resolved, and the outbound allowlist as canonical `AtomicHost` entries (default `https://*:*`). +- [x] Build it in `App::from_router::` (`app.rs:466`) from `A::manifest()`, as an `Arc` field next to `name`. `Absent` and `Malformed` yield an empty policy. Constructors that don't take `Hooks` get an empty policy. Expose `App::client_identity_policy()`. No new `Hooks` methods and no macro changes. +- [x] Add a private `client_identity_policy: Option>` to `HttpClient` (`outbound.rs:436`), with `HttpClient::with_client_identity_policy` and a crate-private setter that only fills an empty slot. +- [x] In `dispatch_admitted_with_request_facts` (`app.rs`, the function every `dispatch_admitted*` and `dispatch_ingress` path reaches), before routing, give the app's policy to the `HttpClient` in the request's extensions when that client has none. Leave every other extension unchanged. +- [x] Tests: + - A manifest with two identities and an explicit allowlist produces the expected policy. Default stores resolve. Absent and malformed manifests give an empty policy. A macro-generated test app gives the same policy as its manifest. + - Through `dispatch_admitted`, a handler's `ctx.http_client()` carries the app's policy. So does a client supplied by a preparation hook. A client that already carries a policy keeps it. A request without an `HttpClient` gains none. + +Exit: core and macro tests pass. Handlers' clients carry the policy, and nothing enforces it yet. + +## 3. Core request contract, errors and host rules + +Files: `crates/edgezero-core/src/outbound.rs`, `outbound/client_identity.rs`, `outbound/redirect.rs`, `error.rs`, `context.rs`, `response_egress_framing.rs`, `lib.rs` re-exports. + +- [x] Add `ClientIdentityName` with `new`, `as_str`, `Display` and `Debug`. +- [x] Add the `client_identity` field to `OutboundRequest` (`outbound.rs:309`) and `OutboundRequestParts`, carried through `from_parts`, `into_parts` and `replay_request` (`redirect.rs`, which destructures every field). Do not strip it in `prepare_redirect`. Add the builder and getter. +- [x] Add `ClientIdentityError` with the spec's variants and a `which` enum (`Certificate`, `Key`, `Hosts`, `Store`). Add `EdgeError::ClientIdentity { name, reason }`, with `wire_status` and `wire_kind` on the reason, following `StoreExtractionReason` (`error.rs:78`). Statuses: + - 500: `Undeclared`, `RequiresHttps`, `Unsupported`. + - 503: `MaterialMissing`, `MaterialInvalid`, `HostNotAllowed { redirect: false }`. + - 502: `HostNotAllowed { redirect: true }`. +- [x] Update every exhaustive `EdgeError` match: `status`, `kind`, `message`, and the arms at `error.rs:368`, `:411`, `:428`, `:497`, `:577` and `:793`, plus `context.rs:192`/`:240`/`:292` and `response_egress_framing.rs:300`. Add `EdgeError::client_identity_error() -> Option<&ClientIdentityError>`. +- [x] Add `ClientIdentityHosts::parse(bytes, &ClientIdentityPolicy) -> Result` and `ClientIdentityHosts::check(&Uri) -> Result<(), ClientIdentityError>`, following the spec's parsing rules. +- [x] `Display` and `Debug` for the new error show the name, reason, fingerprint when present, and the request's scheme, host and port for `HostNotAllowed`. Test that they never include paths, queries, PEM text or entry contents. +- [x] Unit tests: name validation; builder round trip through parts and replay; each error's status and kind; every parse and check case in the spec's testing table; a host-override request passing the check. + +Exit: core unit tests pass. Dispatch does not enforce anything yet. + +## 4. Core dispatch and redirect checks + +Files: `crates/edgezero-core/src/outbound.rs` (`HttpClient`), `outbound/dispatch.rs`, `outbound/redirect.rs`. + +- [x] Clients without a policy (task 2) treat every identity as undeclared. +- [x] In `dispatch::prepare` (`dispatch.rs:80`), after `validate_supported_options` and before `validate_for_dispatch`, return `Undeclared` for names not in the policy and `RequiresHttps` for non-`https` URIs. Attach the resolved `ClientIdentityMetadata` and a handle to the policy to `OutboundDispatchRequest`, exposed as `OutboundDispatchRequest::client_identity()`, so adapters don't repeat the lookup. +- [x] In `FollowChain::hop` (`redirect.rs:109`), when the hop index is above zero, turn `HostNotAllowed { redirect: false }` into `redirect: true`. +- [x] Tests with a recording fake `OutboundHttpClient`, asserting that none of these makes a dispatch call: an undeclared identity, `http://`, and a client without a policy. A same-origin redirect and a redirect to another listed host are dispatched with the identity. A redirect to an unlisted host fails as `Hop { index: 1 }` with status 502. In batches, a failing identity slot fails alone and the other slots complete. + +Exit: core outbound and redirect suites pass, including the existing ones without changes. + +## 5. Unsupported adapters + +Files: `validate_supported_options` in `crates/edgezero-adapter-cloudflare/src/outbound.rs:3845`, `crates/edgezero-adapter-spin/src/outbound.rs` and `crates/edgezero-adapter-axum/src/outbound.rs`. + +- [x] Return `EdgeError::ClientIdentity { reason: Unsupported { adapter } }` when `client_identity_name()` is set. +- [x] Each adapter gets a test showing an identity request fails before its transport is touched, using the adapter's existing recording or native seam. + +Exit: adapter unit tests pass on native and on their wasm targets (`wasm32-unknown-unknown` for Cloudflare, `wasm32-wasip2` for Spin). + +## 6. Fastly binding, cache bypass and backend naming + +Files: `crates/edgezero-adapter-fastly/src/outbound.rs`, a new `src/outbound/client_identity.rs`, `src/config_store.rs`, `src/secret_store.rs`. + +- [x] Fastly's `validate_supported_options` (`outbound.rs:6946`) rejects, in every mode, an identity combined with Image Optimizer options or with `OutboundCachePolicy::PlatformDefaultWithSurrogateKey`, as `Unsupported`. +- [x] Add a per-request binding cache to `FastlyOutboundClient`. It's a `Mutex>`, because `OutboundHttpClient` is `Send + Sync`. The client is built per inbound request, so the cache's lifetime is one request. + - It caches successful bindings, and `MaterialMissing` and `MaterialInvalid` outcomes, so a broken binding doesn't spend more reads in the same request. + - It doesn't cache a deadline (`GatewayTimeout`), so a later dispatch with more budget can try again. +- [x] Add `resolve_binding(metadata, budget, clock)`: + - Resolves the store IDs from the policy. A missing store becomes `MaterialMissing { which: Store }`. + - Opens the config store alias and reads `.hosts` (4,000-character cap) and `.certificate` (8,000 characters) through the bounded config read (`config_store.rs:176`). An absent entry becomes `MaterialMissing`, an oversized one `MaterialInvalid`, and a deadline keeps `GatewayTimeout`. + - Opens the secret store alias and gets `.private-key` with `try_get` as a `Secret` handle, never reading its plaintext. + - Parses the hosts with `ClientIdentityHosts::parse`. + - Decodes every PEM `CERTIFICATE` block to DER. The chain fingerprint is SHA-256 over each DER length-prefixed in order. The leaf's own SHA-256 is kept for logs. +- [x] On every dispatch with an identity, get the binding from the cache or `resolve_binding`, then call `ClientIdentityHosts::check` on the request URI. +- [x] `build_fastly_request` (`outbound.rs:1132`) calls `set_pass(true)` for identity requests, whatever cache policy is set. +- [x] Add `client_identity: Option<(String, [u8; 32])>` to `BackendIdentity` (`outbound.rs:542`). In `backend_name` (`:1038`), hash a `client-identity-v1` tag, the name, a zero byte and the chain fingerprint when present, and change the prefix to `ez_b31v2_`. Regenerate the golden name near `:5801`, and state in the test why it changed. +- [x] Resolve the binding in the dispatch preparation before `ensure_backend` (`:707`), inside the existing budget checks. Pass the certificate PEM and `Secret` to `ensure_backend` (`:628`), which calls `provide_client_certificate` after the TLS settings and changes nothing else. +- [x] `RequestPlan::new` (`:565`) can't know an identity request's backend name before the binding is read. Its `is_registered` therefore reports identity requests as not registered, which keeps them out of the warm-first batch ordering. +- [x] Log the name and leaf fingerprint at debug level when a new identity backend registers. Never log the key, the certificate text or the hosts entry. +- [x] Native tests: + - `backend_name` differs for no identity, two identities, and two chains for one identity, and is equal for one identity with one chain. + - Changing only an intermediate changes the chain fingerprint. + - Against `cached_backend` with an injected registration, the same identity with a changed chain registers a new backend while the old entry stays cached. + - Missing, oversized and malformed entries, and a missing store, map to their reasons. + - Identity requests build with `pass` set under each cache policy that's accepted. The surrogate-key and Image Optimizer combinations are rejected. + - Two dispatches and a redirect hop with one identity in one client read each entry once. A cached `MaterialMissing` isn't re-read. A deadline outcome is. + +Exit: Fastly native tests pass, and the adapter builds for `wasm32-wasip1` with `--features fastly`. + +## 7. Viceroy runner and fixture + +Files: +- A new `crates/edgezero-test-harness/fixtures/reusable-app/crates/fixture-fastly/src/bin/client_identity.rs`, with its `edgezero.toml`. +- That crate's `Cargo.toml`: feature `client-identity`, binary `fixture-fastly-client-identity`. +- A new `crates/edgezero-test-harness/src/runners/client_identity.rs`, plus `src/runners.rs`, `src/runners/ci.rs` and `src/main.rs`. +- The harness `Cargo.toml` and `Cargo.lock`. + +Work: + +- [x] Fixture binary built with `app!` and a small `edgezero.toml`. The manifest declares `fixture-mtls`, with `secret-store = "fixture_secrets"` and `config-store = "fixture_config"`, and the default outbound allowlist. If `app!` can't build inside the fixture workspace, override `Hooks::manifest()` with `Manifest::from_baked_json`, and record why here. Routes: + - `/identity?target=&identity=<0|1>` sends a GET with or without the identity. It returns JSON with the status, body, `EdgeError` kind, `ClientIdentityError` reason and redirect hop index. + - `/identity-io?target=` sends with Image Optimizer options set. + - `/identity-undeclared?target=` uses an undeclared name. + - `/identity-follow?target=&limit=` follows redirects with the identity. +- [x] Runner `client-identity`, for Fastly only, built like `record_contract::run` (`runners/record_contract.rs:199`): + 1. Check the pinned Viceroy version and build the fixture binary for `wasm32-wasip1`. + 2. Generate with `rcgen` a per-run CA, `localhost` server certificates, a client certificate with the `clientAuth` EKU, a second client certificate from an unrelated CA, and a replacement client certificate from the first CA. + 3. Start two rustls origins on loopback ports. Origin A requires client certificates from the first CA, answers with the presented certificate's fingerprint, and has a route that redirects to origin B. Origin B is not in the hosts entry. + 4. Each origin records every TCP accept before TLS starts, and separately records the client certificate from each completed handshake. + 5. Write a per-run `fastly.toml`, copied from the fixture with generated `[local_server.config_stores.fixture_config]` entries for `fixture-mtls.certificate` and `fixture-mtls.hosts` (`https://localhost:`), and a `[[local_server.secret_stores.fixture_secrets]]` entry for `fixture-mtls.private-key`. Launch Viceroy with `SSL_CERT_FILE` set to the per-run CA file. +- [x] Runner cases and assertions: + - With the identity: 200, and origin A's handshake record shows the client certificate. + - Without the identity: the guest reports a transport error. Origin A records a TCP accept, a failed handshake and no accepted client certificate. Viceroy doesn't fill in send-error detail ([Viceroy#727](https://github.com/fastly/Viceroy/issues/727)), so the runner records the cause it reports (`InternalError` in task 0) without asserting it. + - A wrong-CA certificate (relaunch with those entries): the same transport error, and origin A records a failed handshake that rejected the presented certificate. + - A replaced certificate (relaunch): 200, and the handshake record shows the new certificate. + - Undeclared name: 500 `Undeclared`, and origin A records no TCP accept. + - Image Optimizer: `Unsupported`, and origin A records no TCP accept. + - `http://` target: 500 `RequiresHttps`, and neither origin records a TCP accept. + - A redirect from A to B: 502 `HostNotAllowed`, hop index 1, and origin B records no TCP accept. + - Missing `fixture-mtls.hosts` (relaunch without it): 503 `MaterialMissing`, and origin A records no TCP accept. + - Hosts entry outside the allowlist: covered natively in task 3, because the fixture's allowlist is the default `https://*:*`. +- [x] The runner writes events and a receipt in the record-contract style. Add `validate_events` and wire it into the `ci` suite (`runners/ci.rs:240`). Restrict the suite name to `--adapter fastly` in `main.rs:113`, and add the matching parse test. + +Viceroy loads its stores at startup, so the runtime cases prove a replaced certificate is read after a restart. The warm-registry case is proved natively in task 6. + +Exit: `scripts/test_integration.sh --adapter fastly --suite client-identity` passes with the patched Viceroy, and the `ci` suite includes it. + +## 8. Documentation + +- [x] `docs/guide/proxying.md`: a "Client certificates (mTLS)" section covering the manifest, `.client_identity()`, what application code can rely on, the host rules, redirects, the response-cache bypass, the error table and adapter support. +- [x] `docs/guide/adapters/fastly.md`: the three entries and their stores, PEM format, the key-handle rule, the Secret Store read budget, rotation and its non-atomic window, the backend-name change, and commented `[local_server.config_stores]` and `[local_server.secret_stores]` examples. +- [x] `docs/guide/capabilities.md`: add `outbound-client-identity` to the matrix. +- [x] `docs/guide/configuration.md`: `[capabilities.outbound.client-identities.]` with `secret-store` and `config-store`. +- [x] Code examples compile through existing doc tests, or match tested fixture code. + +## 9. Stable gates and evidence + +### Focused and stable command record + +```sh +export RUSTUP_TOOLCHAIN=1.98.1 +export CARGO_NET_OFFLINE=true + +# Focused +cargo +1.98.1 test --locked --offline -p edgezero-core --features test-utils outbound +cargo +1.98.1 test --locked --offline -p edgezero-core manifest +cargo +1.98.1 test --locked --offline -p edgezero-core app +cargo +1.98.1 test --locked --offline -p edgezero-macros +cargo +1.98.1 test --locked --offline -p edgezero-adapter +RUST_TEST_THREADS=1 cargo +1.98.1 test --locked --offline -p edgezero-cli `, which every adapter reaches through `App::build::()`, builds a `ClientIdentityPolicy` from it once, the same way it already takes `A::name()`: + +```rust +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClientIdentityMetadata { + pub name: String, + /// Resolved logical `[stores.secrets]` id, if one could be resolved. + pub secret_store: Option, + /// Resolved logical `[stores.config]` id, if one could be resolved. + pub config_store: Option, +} + +pub struct ClientIdentityPolicy { + // declared identities, plus [capabilities.outbound].hosts as canonical AtomicHost entries +} + +impl App { + /// Shared with each request's `HttpClient` by reference count. + pub fn client_identity_policy(&self) -> &Arc; +} +``` + +- No new `Hooks` methods and no new macro code. An absent or malformed baked manifest yields an empty policy, so every identity request fails as `Undeclared`. +- Every adapter dispatches through `App::dispatch_admitted_with_client_info` or `App::dispatch_ingress`, and both end in `dispatch_admitted_with_request_facts`, which already attaches Geo and ClientInfo to the request. There, core gives the policy to the `HttpClient` in the request's extensions, unless that client already carries one. That covers adapter-built clients and clients supplied by preparation hooks. +- Apps that build an `App` without `Hooks::manifest()` get an empty policy, and identity requests fail as `Undeclared`. +- The policy also carries the outbound allowlist. Today that allowlist is checked only against Spin's `allowed_outbound_hosts`, by the CLI at build time. The host check below needs it at runtime. It comes from the tracked manifest, so using it at runtime adds no operator configuration to the binary. +- `App` is retained across requests under `serve_app`, so the policy is built once per instance. + +## Request contract + +```rust +/// Validated identity name, using the manifest's naming rules. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct ClientIdentityName(/* private */); + +impl ClientIdentityName { + pub fn new(name: &str) -> Result; + pub fn as_str(&self) -> &str; +} + +impl OutboundRequest { + /// Present this declared client identity on the TLS connection. + pub fn client_identity(self, name: ClientIdentityName) -> Self; + pub fn client_identity_name(&self) -> Option<&ClientIdentityName>; +} + +pub struct OutboundRequestParts { + // existing fields unchanged + pub client_identity: Option, +} +``` + +- The identity is set on a single request. `HttpClient` has no default identity. +- `replay_request` in `outbound/redirect.rs` destructures every field, so the new field joins it and redirect hops carry the identity forward. Cross-origin hops keep it as well. They do not strip it the way they strip `Authorization`, `Cookie` and the host override. The host rule below decides whether such a hop may be sent. +- Core attaches the app's policy to the request's `HttpClient` at dispatch (see [Identity policy](#identity-policy)). Adapters don't pass it. Clients that never pass through dispatch, such as ones built directly in tests, have no policy and treat every identity as undeclared. + +## Dispatch rules + +```mermaid +flowchart TD + A["OutboundRequest with client_identity(name)"] --> B["Adapter validate_supported_options"] + B -- "adapter lacks support, Image Optimizer set, or surrogate-key cache policy" --> U["Unsupported"] + B --> C["Core prepare: declared? https?"] + C -- "not in the identity policy" --> UD["Undeclared"] + C -- "scheme is not https" --> RH["RequiresHttps"] + C --> D["Adapter resolves binding once per inbound request"] + D -- "entry or store absent" --> MM["MaterialMissing"] + D -- "malformed, oversized, or a host outside the outbound allowlist" --> MI["MaterialInvalid"] + D --> E["Core ClientIdentityHosts::check(request URI)"] + E -- "scheme/host/port not listed" --> HN["HostNotAllowed"] + E --> F["Adapter attaches certificate, bypasses the response cache, and dispatches"] + F -- "redirect to be followed" --> C + F -- "origin rejects handshake" --> T["Existing TLS failure causes"] +``` + +All of these checks run before any network I/O, on the initial request and on every redirect hop. + +1. **Adapter support.** `OutboundHttpClient::validate_supported_options` rejects an identity when the adapter lacks support. On every adapter it also rejects an identity combined with Image Optimizer options, or with `OutboundCachePolicy::PlatformDefaultWithSurrogateKey`: + - #275 sends Image Optimizer requests through a separate Fastly path, and nothing shows that path can present a client certificate. + - The surrogate-key policy exists only to manage cached objects, and identity responses are never cached (rule 5). +2. **Declaration and scheme.** `dispatch::prepare` looks up the name in the client's identity policy and requires `https`. This runs in core, so every adapter returns the same errors. +3. **Binding.** The adapter resolves the identity's runtime binding at most once per inbound request. Later hops and later calls in the same inbound request reuse it. The next inbound request reads it again, so rotation takes effect on the next request. On Fastly the binding is two config entries and one Secret Store entry, read through #275's bounded reads, so the reads count against the dispatch deadline. +4. **Hosts.** Core parses the hosts entry with `ClientIdentityHosts::parse(bytes, allowlist)`, and the adapter calls `ClientIdentityHosts::check(uri)` on every hop. Both are core functions, so parsing and matching are identical across adapters even though only the adapter can read the entry. Parsing rules: + - One origin per line: `https://host` or `https://host:port`. No path, query, userinfo or wildcard. Blank lines are ignored. A missing port means 443. Hosts follow the outbound allowlist grammar: ASCII only, so internationalized names are written in punycode, and compared lowercase. + - At least one origin. + - Every origin must be allowed by the outbound allowlist in the identity policy. If any origin isn't, the whole identity fails as `MaterialInvalid`, so a provisioning mistake shows up on the first request instead of the first request to that host. + - The check compares the request URI's scheme, host and port, which is where the connection goes. `host_authority_override` and the `Host` header are not compared, and overriding `Host` on an allowed origin stays permitted. +5. **Response cache.** An identity request always bypasses the provider's response cache, as if `OutboundCachePolicy::Bypass` were set. Fastly's default cache key is the request URL and `Host` header, without the backend or certificate. A cached identity response could otherwise be served to a request without the identity, and a cache hit would skip the handshake. Requests without an identity keep their cache behavior. +6. **Attach and send.** See [Fastly binding](#fastly-binding). + +Redirects need no separate code path. Each hop goes through `dispatch::prepare` and the adapter's dispatch again. A hop to an origin outside the hosts list fails with `HostNotAllowed` before it is sent. The follower reports it as `OutboundFollowFailure::Hop { index, .. }`, and because it knows the hop index, it marks the error as a redirect failure. + +Batches (`send_all_until`, `start_batch_until`) apply the same rules to each slot. A slot that fails a rule fails alone, under the existing slot-isolation behavior. + +## Errors + +Add `EdgeError::ClientIdentity { name: String, reason: ClientIdentityError }`. It follows `StoreExtraction`, where the reason chooses the HTTP status: + +| `ClientIdentityError` | When | Status | +| --- | --- | --- | +| `Undeclared` | The name is not in the identity policy | 500. The application references an identity its manifest doesn't declare | +| `RequiresHttps` | The request URI is not `https` | 500. Application bug | +| `Unsupported { adapter: &'static str }` | The adapter lacks support, Image Optimizer options are set, or the cache policy carries surrogate keys | 500. Application or deployment-target bug | +| `MaterialMissing { which: Certificate \| Key \| Hosts \| Store }` | An entry is absent, a store can't be resolved or opened | 503, like `MissingSecret` | +| `MaterialInvalid { which }` | The certificate entry has no PEM `CERTIFICATE` block, an entry exceeds its size cap, or the hosts entry is malformed or outside the outbound allowlist | 503 | +| `HostNotAllowed { redirect: bool }` | The request origin isn't in the identity's hosts | 503 on the initial request, which is a deployment mismatch. 502 on a redirect hop, because the upstream sent the redirect | + +- A bounded read that hits the deadline keeps #275's existing `GatewayTimeout`. Identity errors do not mask timeouts. +- An origin that rejects the handshake surfaces through the existing provider failure causes (`TlsCertificateError`, `TlsAlertReceived`, `TlsConfigurationError`) with no new mapping. A mismatched certificate and key, for example during rotation, fails the same way. Viceroy never fills in send-error detail ([Viceroy#727](https://github.com/fastly/Viceroy/issues/727)), so locally the guest sees a generic `InternalError` instead, and local tests don't check these causes. +- `Display` and `Debug` show the identity name and the reason. They never show key bytes or PEM contents. For `HostNotAllowed` they show the request's scheme, host and port, never the path or query. + +## Fastly binding + +### Entries + +Only the private key needs the Secret Store. The certificate is public, and the hosts list isn't secret. Fastly allows 5 Secret Store reads per Compute request by default, and the application shares that budget. Fastly lists no per-request read limit for the Config Store. So the binding spends one Secret Store read: + +| Store | Entry | Contents | Read | Cap | +| --- | --- | --- | --- | --- | +| Config Store (`config-store`) | `.certificate` | PEM chain, leaf first | Bounded config read | 8,000 characters, Fastly's config value limit | +| Config Store (`config-store`) | `.hosts` | Origins, one per line | Bounded config read | 4,000 characters | +| Secret Store (`secret-store`) | `.private-key` | Unencrypted PEM private key | `fastly::secret_store::Secret` handle only. Never `plaintext()`, `try_plaintext()` or a bounded read | Fastly's 64 KB secret limit | + +- Both stores open through the same resource-link aliases that `run_app` uses for `[stores.config]` and `[stores.secrets]` IDs. +- A chain longer than 8,000 characters fails as `MaterialInvalid`. A leaf plus one intermediate is usually 2 to 5 KB of PEM. Chunked storage for longer chains is a follow-up, if an operator needs it. +- The key handle stays inside the Fastly adapter. Core gets no portable secret-handle type, and the portable `SecretStore` trait still returns bytes. +- EdgeZero checks only that the certificate entry holds at least one PEM `CERTIFICATE` block that decodes to DER. It does not check expiry, the `clientAuth` EKU, or whether the key matches. The origin's handshake decides those. +- The certificate fingerprint is the SHA-256 of every certificate in the entry, each DER encoding length-prefixed, in entry order. So replacing only an intermediate also changes it. Logs show the leaf certificate's own SHA-256, which is what operators can compare against `openssl x509 -fingerprint -sha256`. + +### Reads per inbound request + +`FastlyOutboundClient` is built fresh for each inbound request, so it holds the resolved config binding for exactly one request. The first dispatch that uses an identity reads its two config entries. Later hops and calls in the same inbound request, for the same identity, reuse them. + +The key is different. `fastly::secret_store::Secret` is neither `Clone` nor `Sync`, and `provide_client_certificate` takes it by value, so a handle cannot be cached and reused. The adapter opens the key only when a backend must be registered. A request whose backend is already registered in the instance's registry opens no key. + +| Per identity | Count | +| --- | --- | +| Config Store reads | 2 per inbound request | +| Secret Store reads | 1 per backend registration; 0 when the backend is already registered | + +One inbound request registers more than one backend for an identity only when it reaches different origins or uses different timeout settings with that identity. Whether Fastly counts opening a `Secret` handle as a read is not documented; this design assumes it does. The guide states the budget against Fastly's default of 5 reads per request, which the application's own reads share and Fastly can raise. + +### Rotation + +To rotate, the operator overwrites `.certificate` in the Config Store and `.private-key` in the Secret Store. Those are two writes to two stores, so they are not atomic. A request that reads one new entry and one old entry presents a mismatched pair, and the handshake fails with the existing TLS causes. Each new inbound request reads both again, so that window closes once both writes have reached the POP. The guide documents this, and the order that keeps the window short: write the new key and certificate in quick succession, then confirm with a request. + +### Backend registration + +- `BackendIdentity` gains `client_identity: Option<(String, [u8; 32])>`, holding the name and the chain fingerprint. +- `backend_name` hashes them when present. The backend name prefix moves from `ez_b31v1_` to `ez_b31v2_`, as the comment there requires for any change to the hashed key. Existing golden names are regenerated in the same commit, and each golden test states why its value changed. +- So these never share a backend: a request with an identity and one without, two identities, and one identity before and after a change to any certificate in its chain. That holds for #275's per-instance registry under `serve_app`, and for Fastly's connection pool, which matches on name and settings. +- `ensure_backend` calls `provide_client_certificate(certificate_pem, key_secret)` after the existing `enable_ssl`, `check_certificate` and `sni_hostname` calls. It changes no other builder setting. Connection pooling keeps its default (on). +- Fastly returns `BackendCreationError::Disallowed` when the service can't create dynamic backends, and that keeps its existing mapping. + +### Logging + +The adapter logs, at debug level, the identity name and the leaf fingerprint when it registers a new identity backend. It never logs key bytes, certificate PEM, or the hosts entry's contents. + +## Other adapters + +Cloudflare, Spin and Axum return `ClientIdentityError::Unsupported` from `validate_supported_options` and report `Unsupported` for the capability. The core contract leaves room for their bindings, and each follow-up issue records its adapter's answers to [What application code can rely on](#what-application-code-can-rely-on): + +| Adapter | Expected binding | Known limits | +| --- | --- | --- | +| Cloudflare | A `[[mtls_certificates]]` binding per identity, which the adapter selects as the `Fetcher`. Hosts come from deploy-time operator config. The Wrangler config is operator config, so R-CONFIG still holds | `wrangler dev` needs `--remote` to use the binding. Requests to proxied Cloudflare zones fail with 520 | +| Spin | `[[client_tls]]` entries generated from the identity's hosts and the operator's certificate and key file paths, scoped to the app's component. The guest checks hosts the same way before dispatch | Spin attaches the certificate by component and host, so a request without an identity to a configured host still presents it, and two identities can't share a host | +| Axum | Certificate and key read from configured paths or env, with one `reqwest::Client` per identity, built lazily and reused | None known | + +## CLI and configuration + +- Manifest validation enforces the naming rules and checks that any named `secret-store` or `config-store` is declared. +- A new `Adapter::validate_client_identities(&Manifest)` hook, defaulting to no checks, runs in the same CLI step that enforces required capabilities. Fastly's version rejects an identity whose secret store or config store can't be resolved, from its explicit field or the declared default. +- The existing required-capability check covers `outbound-client-identity`. +- The CLI does not read, generate or push config or secret values. Viceroy setup is documented, not generated. + +## Documentation + +| Page | Content | +| --- | --- | +| `docs/guide/proxying.md` | A "Client certificates (mTLS)" section: declaring an identity, `.client_identity()`, what application code can rely on, the host rules, redirects, the response-cache bypass, the error table, and the per-adapter support status | +| `docs/guide/adapters/fastly.md` | The three entries and their stores, PEM format, the key-handle rule, the Secret Store read budget, rotation and its non-atomic window, the backend name change, and commented `[local_server.config_stores]` and `[local_server.secret_stores]` examples for Viceroy | +| `docs/guide/capabilities.md` | `outbound-client-identity` in the capability matrix | +| `docs/guide/configuration.md` | `[capabilities.outbound.client-identities.]` and its fields | + +`app-demo` gets no route, because demonstrating one would need a mutual-TLS origin. + +## Testing + +Merging requires local evidence only. Certificates are generated per run with `rcgen`, so the repository holds no keys or expiring certificates. + +| Area | Evidence | +| --- | --- | +| Manifest and policy | Name rules, unknown stores, unknown fields, default stores, a manifest with no stores, and the policy `App` builds from `Hooks::manifest()`, including absent and malformed manifests. Dispatch attaches the policy to an adapter-built client and to a client supplied by a preparation hook, and leaves a client that already carries a policy unchanged | +| CLI | Fastly's identity check rejects unresolvable stores. The required-capability check fails for Cloudflare, Spin and Axum and passes for Fastly | +| Core | `ClientIdentityName` validation. `Undeclared` and `RequiresHttps` before I/O. Hosts parsing, covering ports, case, non-ASCII names, blank lines, paths, wildcards, an empty entry, and an origin outside the allowlist. A host-override request is still allowed. `replay_request` carries the identity. A same-origin hop and a hop to another listed host are sent, and a hop to an unlisted host fails with its index before dispatch. Batch slot isolation. Each error's status and redacted `Display` and `Debug` output | +| Unsupported adapters | Cloudflare, Spin and Axum reject an identity request before I/O | +| Fastly native | `backend_name` differs for no identity, two identities, and two chain fingerprints of one identity. Changing only an intermediate changes the fingerprint. A changed chain registers a new backend in a warm registry. Updated golden names. Missing entries, a malformed certificate and oversized entries map to their reasons. Identity requests are sent with the cache bypassed, and the surrogate-key policy is rejected. The binding cache reads each config entry once per inbound request, caches missing and invalid material, and retries after a deadline | +| Fastly runtime (patched Viceroy from `patches/viceroy`) | A new `edgezero-test-harness` runner starts host-side rustls origins that require client certificates from a per-run CA. The origins record every TCP accept before TLS, and separately record the certificate presented in each completed handshake. The runner writes the Viceroy config and secret store entries and runs the cases: the identity request succeeds with the expected certificate; requests without the identity, and with a certificate from a different CA, fail in the guest as a transport error, and the origin's records show a TCP accept with a failed handshake and no accepted client certificate. The runner records whatever cause Viceroy reports without asserting it; a relaunch with a replaced certificate presents the new one; `Undeclared`, `RequiresHttps`, Image Optimizer and a redirect to an unlisted host fail with no TCP accept at the origin they would have reached | +| Integration | The workspace gates in `CLAUDE.md`, `scripts/test_integration.sh --adapter fastly --suite ci` including the new runner, and the docs ESLint and Prettier checks | + +Viceroy loads its config and secret stores at startup, so the runtime test proves a replaced certificate is read after a restart. The warm-registry behavior is proved natively. + +Local evidence closes #523. A hosted Fastly check is not part of this change. Trusted Server's staging run for #1650 exercises the identity against a real origin, and is where the Secret Store read budget gets checked against Trusted Server's own reads. + +## Issue coverage + +| #523 condition | Met by | +| --- | --- | +| Reviewed design spec | This document | +| `OutboundRequest` carries a validated name and never key material | [Request contract](#request-contract) | +| An origin outside the identity's hosts, including after a redirect, fails before I/O | [Dispatch rules](#dispatch-rules) | +| Fastly presents the certificate with the key as a Secret Store handle | [Fastly binding](#fastly-binding) | +| Backend name includes the identity and certificate fingerprint | [Backend registration](#backend-registration) | +| Undeclared, missing and unsupported cases fail before I/O with documented errors | [Errors](#errors) | +| Viceroy test with handshake success and failure | [Testing](#testing) | +| Docs for declaring, provisioning and rotating | [Documentation](#documentation) | +| Follow-up issues for Cloudflare, Spin and Axum | Opened with the PR | + +The PR description says `Closes #523`. + +## Branch and delivery boundary + +The branch `feat/523-outbound-client-identity` stacks on [#464](https://github.com/IABTechLab/edgezero/pull/464), `review/admitted-error-finalization`, above #517. It uses the outbound contracts from #275 and the cache policy from #460. It does not depend on #522's portable record providers. No RC branch is a base or merge target. + +There is one PR, with commits in this order: this spec, the implementation plan in `docs/superpowers/plans/`, then the core and Fastly changes. When the PR opens: + +- Create the Cloudflare, Spin and Axum follow-up issues, each with its adapter's known limits. +- Add #523 to #79's child list. +- Comment on #81 that origin CA pinning is not a dependency of #523. diff --git a/examples/app-demo/Cargo.lock b/examples/app-demo/Cargo.lock index 8be202d7e..663202fda 100644 --- a/examples/app-demo/Cargo.lock +++ b/examples/app-demo/Cargo.lock @@ -930,6 +930,7 @@ dependencies = [ "async-stream", "async-trait", "base16ct", + "base64 0.22.1", "brotli", "brotli-decompressor", "bytes", diff --git a/examples/geo-kv-prototype/Cargo.lock b/examples/geo-kv-prototype/Cargo.lock index fefd2cd54..052fb17a7 100644 --- a/examples/geo-kv-prototype/Cargo.lock +++ b/examples/geo-kv-prototype/Cargo.lock @@ -877,6 +877,7 @@ dependencies = [ "async-stream", "async-trait", "base16ct", + "base64 0.22.1", "brotli", "brotli-decompressor", "bytes", diff --git a/examples/geo-spin-loader/Cargo.lock b/examples/geo-spin-loader/Cargo.lock index f8ef1830c..cc0197a6a 100644 --- a/examples/geo-spin-loader/Cargo.lock +++ b/examples/geo-spin-loader/Cargo.lock @@ -89,6 +89,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bitflags" version = "2.13.2" @@ -303,6 +309,7 @@ dependencies = [ "async-stream", "async-trait", "base16ct", + "base64", "brotli", "brotli-decompressor", "bytes", diff --git a/scripts/check_outbound_docs_contract.mjs b/scripts/check_outbound_docs_contract.mjs index a5dbd13c8..8be390138 100644 --- a/scripts/check_outbound_docs_contract.mjs +++ b/scripts/check_outbound_docs_contract.mjs @@ -148,6 +148,13 @@ const expectedOutboundRows = [ ], ['outbound-batch-slot-isolation', 'Native', 'Native', 'BestEffort', 'Native'], ['outbound-cache-bypass', 'Native', 'Native', 'Native', 'Native'], + [ + 'outbound-client-identity', + 'Unsupported', + 'Unsupported', + 'Native', + 'Unsupported', + ], [ 'outbound-complete-resource-accounting', 'Unsupported',