diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 463813f60..adf721283 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -108,6 +108,12 @@ jobs: --manifest-path tests/fixtures/reusable-app/Cargo.toml -p fixture-axum + # Workspace tests enable test-utils through adapter dev-dependencies. + # Keep the compiled-implementation refusal control in a separate invocation. + - name: Test app-config refusal without compiled implementation + if: matrix.suite == 'workspace' + run: cargo test -p edgezero-core --lib runtime_approved_diagnostic_tracks_compiled_availability + - name: Run workspace tests if: matrix.suite == 'workspace' run: cargo test --workspace --all-targets diff --git a/crates/edgezero-adapter-axum/src/response.rs b/crates/edgezero-adapter-axum/src/response.rs index cf3bb6c69..f79e45454 100644 --- a/crates/edgezero-adapter-axum/src/response.rs +++ b/crates/edgezero-adapter-axum/src/response.rs @@ -61,6 +61,25 @@ mod tests { use edgezero_core::http::{StatusCode, response_builder}; use futures::stream; + #[test] + fn approved_config_diagnostics_stay_private_after_conversion() { + use axum::body::to_bytes; + use edgezero_core::config_diagnostics::contract_fixture::{self, CANARY, EXPLANATION}; + use edgezero_core::response::IntoResponse as _; + let error = block_on(contract_fixture::extraction_error()).expect("extraction failure"); + assert_eq!(error.validation_diagnostics().len(), 1); + assert!(error.operator_message().contains(EXPLANATION)); + let response = into_axum_response(error.into_response().expect("core response")); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(response.headers()["retry-after"], "60"); + let bytes = block_on(to_bytes(response.into_body(), 4096)).expect("body"); + let body = String::from_utf8_lossy(&bytes); + assert!(body.contains("config_out_of_date")); + for hidden in [CANARY, EXPLANATION, "implementation_unavailable"] { + assert!(!body.contains(hidden)); + } + } + #[test] fn converts_core_response_stream_into_axum_body() { let stream = stream::iter(vec![ diff --git a/crates/edgezero-adapter-cloudflare/tests/contract.rs b/crates/edgezero-adapter-cloudflare/tests/contract.rs index 4e9e6409e..edac2ab5f 100644 --- a/crates/edgezero-adapter-cloudflare/tests/contract.rs +++ b/crates/edgezero-adapter-cloudflare/tests/contract.rs @@ -76,6 +76,29 @@ mod tests { } } + #[wasm_bindgen_test] + async fn approved_config_diagnostics_stay_private_after_conversion() { + use edgezero_core::config_diagnostics::contract_fixture::{self, CANARY, EXPLANATION}; + use edgezero_core::response::IntoResponse as _; + let error = contract_fixture::extraction_error() + .await + .expect("extraction failure"); + assert_eq!(error.validation_diagnostics().len(), 1); + assert!(error.operator_message().contains(EXPLANATION)); + let mut response = from_core_response(error.into_response().expect("core response")) + .expect("worker response"); + assert_eq!(response.status_code(), 503); + assert_eq!( + response.headers().get("retry-after").expect("header"), + Some("60".to_owned()) + ); + let body = response.text().await.expect("body"); + assert!(body.contains("config_out_of_date")); + for hidden in [CANARY, EXPLANATION, "implementation_unavailable"] { + assert!(!body.contains(hidden)); + } + } + #[wasm_bindgen_test] async fn ingress_invalid_runtime_header_value_is_a_bad_request() { let raw = web_sys::Request::new_with_str("https://example.com/reserved") diff --git a/crates/edgezero-adapter-fastly/tests/contract.rs b/crates/edgezero-adapter-fastly/tests/contract.rs index 09c5dbef1..6d837f8a8 100644 --- a/crates/edgezero-adapter-fastly/tests/contract.rs +++ b/crates/edgezero-adapter-fastly/tests/contract.rs @@ -120,6 +120,25 @@ mod tests { req } + #[test] + fn approved_config_diagnostics_stay_private_after_conversion() { + use edgezero_core::config_diagnostics::contract_fixture::{self, CANARY, EXPLANATION}; + use edgezero_core::response::IntoResponse as _; + let error = block_on(contract_fixture::extraction_error()).expect("extraction failure"); + assert_eq!(error.validation_diagnostics().len(), 1); + assert!(error.operator_message().contains(EXPLANATION)); + let mut response = from_core_response(error.into_response().expect("core response")) + .expect("fastly response"); + assert_eq!(response.get_status().as_u16(), 503); + assert_eq!(response.get_header_str("retry-after"), Some("60")); + let bytes = response.take_body_bytes(); + let body = String::from_utf8_lossy(&bytes); + assert!(body.contains("config_out_of_date")); + for hidden in [CANARY, EXPLANATION, "implementation_unavailable"] { + assert!(!body.contains(hidden)); + } + } + #[test] fn into_core_request_preserves_method_uri_headers_body_and_context() { let req = fastly_request(FastlyMethod::POST, "/mirror?foo=bar", Some(b"payload")); diff --git a/crates/edgezero-adapter-spin/tests/contract.rs b/crates/edgezero-adapter-spin/tests/contract.rs index a8c238fc4..cfa19089e 100644 --- a/crates/edgezero-adapter-spin/tests/contract.rs +++ b/crates/edgezero-adapter-spin/tests/contract.rs @@ -38,6 +38,35 @@ mod tests { use edgezero_adapter_spin::response::from_core_response; use http_body_util::BodyExt as _; + #[test] + fn approved_config_diagnostics_stay_private_after_conversion() { + use edgezero_core::config_diagnostics::contract_fixture::{self, CANARY, EXPLANATION}; + use edgezero_core::response::IntoResponse as _; + block_on(async { + let error = contract_fixture::extraction_error() + .await + .expect("extraction failure"); + assert_eq!(error.validation_diagnostics().len(), 1); + assert!(error.operator_message().contains(EXPLANATION)); + let response = from_core_response(error.into_response().expect("core response")) + .await + .expect("spin response"); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(response.headers()["retry-after"], "60"); + let bytes = response + .into_body() + .collect() + .await + .expect("body") + .to_bytes(); + let body = String::from_utf8_lossy(&bytes); + assert!(body.contains("config_out_of_date")); + for hidden in [CANARY, EXPLANATION, "implementation_unavailable"] { + assert!(!body.contains(hidden)); + } + }); + } + #[test] fn from_core_response_translates_status_and_headers() { block_on(async { diff --git a/crates/edgezero-cli/src/config.rs b/crates/edgezero-cli/src/config.rs index 438db18bb..b8b87d267 100644 --- a/crates/edgezero-cli/src/config.rs +++ b/crates/edgezero-cli/src/config.rs @@ -32,6 +32,7 @@ use edgezero_core::app_config::{ SecretPathSegment, }; use edgezero_core::blob_envelope::{BlobEnvelope, BlobEnvelopeError, ENVELOPE_VERSION_V1}; +use edgezero_core::config_diagnostics::ValidationReport; use edgezero_core::env_config::{EnvConfig, merge_env_defaults}; use edgezero_core::manifest::{Manifest, ManifestAdapter, ManifestLoader, StoreDeclaration}; use serde::Serialize; @@ -261,8 +262,12 @@ where &opts, ) .map_err(|err| format_app_config_error(&err))?; - app_config::validate_excluding_secrets(&typed) - .map_err(|err| format!("typed app-config failed validation: {err}"))?; + app_config::validate_excluding_secrets(&typed).map_err(|err| { + format!( + "typed app-config failed validation: {}", + ValidationReport::from_errors(&err, C::validation_diagnostics()).operator_message() + ) + })?; typed_secret_checks(&typed, &ctx)?; run_adapter_typed_checks::(&ctx, AdapterValidationScope::All)?; @@ -465,8 +470,12 @@ where &opts, ) .map_err(|err| format_app_config_error(&err))?; - app_config::validate_excluding_secrets(&typed) - .map_err(|err| format!("typed app-config failed validation: {err}"))?; + app_config::validate_excluding_secrets(&typed).map_err(|err| { + format!( + "typed app-config failed validation: {}", + ValidationReport::from_errors(&err, C::validation_diagnostics()).operator_message() + ) + })?; typed_secret_checks(&typed, &ctx.validation)?; run_adapter_typed_checks::(&ctx.validation, validation_scope)?; @@ -638,8 +647,12 @@ where &opts, ) .map_err(|err| format_app_config_error(&err))?; - app_config::validate_excluding_secrets(&typed) - .map_err(|err| format!("local validation failed: {err}"))?; + app_config::validate_excluding_secrets(&typed).map_err(|err| { + format!( + "local validation failed: {}", + ValidationReport::from_errors(&err, C::validation_diagnostics()).operator_message() + ) + })?; typed_secret_checks(&typed, &ctx)?; run_adapter_typed_checks::(&ctx, validation_scope)?; @@ -2087,6 +2100,10 @@ fn format_app_config_error(err: &AppConfigError) -> String { clippy::default_numeric_fallback, reason = "test module groups items by subject (PathPrepend co-located with its fake-spin consumers, fixtures with their tests) rather than by item kind; `range(min = 100, max = 60_000)` bounds default to the field's int type" )] +#[expect( + clippy::missing_trait_methods, + reason = "fixtures exercise the default-empty diagnostic metadata contract" +)] mod tests { use super::*; use crate::test_support::{EnvOverride, manifest_guard}; @@ -2975,8 +2992,105 @@ timeout_ms = 1500 ); } + #[test] + fn typed_commands_share_approved_diagnostics_and_redact_validator_values() { + use edgezero_core::config_diagnostics::{ApprovedDiagnostic, ValidationPathSegment}; + use std::borrow::Cow; + const RULES: &[ApprovedDiagnostic] = &[ApprovedDiagnostic { + path: &[ValidationPathSegment::Field("implementation")], + code: "implementation_unavailable", + explanation: "Enable feature bidder-x and rebuild both CLI and serving guest.", + }]; + #[derive(Deserialize, Serialize, edgezero_core::AppConfig)] + #[app_config(diagnostics = RULES)] + struct RefusedConfig { + implementation: String, + } + impl Validate for RefusedConfig { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + let code = if self.implementation == "unapproved" { + "unknown" + } else { + "implementation_unavailable" + }; + let mut error = validator::ValidationError::new(code); + error.message = Some(Cow::Borrowed("UNTRUSTED_CUSTOM_MESSAGE_CANARY")); + error.add_param(Cow::Borrowed("value"), &"REJECTED_URL_SECRET_CANARY"); + let mut errors = validator::ValidationErrors::new(); + errors.add("implementation", error); + Err(errors) + } + } + for selection in ["bidder-x", "unapproved"] { + let (dir, manifest, _) = + setup_project(PUSH_MANIFEST, &format!("implementation = {selection:?}\n")); + let diff = ConfigDiffArgs { + adapter: "axum".to_owned(), + app_config: None, + exit_code: false, + format: DiffFormat::Unified, + key: None, + local: false, + manifest: manifest.clone(), + no_env: true, + runtime_config: None, + store: None, + staging: false, + }; + let errors = [ + run_config_validate_typed::(&args_for(&manifest)) + .expect_err("refused validate"), + run_config_push_typed::(&push_args(&manifest, "axum")) + .expect_err("refused push"), + run_config_diff_typed::(&diff).expect_err("refused diff"), + ]; + for error in errors { + assert!(error.contains("validation")); + assert_eq!( + error.contains(RULES[0].explanation), + selection == "bidder-x" + ); + for canary in [ + "UNTRUSTED_CUSTOM_MESSAGE_CANARY", + "REJECTED_URL_SECRET_CANARY", + ] { + assert!(!error.contains(canary), "unsafe validator output: {error}"); + } + } + assert!( + !dir.path().join(".edgezero").exists(), + "validation must precede remote work" + ); + } + } + #[test] fn typed_errors_on_validator_rule_failure() { + use edgezero_core::config_diagnostics::{ApprovedDiagnostic, ValidationPathSegment}; + const RULES: &[ApprovedDiagnostic] = &[ApprovedDiagnostic { + path: &[ + ValidationPathSegment::Field("service"), + ValidationPathSegment::Field("timeout_ms"), + ], + code: "range", + explanation: "Set timeout_ms between 100 and 60000.", + }]; + #[derive(Deserialize)] + #[serde(transparent)] + struct RegisteredConfig(FixtureConfig); + impl Validate for RegisteredConfig { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + self.0.validate() + } + } + impl AppConfigMeta for RegisteredConfig { + fn secret_fields() -> Vec { + FixtureConfig::secret_fields() + } + fn validation_diagnostics() -> &'static [ApprovedDiagnostic] { + RULES + } + } let app_config = r#" api_token = "x" greeting = "hi" @@ -2989,9 +3103,21 @@ timeout_ms = 50 let err = run_config_validate_typed::(&args_for(&manifest)) .expect_err("validator rule must error"); assert!( - err.to_lowercase().contains("validation"), - "error mentions validation: {err}" + err.contains("app config failed validation for field `.`"), + "{err}" + ); + assert!( + !err.contains("service.timeout_ms"), + "unregistered path: {err}" + ); + + let approved = run_config_validate_typed::(&args_for(&manifest)) + .expect_err("registered rule still rejects invalid config"); + assert!( + approved.contains("service.timeout_ms [range]: Set timeout_ms between 100 and 60000."), + "{approved}" ); + assert!(!approved.contains(""), "{approved}"); } #[test] diff --git a/crates/edgezero-core/src/app_config.rs b/crates/edgezero-core/src/app_config.rs index 74a17cdd1..ead5f33e9 100644 --- a/crates/edgezero-core/src/app_config.rs +++ b/crates/edgezero-core/src/app_config.rs @@ -23,6 +23,7 @@ use std::io; use std::path::{Path, PathBuf}; use std::thread_local; +use crate::config_diagnostics::ApprovedDiagnostic; use serde::de::DeserializeOwned; use thiserror::Error; use toml::Value; @@ -91,6 +92,15 @@ pub trait AppConfigMeta { /// including those reached through `#[app_config(nested)]` children, /// each carrying its full path from this struct's root. fn secret_fields() -> Vec; + + /// Root-owned approval registry for operator-facing validation diagnostics. + /// Derived configs opt in with `#[app_config(diagnostics = REGISTRY)]`. + /// The default retains generic, redacted reporting. + #[inline] + #[must_use] + fn validation_diagnostics() -> &'static [ApprovedDiagnostic] { + &[] + } } thread_local! { @@ -753,6 +763,10 @@ fn walk_and_overlay( match arms in `expect_err` assertions intentionally collapse all unexpected \ variants into a single panic" )] +#[expect( + clippy::missing_trait_methods, + reason = "fixtures exercise the default-empty diagnostic metadata contract" +)] mod tests { use super::*; use crate::test_env::{EnvOverride, env_lock}; diff --git a/crates/edgezero-core/src/config_diagnostics.rs b/crates/edgezero-core/src/config_diagnostics.rs new file mode 100644 index 000000000..4c9f70a42 --- /dev/null +++ b/crates/edgezero-core/src/config_diagnostics.rs @@ -0,0 +1,775 @@ +//! Bounded, explicitly approved typed app-config validation diagnostics. + +#![expect( + clippy::arbitrary_source_item_ordering, + reason = "approval declarations, safe reports, and bounded traversal are grouped in data-flow order" +)] + +use validator::{ValidationErrors, ValidationErrorsKind}; + +/// Maximum number of declarations accepted from a registry. +pub const MAX_REGISTRY_ENTRIES: usize = 64; +/// Maximum number of approved diagnostics retained per failure. +pub const MAX_DIAGNOSTICS: usize = 8; +/// Maximum approved code length in bytes. +pub const MAX_CODE_BYTES: usize = 64; +/// Maximum fixed explanation length in bytes. +pub const MAX_EXPLANATION_BYTES: usize = 512; +/// Maximum rendered structural path length in bytes. +pub const MAX_PATH_BYTES: usize = 256; +/// Maximum validation-tree path depth inspected. +pub const MAX_DEPTH: usize = 32; +/// Maximum validation containers, entries and field errors inspected. +pub const MAX_VISITED_NODES: usize = 1_024; + +/// A trusted structural path component. Wildcards match list indices only. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ValidationPathSegment { + /// A fixed field name from the application's schema, never a map key value. + Field(&'static str), + /// Any numeric list position. + Each, +} + +/// Explicit approval of a fixed diagnostic at an exact path and error code. +/// +/// All strings must come from compiled declarations, never configuration values. +/// Validator messages and parameters are ignored, even for approved codes. +#[derive(Clone, Copy, Debug)] +pub struct ApprovedDiagnostic { + /// Full structural path, with `Each` for list positions. + pub path: &'static [ValidationPathSegment], + /// Fixed validator error code. + pub code: &'static str, + /// Fixed, single-line operator explanation (including remediation). + pub explanation: &'static str, +} + +/// An approved diagnostic, containing no validator-owned strings or values. +#[derive(Clone, Debug)] +pub struct ValidationDiagnostic { + field_path: String, + code: &'static str, + explanation: &'static str, +} + +impl ValidationDiagnostic { + /// Approved structural path with numeric list positions. + #[must_use] + #[inline] + pub fn field_path(&self) -> &str { + &self.field_path + } + + /// Approved fixed error code. + #[must_use] + #[inline] + pub fn code(&self) -> &'static str { + self.code + } + + /// Approved fixed operator explanation. + #[must_use] + #[inline] + pub fn explanation(&self) -> &'static str { + self.explanation + } +} + +/// Bounded safe summary of a validation failure. It does not retain its source. +#[derive(Clone, Debug, Default)] +pub struct ValidationReport { + field_path: String, + diagnostics: Vec, +} + +impl ValidationReport { + /// Inspect an existing validation result without revalidating or reading data. + /// + /// Invalid/oversized registries and unknown errors retain generic reporting. + /// Exhausting any limit only stops diagnostic collection; callers must still + /// reject the configuration. Names in the fallback path are redacted. + #[must_use] + #[inline] + pub fn from_errors(errors: &ValidationErrors, registry: &[ApprovedDiagnostic]) -> Self { + let rules: Vec<&ApprovedDiagnostic> = if registry.len() <= MAX_REGISTRY_ENTRIES { + registry.iter().filter(|rule| valid_rule(rule)).collect() + } else { + Vec::new() + }; + let mut walker = Walker { + report: Self::default(), + rules, + remaining: MAX_VISITED_NODES, + }; + walker.walk(errors, &mut Vec::new()); + walker.report + } + + /// First failing public path, with all field names redacted and numeric indices retained. + #[must_use] + #[inline] + pub fn field_path(&self) -> &str { + &self.field_path + } + + /// Explicitly approved operator diagnostics, in deterministic path order. + #[must_use] + #[inline] + pub fn diagnostics(&self) -> &[ValidationDiagnostic] { + &self.diagnostics + } + + /// Coarse public explanation; approved diagnostic details are omitted. + #[must_use] + #[inline] + pub fn public_message(&self) -> String { + if self.field_path.is_empty() { + "app config failed validation".to_owned() + } else { + format!( + "app config failed validation for field `{}`", + self.field_path + ) + } + } + + /// Safe operator text suitable for CLI errors and application logs. + #[must_use] + #[inline] + pub fn operator_message(&self) -> String { + let mut output = if self.diagnostics.is_empty() { + self.public_message() + } else { + "app config failed validation".to_owned() + }; + for diagnostic in &self.diagnostics { + output.push_str("; "); + output.push_str(&diagnostic.field_path); + output.push_str(" ["); + output.push_str(diagnostic.code); + output.push_str("]: "); + output.push_str(diagnostic.explanation); + } + output + } +} + +fn valid_rule(rule: &ApprovedDiagnostic) -> bool { + !rule.code.is_empty() + && rule.code.len() <= MAX_CODE_BYTES + && rule + .code + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + && !rule.explanation.is_empty() + && rule.explanation.len() <= MAX_EXPLANATION_BYTES + && !rule.explanation.chars().any(char::is_control) + && rule.path.len() <= MAX_DEPTH + && rule.path.iter().all(|segment| match segment { + ValidationPathSegment::Field(name) => { + !name.is_empty() + && name.len() <= MAX_PATH_BYTES + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + } + ValidationPathSegment::Each => true, + }) +} + +#[derive(Clone, Copy)] +enum ActualSegment<'tree> { + Field(&'tree str), + Index(usize), +} + +struct Walker<'tree> { + report: ValidationReport, + rules: Vec<&'tree ApprovedDiagnostic>, + remaining: usize, +} + +impl Walker<'_> { + fn spend(&mut self, count: usize) -> bool { + if count > self.remaining { + self.remaining = 0; + false + } else { + self.remaining = self.remaining.saturating_sub(count); + true + } + } + + fn walk<'tree>( + &mut self, + errors: &'tree ValidationErrors, + path: &mut Vec>, + ) { + if path.len() >= MAX_DEPTH + || self.report.diagnostics.len() >= MAX_DIAGNOSTICS + || !self.spend(1) + || !self.spend(errors.errors().len()) + { + return; + } + // Bound the collection BEFORE allocating/sorting attacker-sized maps. + let mut keys: Vec<&str> = errors + .errors() + .keys() + .map(AsRef::as_ref) + .filter(|key: &&str| key.len() <= MAX_PATH_BYTES) + .collect(); + keys.sort_unstable(); + for key in keys { + if self.remaining == 0 || self.report.diagnostics.len() >= MAX_DIAGNOSTICS { + break; + } + path.push(ActualSegment::Field(key)); + match errors.errors().get(key) { + Some(ValidationErrorsKind::Field(items)) => { + if self.report.field_path.is_empty() { + self.report.field_path = render_path(path, None).unwrap_or_default(); + } + for error in items { + if !self.spend(1) || self.report.diagnostics.len() >= MAX_DIAGNOSTICS { + break; + } + for rule in &self.rules { + if error.code.as_ref() == rule.code + && path_matches(path, rule.path) + && let Some(field_path) = render_path(path, Some(rule.path)) + { + if !self.report.diagnostics.iter().any(|diagnostic| { + diagnostic.field_path == field_path + && diagnostic.code == rule.code + }) { + self.report.diagnostics.push(ValidationDiagnostic { + field_path, + code: rule.code, + explanation: rule.explanation, + }); + } + break; + } + } + } + } + Some(ValidationErrorsKind::Struct(inner)) => self.walk(inner, path), + Some(ValidationErrorsKind::List(items)) + if path.len() < MAX_DEPTH && self.spend(items.len()) => + { + // validator's list is a BTreeMap, already in index order. + for (index, inner) in items { + if self.remaining == 0 || self.report.diagnostics.len() >= MAX_DIAGNOSTICS { + break; + } + path.push(ActualSegment::Index(*index)); + self.walk(inner, path); + path.pop(); + } + } + Some(ValidationErrorsKind::List(_)) | None => {} + } + path.pop(); + } + } +} + +fn path_matches(actual: &[ActualSegment<'_>], approved: &[ValidationPathSegment]) -> bool { + actual.len() == approved.len() + && actual + .iter() + .zip(approved) + .all( + |(actual_part, approved_part)| match (actual_part, approved_part) { + (ActualSegment::Field(found), ValidationPathSegment::Field(expected)) => { + found == expected + } + (ActualSegment::Index(_), ValidationPathSegment::Each) => true, + _ => false, + }, + ) +} + +fn render_path( + actual: &[ActualSegment<'_>], + approved: Option<&[ValidationPathSegment]>, +) -> Option { + let mut result = String::new(); + for (position, segment) in actual.iter().enumerate() { + match segment { + ActualSegment::Field(_) => { + let name = match approved.and_then(|parts| parts.get(position)) { + Some(ValidationPathSegment::Field(name)) => name, + Some(ValidationPathSegment::Each) | None => "", + }; + if !result.is_empty() { + result.push('.'); + } + if result.len().saturating_add(name.len()) > MAX_PATH_BYTES { + return None; + } + result.push_str(name); + } + ActualSegment::Index(index) => { + result.push('['); + result.push_str(&index.to_string()); + result.push(']'); + } + } + if result.len() > MAX_PATH_BYTES { + return None; + } + } + Some(result) +} + +/// Shared extraction fixture for adapter contracts; not part of the application API. +#[cfg(feature = "test-utils")] +#[doc(hidden)] +pub mod contract_fixture { + use std::sync::Arc; + + use async_trait::async_trait; + use serde::Deserialize; + use validator::{Validate, ValidationError, ValidationErrors}; + + use super::{ApprovedDiagnostic, ValidationPathSegment}; + use crate::app_config::{AppConfigMeta, SecretField}; + use crate::blob_envelope::BlobEnvelope; + use crate::body::Body; + use crate::config_store::{ConfigStore, ConfigStoreError, ConfigStoreHandle}; + use crate::context::RequestContext; + use crate::error::EdgeError; + use crate::extractor::AppConfig; + use crate::http::request_builder; + use crate::params::PathParams; + use crate::store_registry::{ConfigStoreBinding, StoreRegistry}; + + /// Approved explanation must stay out of public responses. + pub const EXPLANATION: &str = "Enable feature bidder-x and rebuild CLI and guest."; + /// Validator value/message must stay out of all reports. + pub const CANARY: &str = "UNTRUSTED_CONFIG_VALUE_CANARY"; + + #[derive(Deserialize)] + struct RefusedConfig { + _unused: Option, + } + + impl AppConfigMeta for RefusedConfig { + fn secret_fields() -> Vec { + Vec::new() + } + fn validation_diagnostics() -> &'static [ApprovedDiagnostic] { + &[ApprovedDiagnostic { + path: &[ValidationPathSegment::Field("implementation")], + code: "implementation_unavailable", + explanation: EXPLANATION, + }] + } + } + + impl Validate for RefusedConfig { + fn validate(&self) -> Result<(), ValidationErrors> { + let mut error = ValidationError::new("implementation_unavailable"); + error.message = Some(CANARY.into()); + error.add_param("value".into(), &CANARY); + let mut errors = ValidationErrors::new(); + errors.add("implementation", error); + Err(errors) + } + } + + struct FixtureStore; + #[async_trait(?Send)] + impl ConfigStore for FixtureStore { + async fn get(&self, _key: &str) -> Result, ConfigStoreError> { + let envelope = BlobEnvelope::new(serde_json::json!({}), "2026-11-13T00:00:00Z".into()); + serde_json::to_string(&envelope) + .map(Some) + .map_err(ConfigStoreError::internal) + } + } + + /// Exercise the real store reader, typed validation and safe error mapping. + #[inline] + pub async fn extraction_error() -> Result { + let binding = ConfigStoreBinding { + handle: ConfigStoreHandle::new(Arc::new(FixtureStore)), + default_key: "config".to_owned(), + }; + let registry = StoreRegistry::single_id("default".to_owned(), binding); + let mut request = request_builder() + .uri("/") + .body(Body::empty()) + .map_err(EdgeError::internal)?; + request.extensions_mut().insert(registry); + let ctx = RequestContext::new(request, PathParams::default()); + match AppConfig::::from_store(&ctx, "default", None).await { + Err(error) => Ok(error), + Ok(_) => Err(EdgeError::internal(anyhow::anyhow!( + "contract fixture unexpectedly accepted" + ))), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::borrow::Cow; + use validator::{ValidationError, ValidationErrors, ValidationErrorsKind}; + + const RULES: &[ApprovedDiagnostic] = &[ApprovedDiagnostic { + path: &[ + ValidationPathSegment::Field("bidders"), + ValidationPathSegment::Each, + ValidationPathSegment::Field("implementation"), + ], + code: "implementation_unavailable", + explanation: "Enable Cargo feature bidder-x and rebuild both CLI and serving guest.", + }]; + + fn refusal(code: &'static str) -> ValidationErrors { + let mut error = ValidationError::new(code); + error.message = Some(Cow::Borrowed("UNTRUSTED_MESSAGE_CANARY")); + error.add_param(Cow::Borrowed("value"), &"SECRET_URL_VALUE_CANARY"); + let mut leaf = ValidationErrors::new(); + leaf.add("implementation", error); + let mut root = ValidationErrors::new(); + root.errors_mut().insert( + Cow::Borrowed("bidders"), + ValidationErrorsKind::List([(2, Box::new(leaf))].into_iter().collect()), + ); + root + } + + #[test] + fn approves_exact_path_and_code_without_retaining_values() { + let report = ValidationReport::from_errors(&refusal("implementation_unavailable"), RULES); + assert_eq!(report.diagnostics().len(), 1); + let diagnostic = &report.diagnostics()[0]; + assert_eq!(diagnostic.field_path(), "bidders[2].implementation"); + assert_eq!(diagnostic.code(), "implementation_unavailable"); + assert_eq!(diagnostic.explanation(), RULES[0].explanation); + let output = format!("{report:?} {}", report.operator_message()); + for canary in ["UNTRUSTED_MESSAGE_CANARY", "SECRET_URL_VALUE_CANARY"] { + assert!(!output.contains(canary)); + } + } + + #[test] + fn repeated_diagnostics_leave_room_for_distinct_codes_and_indices() { + let rules = [ + RULES[0], + ApprovedDiagnostic { + code: "other", + ..RULES[0] + }, + ]; + let mut leaf = ValidationErrors::new(); + for _ in 0..MAX_DIAGNOSTICS { + for code in ["implementation_unavailable", "other"] { + leaf.add("implementation", ValidationError::new(code)); + } + } + let mut errors = ValidationErrors::new(); + errors.errors_mut().insert( + Cow::Borrowed("bidders"), + ValidationErrorsKind::List( + [(0, Box::new(leaf.clone())), (1, Box::new(leaf))] + .into_iter() + .collect(), + ), + ); + let report = ValidationReport::from_errors(&errors, &rules); + let found: Vec<_> = report + .diagnostics() + .iter() + .map(|diagnostic| (diagnostic.field_path(), diagnostic.code())) + .collect(); + assert_eq!( + found, + [ + ("bidders[0].implementation", "implementation_unavailable"), + ("bidders[0].implementation", "other"), + ("bidders[1].implementation", "implementation_unavailable"), + ("bidders[1].implementation", "other"), + ] + ); + } + + #[test] + fn operator_message_uses_approved_locations_without_redacted_prefix() { + let report = ValidationReport::from_errors(&refusal("implementation_unavailable"), RULES); + assert_eq!( + report.operator_message(), + format!( + "app config failed validation; bidders[2].implementation [implementation_unavailable]: {}", + RULES[0].explanation, + ) + ); + let fallback = ValidationReport::from_errors(&refusal("unknown"), RULES); + assert_eq!(fallback.operator_message(), fallback.public_message()); + assert_eq!(fallback.field_path(), "[2]."); + } + + #[test] + fn unknown_codes_and_different_paths_are_generic() { + let unknown = ValidationReport::from_errors(&refusal("unknown"), RULES); + assert!(unknown.diagnostics().is_empty()); + let mut errors = ValidationErrors::new(); + errors.add( + "SECRET_MAP_KEY_CANARY", + ValidationError::new("implementation_unavailable"), + ); + let report = ValidationReport::from_errors(&errors, RULES); + assert!(report.diagnostics().is_empty()); + assert!(!format!("{report:?}").contains("SECRET_MAP_KEY_CANARY")); + } + + #[test] + fn bounds_codes_explanations_paths_depth_and_diagnostic_count() { + for length in [MAX_CODE_BYTES, MAX_CODE_BYTES + 1] { + let code = "x".repeat(length).leak(); + let rule = ApprovedDiagnostic { code, ..RULES[0] }; + assert_eq!( + ValidationReport::from_errors(&refusal(code), &[rule]) + .diagnostics() + .len(), + usize::from(length == MAX_CODE_BYTES) + ); + } + for length in [MAX_EXPLANATION_BYTES, MAX_EXPLANATION_BYTES + 1] { + let rule = ApprovedDiagnostic { + explanation: "x".repeat(length).leak(), + ..RULES[0] + }; + assert_eq!( + ValidationReport::from_errors(&refusal("implementation_unavailable"), &[rule]) + .diagnostics() + .len(), + usize::from(length == MAX_EXPLANATION_BYTES) + ); + } + let mut many = ValidationErrors::new(); + let items = (0..=MAX_DIAGNOSTICS) + .map(|index| { + let mut leaf = ValidationErrors::new(); + leaf.add( + "implementation", + ValidationError::new("implementation_unavailable"), + ); + (index, Box::new(leaf)) + }) + .collect(); + many.errors_mut() + .insert(Cow::Borrowed("bidders"), ValidationErrorsKind::List(items)); + assert_eq!( + ValidationReport::from_errors(&many, RULES) + .diagnostics() + .len(), + MAX_DIAGNOSTICS + ); + + let long_name = "x".repeat(MAX_PATH_BYTES).leak(); + let long_path = [ApprovedDiagnostic { + path: Box::leak( + vec![ + ValidationPathSegment::Field("bidders"), + ValidationPathSegment::Each, + ValidationPathSegment::Field(long_name), + ] + .into_boxed_slice(), + ), + ..RULES[0] + }]; + let mut long_leaf = ValidationErrors::new(); + long_leaf.add( + long_name, + ValidationError::new("implementation_unavailable"), + ); + let mut root = ValidationErrors::new(); + root.errors_mut().insert( + Cow::Borrowed("bidders"), + ValidationErrorsKind::List([(0, Box::new(long_leaf))].into_iter().collect()), + ); + assert!( + ValidationReport::from_errors(&root, &long_path) + .diagnostics() + .is_empty() + ); + + let mut deep = refusal("implementation_unavailable"); + for _ in 0..=MAX_DEPTH { + let mut parent = ValidationErrors::new(); + parent.errors_mut().insert( + Cow::Borrowed("NESTED_CANARY"), + ValidationErrorsKind::Struct(Box::new(deep)), + ); + deep = parent; + } + let report = ValidationReport::from_errors(&deep, RULES); + assert!(report.diagnostics().is_empty()); + assert!(!format!("{report:?}").contains("NESTED_CANARY")); + } + + #[test] + fn list_wildcard_does_not_approve_string_keys_or_prefixes() { + let mut leaf = ValidationErrors::new(); + leaf.add( + "implementation", + ValidationError::new("implementation_unavailable"), + ); + let mut map = ValidationErrors::new(); + map.errors_mut().insert( + Cow::Borrowed("0"), + ValidationErrorsKind::Struct(Box::new(leaf)), + ); + let mut root = ValidationErrors::new(); + root.errors_mut().insert( + Cow::Borrowed("bidders"), + ValidationErrorsKind::Struct(Box::new(map)), + ); + assert!( + ValidationReport::from_errors(&root, RULES) + .diagnostics() + .is_empty() + ); + let prefix = [ApprovedDiagnostic { + path: &[ValidationPathSegment::Field("bidders")], + ..RULES[0] + }]; + assert!( + ValidationReport::from_errors(&refusal("implementation_unavailable"), &prefix) + .diagnostics() + .is_empty() + ); + } + + #[test] + fn accepts_exact_registry_path_and_depth_limits() { + let registry = vec![RULES[0]; MAX_REGISTRY_ENTRIES]; + assert_eq!( + ValidationReport::from_errors(&refusal("implementation_unavailable"), ®istry) + .diagnostics() + .len(), + 1 + ); + for length in [MAX_PATH_BYTES, MAX_PATH_BYTES + 1] { + let name = "x".repeat(length).leak(); + let path = Box::leak(vec![ValidationPathSegment::Field(name)].into_boxed_slice()); + let rule = ApprovedDiagnostic { path, ..RULES[0] }; + let mut errors = ValidationErrors::new(); + errors.add(name, ValidationError::new(rule.code)); + assert_eq!( + ValidationReport::from_errors(&errors, &[rule]) + .diagnostics() + .len(), + usize::from(length == MAX_PATH_BYTES) + ); + } + for depth in [MAX_DEPTH, MAX_DEPTH + 1] { + let path = Box::leak(vec![ValidationPathSegment::Field("n"); depth].into_boxed_slice()); + let rule = ApprovedDiagnostic { path, ..RULES[0] }; + let mut errors = ValidationErrors::new(); + errors.add("n", ValidationError::new(rule.code)); + for _ in 1..depth { + let mut parent = ValidationErrors::new(); + parent.errors_mut().insert( + Cow::Borrowed("n"), + ValidationErrorsKind::Struct(Box::new(errors)), + ); + errors = parent; + } + assert_eq!( + ValidationReport::from_errors(&errors, &[rule]) + .diagnostics() + .len(), + usize::from(depth == MAX_DEPTH) + ); + } + } + + #[test] + fn field_and_list_budgets_bound_collection() { + let mut leaf = ValidationErrors::new(); + for _ in 0..=MAX_VISITED_NODES { + leaf.add( + "implementation", + ValidationError::new("implementation_unavailable"), + ); + } + let mut errors = ValidationErrors::new(); + errors.errors_mut().insert( + Cow::Borrowed("bidders"), + ValidationErrorsKind::List([(0, Box::new(leaf))].into_iter().collect()), + ); + assert_eq!( + ValidationReport::from_errors(&errors, RULES) + .diagnostics() + .len(), + 1 + ); + // An approved error beyond the field budget must not be visited. + let mut exhausted_leaf = ValidationErrors::new(); + for _ in 0..MAX_VISITED_NODES { + exhausted_leaf.add("implementation", ValidationError::new("unknown")); + } + exhausted_leaf.add( + "implementation", + ValidationError::new("implementation_unavailable"), + ); + errors.errors_mut().insert( + Cow::Borrowed("bidders"), + ValidationErrorsKind::List([(0, Box::new(exhausted_leaf))].into_iter().collect()), + ); + assert!( + ValidationReport::from_errors(&errors, RULES) + .diagnostics() + .is_empty() + ); + let items = (0..=MAX_VISITED_NODES) + .map(|index| (index, Box::new(ValidationErrors::new()))) + .collect(); + errors + .errors_mut() + .insert(Cow::Borrowed("bidders"), ValidationErrorsKind::List(items)); + assert!( + ValidationReport::from_errors(&errors, RULES) + .diagnostics() + .is_empty() + ); + } + + #[test] + fn oversized_declarations_and_trees_stay_generic_and_bounded() { + let oversized = [ApprovedDiagnostic { + explanation: "bad\nexplanation", + ..RULES[0] + }]; + assert!( + ValidationReport::from_errors(&refusal("implementation_unavailable"), &oversized) + .diagnostics() + .is_empty() + ); + let many = vec![RULES[0]; MAX_REGISTRY_ENTRIES + 1]; + assert!( + ValidationReport::from_errors(&refusal("implementation_unavailable"), &many) + .diagnostics() + .is_empty() + ); + let mut errors = ValidationErrors::new(); + for index in 0..=MAX_VISITED_NODES { + errors.errors_mut().insert( + Cow::Owned(format!("CANARY{index}")), + ValidationErrorsKind::Field(vec![ValidationError::new("x")]), + ); + } + let report = ValidationReport::from_errors(&errors, RULES); + assert!(report.diagnostics().is_empty()); + assert!(report.field_path().len() <= MAX_PATH_BYTES); + assert!(!format!("{report:?}").contains("CANARY")); + } +} diff --git a/crates/edgezero-core/src/error.rs b/crates/edgezero-core/src/error.rs index 96dd9ff1c..cda2e0c62 100644 --- a/crates/edgezero-core/src/error.rs +++ b/crates/edgezero-core/src/error.rs @@ -5,6 +5,7 @@ use serde_path_to_error::Error as SerdePathError; use thiserror::Error; use crate::body::Body; +use crate::config_diagnostics::{ValidationDiagnostic, ValidationReport}; use crate::config_store::ConfigStoreError; use crate::http::{ HeaderValue, Method, Response, StatusCode, @@ -24,6 +25,11 @@ pub enum EdgeError { /// `"config_out_of_date"`, carries `Retry-After: 60`. #[error("config out of date: {message}")] ConfigOutOfDate { message: String, field_path: String }, + /// Typed app-config refusal with explicitly approved operator diagnostics. + /// Public rendering is identical to `ConfigOutOfDate`; details are available + /// through `validation_diagnostics`, `operator_message`, and safe `Debug`. + #[error("config out of date: {}", report.public_message())] + ConfigValidation { report: ValidationReport }, #[error("internal error: {source}")] Internal { #[from] @@ -100,6 +106,17 @@ impl EdgeError { } } + /// Build a fail-closed app-config error from a sanitized report. + #[must_use] + #[inline] + pub fn config_validation(report: ValidationReport) -> Self { + if report.diagnostics().is_empty() { + Self::config_out_of_date(report.public_message(), report.field_path()) + } else { + Self::ConfigValidation { report } + } + } + /// Typed access to the wrapped [`AnyError`] for `EdgeError::Internal`. /// /// Renamed away from `source` to avoid shadowing @@ -113,6 +130,7 @@ impl EdgeError { EdgeError::Internal { source } => Some(source), EdgeError::BadRequest { .. } | EdgeError::ConfigOutOfDate { .. } + | EdgeError::ConfigValidation { .. } | EdgeError::NotFound { .. } | EdgeError::NotImplemented { .. } | EdgeError::MethodNotAllowed { .. } @@ -131,10 +149,23 @@ impl EdgeError { } } + /// Whether this error reports an out-of-date or rejected typed app configuration. + /// Covers both generic failures and failures with approved operator diagnostics. + #[must_use] + #[inline] + pub fn is_config_out_of_date(&self) -> bool { + matches!( + self, + Self::ConfigOutOfDate { .. } | Self::ConfigValidation { .. } + ) + } + fn kind_str(&self) -> &'static str { match self { EdgeError::BadRequest { .. } => "bad_request", - EdgeError::ConfigOutOfDate { .. } => "config_out_of_date", + EdgeError::ConfigOutOfDate { .. } | EdgeError::ConfigValidation { .. } => { + "config_out_of_date" + } EdgeError::Internal { .. } => "internal", EdgeError::MethodNotAllowed { .. } => "method_not_allowed", EdgeError::NotFound { .. } => "not_found", @@ -153,6 +184,7 @@ impl EdgeError { | EdgeError::Validation { message } | EdgeError::NotImplemented { message } | EdgeError::ServiceUnavailable { message } => message.clone(), + EdgeError::ConfigValidation { report } => report.public_message(), EdgeError::NotFound { path } => format!("no route matched path: {path}"), EdgeError::MethodNotAllowed { method, allowed } => { format!("method {method} not allowed; allowed: {allowed}") @@ -198,6 +230,23 @@ impl EdgeError { } } + /// Safe operator view, including approved config diagnostics when present. + #[must_use] + #[inline] + pub fn operator_message(&self) -> String { + match self { + Self::ConfigValidation { report } => report.operator_message(), + Self::BadRequest { .. } + | Self::ConfigOutOfDate { .. } + | Self::Internal { .. } + | Self::MethodNotAllowed { .. } + | Self::NotFound { .. } + | Self::NotImplemented { .. } + | Self::ServiceUnavailable { .. } + | Self::Validation { .. } => self.message(), + } + } + #[inline] pub fn service_unavailable(message: S) -> Self where @@ -213,9 +262,9 @@ impl EdgeError { pub fn status(&self) -> StatusCode { match self { EdgeError::BadRequest { .. } => StatusCode::BAD_REQUEST, - EdgeError::ConfigOutOfDate { .. } | EdgeError::ServiceUnavailable { .. } => { - StatusCode::SERVICE_UNAVAILABLE - } + EdgeError::ConfigOutOfDate { .. } + | EdgeError::ConfigValidation { .. } + | EdgeError::ServiceUnavailable { .. } => StatusCode::SERVICE_UNAVAILABLE, EdgeError::Validation { .. } => StatusCode::UNPROCESSABLE_ENTITY, EdgeError::NotFound { .. } => StatusCode::NOT_FOUND, EdgeError::MethodNotAllowed { .. } => StatusCode::METHOD_NOT_ALLOWED, @@ -233,6 +282,22 @@ impl EdgeError { message: message.into(), } } + /// Approved diagnostics for operator use. Empty for generic errors. + #[must_use] + #[inline] + pub fn validation_diagnostics(&self) -> &[ValidationDiagnostic] { + match self { + Self::ConfigValidation { report } => report.diagnostics(), + Self::BadRequest { .. } + | Self::ConfigOutOfDate { .. } + | Self::Internal { .. } + | Self::MethodNotAllowed { .. } + | Self::NotFound { .. } + | Self::NotImplemented { .. } + | Self::ServiceUnavailable { .. } + | Self::Validation { .. } => &[], + } + } } impl From for EdgeError { @@ -250,7 +315,7 @@ impl IntoResponse for EdgeError { #[inline] fn into_response(self) -> Result { let kind = self.kind_str(); - let is_config_out_of_date = matches!(self, EdgeError::ConfigOutOfDate { .. }); + let is_config_out_of_date = self.is_config_out_of_date(); // `ConfigOutOfDate { field_path: String::new(), .. }` (the missing-blob // path) must OMIT the `field_path` JSON key entirely, not emit // `"field_path": ""`. Per spec 6.3.1. @@ -258,8 +323,12 @@ impl IntoResponse for EdgeError { EdgeError::ConfigOutOfDate { field_path, .. } if !field_path.is_empty() => { Some(field_path.as_str()) } + EdgeError::ConfigValidation { report } if !report.field_path().is_empty() => { + Some(report.field_path()) + } EdgeError::BadRequest { .. } | EdgeError::ConfigOutOfDate { .. } + | EdgeError::ConfigValidation { .. } | EdgeError::Internal { .. } | EdgeError::MethodNotAllowed { .. } | EdgeError::NotFound { .. } @@ -357,6 +426,40 @@ mod tests { assert_eq!(err.message(), "oops"); } + #[test] + fn config_out_of_date_classifies_generic_and_approved_failures() { + use crate::config_diagnostics::{ApprovedDiagnostic, ValidationPathSegment}; + const RULES: &[ApprovedDiagnostic] = &[ApprovedDiagnostic { + path: &[ValidationPathSegment::Field("implementation")], + code: "implementation_unavailable", + explanation: "Rebuild both CLI and guest with the required feature.", + }]; + let mut errors = validator::ValidationErrors::new(); + errors.add( + "implementation", + validator::ValidationError::new(RULES[0].code), + ); + let report = ValidationReport::from_errors(&errors, RULES); + assert_eq!(report.diagnostics().len(), 1); + assert!(EdgeError::config_validation(report).is_config_out_of_date()); + assert!( + EdgeError::config_validation(ValidationReport::from_errors(&errors, &[])) + .is_config_out_of_date() + ); + assert!(EdgeError::config_out_of_date("mismatch", "field").is_config_out_of_date()); + for error in [ + EdgeError::bad_request("bad"), + EdgeError::internal(anyhow::anyhow!("internal")), + EdgeError::method_not_allowed(&Method::GET, &[Method::POST]), + EdgeError::not_found("/"), + EdgeError::not_implemented("missing"), + EdgeError::service_unavailable("down"), + EdgeError::validation("invalid"), + ] { + assert!(!error.is_config_out_of_date(), "{error:?}"); + } + } + #[test] fn config_out_of_date_constructor_round_trips() { let err = EdgeError::config_out_of_date("missing field", "feature.new_checkout"); @@ -374,6 +477,7 @@ mod tests { | EdgeError::NotFound { .. } | EdgeError::NotImplemented { .. } | EdgeError::ServiceUnavailable { .. } + | EdgeError::ConfigValidation { .. } | EdgeError::Validation { .. } => panic!("expected ConfigOutOfDate"), } } @@ -424,6 +528,7 @@ mod tests { | EdgeError::NotFound { .. } | EdgeError::NotImplemented { .. } | EdgeError::ServiceUnavailable { .. } + | EdgeError::ConfigValidation { .. } | EdgeError::Validation { .. } => panic!("expected ConfigOutOfDate"), } } @@ -478,6 +583,7 @@ mod tests { | EdgeError::NotFound { .. } | EdgeError::NotImplemented { .. } | EdgeError::ServiceUnavailable { .. } + | EdgeError::ConfigValidation { .. } | EdgeError::Validation { .. } => panic!("expected ConfigOutOfDate"), } } @@ -517,6 +623,7 @@ mod tests { | EdgeError::NotFound { .. } | EdgeError::NotImplemented { .. } | EdgeError::ServiceUnavailable { .. } + | EdgeError::ConfigValidation { .. } | EdgeError::Validation { .. } => panic!("expected ConfigOutOfDate"), } } diff --git a/crates/edgezero-core/src/extractor.rs b/crates/edgezero-core/src/extractor.rs index 7c131e7b5..f14dd5faa 100644 --- a/crates/edgezero-core/src/extractor.rs +++ b/crates/edgezero-core/src/extractor.rs @@ -10,6 +10,7 @@ use validator::Validate; use crate::app_config::{AppConfigMeta, SecretField, SecretKind, SecretPathSegment}; use crate::blob_envelope::{BlobEnvelope, BlobEnvelopeError}; +use crate::config_diagnostics::ValidationReport; use crate::config_store::ConfigStoreHandle; use crate::context::RequestContext; use crate::error::EdgeError; @@ -951,18 +952,10 @@ where // is a key NAME; RUNTIME runs cfg.validate() because the value is // now the resolved secret. cfg.validate().map_err(|err| { - // SECURITY: `secret_walk` has replaced `#[secret]` fields with their - // RESOLVED values, and `validator`'s error params echo the rejected - // value — so `err.to_string()` here can leak a secret into the HTTP - // response body and logs. Keep the field path (structural, not secret) - // but drop the formatted validator details on this runtime path. - let field = first_violating_field(&err).unwrap_or_default(); - let message = if field.is_empty() { - "app config failed validation".to_owned() - } else { - format!("app config failed validation for field `{field}`") - }; - EdgeError::config_out_of_date(message, field) + EdgeError::config_validation(ValidationReport::from_errors( + &err, + C::validation_diagnostics(), + )) })?; Ok(cfg) } @@ -1196,63 +1189,11 @@ fn map_secret_error( } } -/// Walk `errors` recursively and return the first violating field's DOTTED -/// PATH (e.g. `"service.timeout_ms"` for a nested failure). -/// -/// Keys are sorted for determinism across runs — required for the 6.3.1 -/// contract test. An earlier draft only looked at top-level keys, -/// collapsing nested paths like `service.timeout_ms` to `"service"`. -fn first_violating_field(errors: &validator::ValidationErrors) -> Option { - fn walk(errors: &validator::ValidationErrors, prefix: &str, out: &mut Option) { - if out.is_some() { - return; - } - // Validator 0.20 stores keys as `Cow<'static, str>`. - // `.as_ref()` gives `&str`; sort for determinism. - let mut keys: Vec<&str> = errors.errors().keys().map(AsRef::as_ref).collect(); - keys.sort_unstable(); - for key in keys { - let path = if prefix.is_empty() { - key.to_owned() - } else { - format!("{prefix}.{key}") - }; - match errors.errors().get(key) { - Some(validator::ValidationErrorsKind::Field(_)) => { - *out = Some(path); - return; - } - Some(validator::ValidationErrorsKind::Struct(inner)) => { - walk(inner, &path, out); - if out.is_some() { - return; - } - } - Some(validator::ValidationErrorsKind::List(items)) => { - // BTreeMap>; iterate - // in index order for determinism. - let mut indices: Vec = items.keys().copied().collect(); - indices.sort_unstable(); - for idx in indices { - if let Some(inner) = items.get(&idx) { - let indexed = format!("{path}[{idx}]"); - walk(inner, &indexed, out); - if out.is_some() { - return; - } - } - } - } - None => {} - } - } - } - let mut out: Option = None; - walk(errors, "", &mut out); - out -} - #[cfg(test)] +#[expect( + clippy::missing_trait_methods, + reason = "fixtures exercise the default-empty diagnostic metadata contract" +)] mod tests { use super::*; use crate::app_config::{AppConfigMeta, SecretField, SecretKind, SecretPathSegment}; @@ -2655,6 +2596,233 @@ mod tests { } } + // The existing test-utils feature stands in for a compiled implementation. + // Adapter dev-dependencies enable it during workspace feature unification, + // so CI also runs this test with core alone to exercise the refusal branch. + #[test] + fn runtime_approved_diagnostic_tracks_compiled_availability() { + use crate::config_diagnostics::{ApprovedDiagnostic, ValidationPathSegment}; + use crate::response::IntoResponse as _; + use std::sync::atomic::{AtomicUsize, Ordering}; + const RULES: &[ApprovedDiagnostic] = &[ApprovedDiagnostic { + path: &[ValidationPathSegment::Field("implementation")], + code: "implementation_unavailable", + explanation: "Enable feature test-utils and rebuild both CLI and serving guest.", + }]; + #[derive(Debug, Deserialize, crate::AppConfig)] + #[app_config(diagnostics = RULES)] + struct CompiledConfig { + implementation: String, + #[secret] + token: String, + } + impl Validate for CompiledConfig { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + if self.implementation == "test-bidder" && !cfg!(feature = "test-utils") { + let mut error = validator::ValidationError::new("implementation_unavailable"); + error.message = Some(Cow::Owned(format!("unsafe {}", self.token))); + error.add_param(Cow::Borrowed("value"), &self.token); + let mut errors = validator::ValidationErrors::new(); + errors.add("implementation", error); + Err(errors) + } else { + Ok(()) + } + } + } + struct CountingStore(Arc); + #[async_trait(?Send)] + impl ConfigStore for CountingStore { + async fn get(&self, _key: &str) -> Result, ConfigStoreError> { + self.0.fetch_add(1, Ordering::SeqCst); + Ok(Some(make_envelope( + serde_json::json!({"implementation":"test-bidder", "token":"key"}), + ))) + } + } + let reads = Arc::new(AtomicUsize::new(0)); + let secrets = InMemorySecretStore::new([( + "vault/key", + bytes::Bytes::from_static(b"RESOLVED_SECRET_CANARY"), + )]); + let ctx = + ctx_with_config_and_secrets(CountingStore(Arc::clone(&reads)), "key", secrets, "vault"); + let result = block_on(AppConfig::::from_store( + &ctx, + "default", + Some("key"), + )); + assert_eq!(reads.load(Ordering::SeqCst), 1); + if cfg!(feature = "test-utils") { + let loaded = result.expect("compiled implementation accepts same policy"); + assert_eq!(loaded.implementation, "test-bidder"); + assert_eq!(loaded.token, "RESOLVED_SECRET_CANARY"); + } else { + let error = result.expect_err("missing compiled implementation"); + assert_eq!(error.validation_diagnostics().len(), 1); + assert!(error.operator_message().contains(RULES[0].explanation)); + assert!(!error.message().contains(RULES[0].explanation)); + assert!(!format!("{error:?} {error}").contains("RESOLVED_SECRET_CANARY")); + let response = error.into_response().expect("public error"); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(response.headers()["retry-after"], "60"); + let payload: serde_json::Value = + serde_json::from_slice(response.body().as_bytes().expect("buffered")) + .expect("JSON"); + assert_eq!(payload["error"]["field_path"], ""); + assert_eq!( + payload["error"]["message"], + "app config failed validation for field ``" + ); + let body = String::from_utf8_lossy(response.body().as_bytes().expect("buffered")); + for hidden in [ + RULES[0].explanation, + RULES[0].code, + "RESOLVED_SECRET_CANARY", + ] { + assert!(!body.contains(hidden)); + } + } + } + + #[test] + fn from_store_preserves_approved_nested_list_diagnostic() { + use crate::config_diagnostics::{ApprovedDiagnostic, ValidationPathSegment}; + const RULES: &[ApprovedDiagnostic] = &[ApprovedDiagnostic { + path: &[ + ValidationPathSegment::Field("bidders"), + ValidationPathSegment::Each, + ValidationPathSegment::Field("implementation"), + ], + code: "implementation_unavailable", + explanation: "Enable feature bidder-x and rebuild CLI and guest.", + }]; + fn unavailable(_value: &str) -> Result<(), validator::ValidationError> { + Err(validator::ValidationError::new( + "implementation_unavailable", + )) + } + #[derive(Debug, Deserialize, Validate)] + struct Bidder { + #[validate(custom(function = "unavailable"))] + implementation: String, + } + #[derive(Debug, Deserialize, Validate, crate::AppConfig)] + #[app_config(diagnostics = RULES)] + struct NestedPolicy { + #[validate(nested)] + bidders: Vec, + } + struct NestedStore; + #[async_trait(?Send)] + impl ConfigStore for NestedStore { + async fn get(&self, _key: &str) -> Result, ConfigStoreError> { + Ok(Some(make_envelope( + serde_json::json!({"bidders":[{"implementation":"bidder-x"}]}), + ))) + } + } + let ctx = ctx_with_config_store(NestedStore, "key"); + let error = block_on(AppConfig::::from_store(&ctx, "default", None)) + .expect_err("unavailable"); + assert_eq!(error.validation_diagnostics().len(), 1); + assert_eq!( + error.validation_diagnostics()[0].field_path(), + "bidders[0].implementation" + ); + assert_eq!( + error.validation_diagnostics()[0].explanation(), + RULES[0].explanation + ); + } + + #[test] + fn runtime_validation_redacts_untrusted_map_keys() { + use crate::response::IntoResponse as _; + use std::sync::OnceLock; + static RUNTIME_KEY: OnceLock = OnceLock::new(); + #[derive(Debug, Deserialize)] + struct HostileConfig { + borrowed: bool, + key: String, + nested: bool, + } + impl AppConfigMeta for HostileConfig { + fn secret_fields() -> Vec { + Vec::new() + } + } + impl Validate for HostileConfig { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + let mut errors = validator::ValidationErrors::new(); + let error = validator::ValidationError::new("custom"); + if self.borrowed { + // A static lifetime does not prove schema provenance: this + // borrowed key was read from configuration at runtime. + let key = RUNTIME_KEY.get_or_init(|| self.key.clone()).as_str(); + errors.add(key, error); + } else { + errors.errors_mut().insert( + Cow::Owned(self.key.clone()), + validator::ValidationErrorsKind::Field(vec![error]), + ); + } + if self.nested { + let mut parent = validator::ValidationErrors::new(); + parent.errors_mut().insert( + Cow::Borrowed("items"), + validator::ValidationErrorsKind::List( + [(2, Box::new(errors))].into_iter().collect(), + ), + ); + errors = parent; + } + Err(errors) + } + } + struct HostileStore { + borrowed: bool, + nested: bool, + } + #[async_trait(?Send)] + impl ConfigStore for HostileStore { + async fn get(&self, _key: &str) -> Result, ConfigStoreError> { + Ok(Some(make_envelope(serde_json::json!({ + "key": "SECRET_MAP_KEY_CANARY", + "borrowed": self.borrowed, + "nested": self.nested, + })))) + } + } + for borrowed in [true, false] { + for nested in [false, true] { + let ctx = ctx_with_config_store(HostileStore { borrowed, nested }, "key"); + let error = + block_on(AppConfig::::from_request(&ctx)).expect_err("invalid"); + let output = format!( + "{error:?} {error} {} {}", + error.message(), + error.operator_message() + ); + assert!(!output.contains("SECRET_MAP_KEY_CANARY"), "{output}"); + assert!(error.validation_diagnostics().is_empty()); + let expected_path = if nested { + "[2]." + } else { + "" + }; + let response = error.into_response().expect("public error"); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(response.headers()["retry-after"], "60"); + let body: serde_json::Value = + serde_json::from_slice(response.body().as_bytes().expect("buffered")) + .expect("JSON"); + assert_eq!(body["error"]["field_path"], expected_path); + assert!(!body.to_string().contains("SECRET_MAP_KEY_CANARY")); + } + } + } + #[test] fn app_config_extractor_returns_config_out_of_date_on_validation_failure() { use crate::config_store::{ConfigStore, ConfigStoreError}; @@ -2678,8 +2846,8 @@ mod tests { ); if let EdgeError::ConfigOutOfDate { field_path, .. } = &err { assert_eq!( - field_path, "timeout_ms", - "field_path names the violator: {err:?}" + field_path, "", + "unapproved field name is redacted: {err:?}" ); } } @@ -3139,8 +3307,8 @@ mod tests { ); if let EdgeError::ConfigOutOfDate { field_path, .. } = &err { assert_eq!( - field_path, "api_token", - "field_path names the violating secret field: {err:?}" + field_path, "", + "unapproved secret field name is redacted: {err:?}" ); } } @@ -3186,8 +3354,8 @@ mod tests { // The error message names the field but NOT the secret. assert!( - err.message().contains("api_token"), - "names the field: {err:?}" + err.message().contains(""), + "redacts unapproved field names: {err:?}" ); assert!( !err.message().contains(SECRET), diff --git a/crates/edgezero-core/src/lib.rs b/crates/edgezero-core/src/lib.rs index c0f1e89e8..5611e71f6 100644 --- a/crates/edgezero-core/src/lib.rs +++ b/crates/edgezero-core/src/lib.rs @@ -20,6 +20,7 @@ pub mod blob_envelope; pub mod body; pub mod canonical_form; pub mod compression; +pub mod config_diagnostics; pub mod config_store; pub mod context; pub mod env_config; diff --git a/crates/edgezero-core/src/middleware.rs b/crates/edgezero-core/src/middleware.rs index a9edaf2c0..a83155e24 100644 --- a/crates/edgezero-core/src/middleware.rs +++ b/crates/edgezero-core/src/middleware.rs @@ -96,7 +96,7 @@ impl Middleware for RequestLogger { } Err(err) => { let status = err.status(); - let message = err.message(); + let message = err.operator_message(); let elapsed = start.elapsed().as_millis(); tracing::error!( "request method={} path={} status={} error={} elapsed_ms={}", @@ -247,6 +247,84 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); } + #[test] + fn request_logger_emits_approved_operator_diagnostic() { + use crate::config_diagnostics::{ + ApprovedDiagnostic, ValidationPathSegment, ValidationReport, + }; + use std::fmt::{Debug, Write as _}; + use std::sync::Mutex; + use tracing::subscriber::with_default; + use tracing::{ + Event, Metadata, Subscriber, + field::{Field, Visit}, + span::{Attributes, Id, Record}, + }; + + struct Capture(Arc>); + #[expect( + clippy::missing_trait_methods, + reason = "typed value recording defaults route to record_debug" + )] + impl Visit for Capture { + #[expect( + clippy::use_debug, + reason = "tracing Visit supplies values through the Debug trait" + )] + fn record_debug(&mut self, _field: &Field, value: &dyn Debug) { + write!(self.0.lock().expect("capture"), "{value:?}") + .expect("String writes cannot fail"); + } + } + #[expect( + clippy::missing_trait_methods, + clippy::arbitrary_source_item_ordering, + reason = "subscriber methods follow the trait lifecycle; defaults suffice for scoped capture" + )] + impl Subscriber for Capture { + fn enabled(&self, _metadata: &Metadata<'_>) -> bool { + true + } + fn new_span(&self, _attributes: &Attributes<'_>) -> Id { + Id::from_u64(1) + } + fn record(&self, _span: &Id, _values: &Record<'_>) {} + fn record_follows_from(&self, _span: &Id, _follows: &Id) {} + fn event(&self, event: &Event<'_>) { + event.record(&mut Self(Arc::clone(&self.0))); + } + fn enter(&self, _span: &Id) {} + fn exit(&self, _span: &Id) {} + } + let mut errors = validator::ValidationErrors::new(); + let mut detail = validator::ValidationError::new("unavailable"); + detail.message = Some("UNTRUSTED_LOG_MESSAGE_CANARY".into()); + errors.add("implementation", detail); + let report = ValidationReport::from_errors( + &errors, + &[ApprovedDiagnostic { + path: &[ValidationPathSegment::Field("implementation")], + code: "unavailable", + explanation: "Rebuild CLI and guest with feature bidder-x.", + }], + ); + let handler = (move |_ctx: RequestContext| { + let safe_report = report.clone(); + async move { Err::(EdgeError::config_validation(safe_report)) } + }) + .into_handler(); + let output = Arc::new(Mutex::new(String::new())); + with_default(Capture(Arc::clone(&output)), || { + let error = + block_on(RequestLogger.handle(empty_context(), Next::new(&[], handler.as_ref()))) + .expect_err("refused"); + assert_eq!(error.validation_diagnostics().len(), 1); + }); + let captured = output.lock().expect("capture"); + assert!(captured.contains("Rebuild CLI and guest with feature bidder-x.")); + assert!(!captured.contains("UNTRUSTED_LOG_MESSAGE_CANARY")); + } + #[test] fn request_logger_propagates_error() { let handler = (|_ctx: RequestContext| async move { diff --git a/crates/edgezero-macros/src/app_config.rs b/crates/edgezero-macros/src/app_config.rs index 36e0898a3..073b2e268 100644 --- a/crates/edgezero-macros/src/app_config.rs +++ b/crates/edgezero-macros/src/app_config.rs @@ -146,7 +146,13 @@ fn expand(input: &DeriveInput) -> Result { } } - Ok(emit_impl(input, &annotations, &nested_descriptors)) + let diagnostics = diagnostics_registry(&input.attrs)?; + Ok(emit_impl( + input, + &annotations, + &nested_descriptors, + diagnostics.as_ref(), + )) } /// Classify every field as a direct `#[secret]` annotation or a @@ -198,7 +204,9 @@ fn emit_impl( input: &DeriveInput, annotations: &[FieldAnnotation], nested_descriptors: &[NestedDescriptor<'_>], + diagnostics: Option<&syn::Path>, ) -> TokenStream2 { + let diagnostic_method = emit_diagnostic_method(diagnostics); let struct_ident = &input.ident; let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl(); @@ -311,6 +319,7 @@ fn emit_impl( impl #impl_generics ::edgezero_core::app_config::AppConfigMeta for #struct_ident #type_generics #where_clause { + #diagnostic_method fn secret_fields() -> ::std::vec::Vec<::edgezero_core::app_config::SecretField> { #root_bound_checks #secret_fields_body @@ -650,3 +659,84 @@ fn enforce_no_disallowed_serde_attrs(field: &Field) -> Result<(), syn::Error> { } Ok(()) } + +/// Parse the root-only diagnostic registry opt-in, rejecting typos/duplicates. +fn diagnostics_registry(attrs: &[Attribute]) -> Result, syn::Error> { + let mut registry = None; + for attr in attrs + .iter() + .filter(|attr| attr.path().is_ident("app_config")) + { + let mut seen = false; + attr.parse_nested_meta(|meta| { + seen = true; + if !meta.path.is_ident("diagnostics") { + return Err(meta.error("root app_config only accepts diagnostics = REGISTRY")); + } + if registry.is_some() { + return Err(meta.error("duplicate diagnostics registry")); + } + registry = Some(meta.value()?.parse()?); + Ok(()) + })?; + if !seen { + return Err(syn::Error::new_spanned( + attr, + "expected diagnostics = REGISTRY", + )); + } + } + Ok(registry) +} + +fn emit_diagnostic_method(diagnostics: Option<&syn::Path>) -> Option { + diagnostics.map(|registry| quote! { + fn validation_diagnostics() -> &'static [::edgezero_core::config_diagnostics::ApprovedDiagnostic] { + #registry + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn diagnostic_registry_attribute_rejects_unknown_duplicate_and_empty_options() { + for input in [ + syn::parse_quote!( + #[app_config(bogus = RULES)] + struct C { + value: String, + } + ), + syn::parse_quote!( + #[app_config(diagnostics = A, diagnostics = B)] + struct C { + value: String, + } + ), + syn::parse_quote!( + #[app_config()] + struct C { + value: String, + } + ), + ] { + expand(&input).expect_err("invalid registry declaration"); + } + } + + #[test] + fn diagnostic_registry_attribute_emits_root_method() { + let input = syn::parse_quote!( + #[app_config(diagnostics = crate::RULES)] + struct C { + value: String, + } + ); + let output = expand(&input).expect("registry attribute").to_string(); + assert!(output.contains("fn validation_diagnostics")); + assert!(output.contains("crate :: RULES")); + } +} diff --git a/docs/guide/blob-app-config-migration.md b/docs/guide/blob-app-config-migration.md index 86f6f74c0..0269b366a 100644 --- a/docs/guide/blob-app-config-migration.md +++ b/docs/guide/blob-app-config-migration.md @@ -386,6 +386,24 @@ Run ` config push --adapter ` for the deployed code revision to fix the first two cases; provision the missing secret to fix the third. +### Config validation rejects a compiled implementation + +A policy may select an implementation whose Cargo feature is absent from the +serving guest. Typed validation still fails closed, even if a CLI built with the +feature accepted the same policy. Rebuild both CLI and guest with matching +features; another config push cannot add missing compiled code. + +Applications can register [safe operator diagnostics](./configuration.md#safe-operator-validation-diagnostics) +from compiled declarations to identify the required feature. Approved failures use +`EdgeError::ConfigValidation`; CLI errors include the approved explanation. +Replace `matches!(err, EdgeError::ConfigOutOfDate { .. })` with +`err.is_config_out_of_date()` when both generic and approved failures should match. +`RequestLogger` includes it when a tracing subscriber or tracing-to-`log` bridge +is configured; applications can also log `err.operator_message()` explicitly. +Public responses retain the coarse `config_out_of_date` 503 and `Retry-After: 60`. +Unregistered failures remain generic, and arbitrary validator +messages, values, and map keys are never promoted into diagnostics. + ### `config push` reports "this command requires a typed app-config struct" You ran `edgezero config push` from the BUNDLED binary instead of your diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 4aef7303f..a5b36d2c4 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -281,6 +281,98 @@ let cfg: MyAppConfig = The function deserialises, runs the `validator` rules (e.g. `#[validate(range(...))]`), and returns the typed struct. +### Safe operator validation diagnostics + +Runtime extraction and typed CLI `config validate`, `config push`, and `config diff` +never print validator messages or parameter maps. By default they report a generic +failure and redact validator field names, since a custom validator may use a +stored map key as a field name. Even a borrowed (`Cow::Borrowed`) name can +come from runtime data held in static storage; its lifetime does not establish +that it belongs to the schema. Numeric list positions can remain visible. +To restore an operator location such as `service.timeout_ms`, register that exact +path and its validator code (for example, `range`) with a fixed explanation. + +To approve an operator explanation, register a fixed structural path, code, and +explanation on the **root** config type: + +```rust +use edgezero_core::config_diagnostics::{ApprovedDiagnostic, ValidationPathSegment}; +use serde::{Deserialize, Serialize}; +use validator::{Validate, ValidationError}; + +const DIAGNOSTICS: &[ApprovedDiagnostic] = &[ApprovedDiagnostic { + path: &[ValidationPathSegment::Field("implementation")], + code: "implementation_unavailable", + explanation: "Enable Cargo feature bidder-x and rebuild both CLI and serving guest.", +}]; + +#[derive(Deserialize, Serialize, Validate, edgezero_core::AppConfig)] +#[app_config(diagnostics = DIAGNOSTICS)] +struct Policy { + #[validate(custom(function = "implementation_available"))] + implementation: String, +} + +fn implementation_available(value: &str) -> Result<(), ValidationError> { + if value == "bidder-x" && !cfg!(feature = "bidder-x") { + return Err(ValidationError::new("implementation_unavailable")); + } + Ok(()) +} +``` + +The feature in this example belongs to the consuming application. Registry strings +must be reviewed, compiled declarations: never construct them from configuration, +secrets, rejected URLs, or validator parameters. Matching requires the exact code +and complete path; a matching code elsewhere does not approve a diagnostic. +Use `ValidationPathSegment::Each` for a numeric list position, for example +`[Field("bidders"), Each, Field("implementation")]`. Wildcards never match string +map keys. Nested diagnostics must be registered with their full path at the root. +Registries on nested types are not inherited. +Handwritten `AppConfigMeta` implementations can override `validation_diagnostics()`; +its default is an empty registry. + +The shared sanitizer inspects the existing validation result without another store +read, policy parse, or validation call. Runtime validates **resolved secrets**; CLI +commands still skip secret-field rules while those fields contain key names. CLI +success cannot certify a guest built with different Cargo features. A missing +implementation requires rebuilding both binaries with matching features; pushing +configuration again cannot add code to the guest. + +Approved failures use `EdgeError::ConfigValidation`; unapproved failures retain +`ConfigOutOfDate`. Replace checks such as +`matches!(err, EdgeError::ConfigOutOfDate { .. })` with +`err.is_config_out_of_date()` to classify both variants. Use +`err.validation_diagnostics()` or `err.operator_message()` for operator output. +`RequestLogger` uses the operator view through `tracing`. To receive these events, +configure a tracing subscriber, or enable tracing's `log` feature and initialize a +`log` logger. Adapter logger initialization alone does not guarantee that tracing +events reach a log sink. Alternatively, log `err.operator_message()` explicitly +through your application's configured logger. + +`message()`, `Display`, and the HTTP response stay coarse: status 503, kind +`config_out_of_date`, and `Retry-After: 60`, without +approved codes or explanations. `Debug` includes the safe report, never the raw +validation error. This policy concerns typed validation failures; it does not make +arbitrary application errors or local loader errors safe to log. + +| Diagnostic limit | Maximum | +| -------------------------------------------------------- | ------: | +| Registry entries | 64 | +| Approved diagnostics per failure | 8 | +| Code bytes (ASCII letters, digits, underscore) | 64 | +| Single-line explanation bytes | 512 | +| Rendered path bytes | 256 | +| Path depth | 32 | +| Visited validation containers, entries, and field errors | 1,024 | + +Field declarations accept ASCII letters, digits, underscores, and hyphens. Invalid +or oversized entries are ignored; a registry exceeding 64 entries is ignored in +full. Oversized raw keys are omitted. Diagnostic collection stops at its traversal +or count limit. Every such case remains a validation **failure**, with generic +reporting where no approved diagnostic is retained. Explanations are never +truncated. Existing extraction byte/depth/node limits and deadlines are unchanged. + ### Secret annotations | Attribute | Meaning | diff --git a/docs/superpowers/plans/2026-11-13-safe-config-diagnostics.md b/docs/superpowers/plans/2026-11-13-safe-config-diagnostics.md new file mode 100644 index 000000000..58403df53 --- /dev/null +++ b/docs/superpowers/plans/2026-11-13-safe-config-diagnostics.md @@ -0,0 +1,34 @@ +# Safe app-config validation diagnostics implementation plan + +**Goal:** Preserve explicitly approved operator diagnostics while keeping untrusted validation details out of logs and HTTP responses. + +**Architecture:** Shared bounded core sanitizer, default-empty static metadata registry, optional derive registration, separate operator and public error views. No new dependencies or store reads. + +- [x] Add failing sanitizer tests in a colocated `config_diagnostics` module: exact path/code approval, nested arrays, unknown codes/keys, value/message canaries and limits. Run `cargo +1.98.1 test -p edgezero-core`; implement the bounded registry walker and rerun. +- [x] Add default registry metadata and optional derive attribute in `app_config.rs` and `edgezero-macros/src/app_config.rs`. Test normal derives and invalid registry declarations/attributes; preserve existing derives and manual metadata implementations. +- [x] Add failing extraction and error-rendering tests. Add opt-in diagnostic-bearing error variant and accessors; replace `first_violating_field` with sanitized reporting. Update logger operator formatting. Keep 503/kind/retry/public text and one read. Run scoped core tests after each change. +- [x] Add CLI typed validate/push/diff regression coverage and replace their raw validation formatting with shared reporting. Preserve secret pruning and perform no remote operations on validation failure. Run CLI tests. +- [x] Add affected adapter extraction/response contract coverage (Fastly, Cloudflare, Spin, Axum) and documentation in configuration and migration guides. Run applicable scoped tests after changes. +- [x] Review the combined diff against #457, including limits and secret/value paths. Run format, full-feature clippy, workspace tests, adapter feature checks, Spin WASM compile, and available actual adapter contract runners. Use Rust 1.98.1. Record blocked runners separately. +- [x] Report exact tested revision/worktree, API compatibility adjustments, verification, and remaining limitations. Publication remains separate. + +## Verification result + +Verified on Rust 1.98.1 and Node.js 24.20.0. The final workspace run passed +1,565 tests across 21 targets. Scoped core tests ran separately without +`test-utils` to exercise compiled-feature refusal, and with it to exercise the +same policy's success. The logger regression failed when temporarily routed to +`message()` and passed after restoring `operator_message()`. + +Passed: workspace formatting, full-feature/all-target Clippy, workspace tests, +`fastly cloudflare spin` feature compilation, required Spin WASM compilation, +all three WASM adapter test-target compilation checks, Axum's extraction/response +contract, docs ESLint, and full docs Prettier checks. Independent source review +found no blocking defects; boundary controls and nested extraction coverage were +added in response to its coverage observations. + +WASM runtime qualification remains outstanding: local Viceroy 0.17.0 cannot load +the current Fastly SDK (project pin 0.21.0); the Cloudflare runner is 0.2.122 +instead of the locked 0.2.128 and has no browser driver; Wasmtime is unavailable. +These are compilation results, not claims of passing provider runtime contracts. +No hosted-provider or downstream Auctioneer execution is claimed. diff --git a/docs/superpowers/specs/2026-11-13-safe-config-diagnostics-design.md b/docs/superpowers/specs/2026-11-13-safe-config-diagnostics-design.md new file mode 100644 index 000000000..dfa9b9e9d --- /dev/null +++ b/docs/superpowers/specs/2026-11-13-safe-config-diagnostics-design.md @@ -0,0 +1,25 @@ +# Safe app-config validation diagnostics + +Issue: [#457](https://github.com/IABTechLab/edgezero/issues/457). + +## Contract + +Typed app-config validation may preserve explicitly approved operator diagnostics without retaining validator messages, parameters, or resolved values. A root-owned static registry maps structural path patterns and error codes to fixed explanations. `AppConfigMeta` defaults to no approved diagnostics; an optional `#[app_config(diagnostics = REGISTRY)]` derive attribute enables the registry. Paths use named field segments and array wildcard segments, matched against the validation tree, rather than arbitrary string interpolation. + +Only approved names, codes, explanations, and numeric list positions enter diagnostics. Unknown validator keys are redacted even if they resemble identifiers. Generic failures continue to fail closed. Redacting previously echoed, unapproved field names is an intentional security adjustment. + +Bound registry inspection to 64 entries, output to 8 diagnostics, codes to 64 bytes, single-line explanations to 512 bytes, paths to 256 bytes, traversal to 32 levels and 1,024 visited nodes. Invalid declarations are ignored. Exhaustion never converts validation failure to success. Do not truncate explanations into a different meaning. + +Attach approved diagnostics to a new opt-in `EdgeError` variant, preserving existing `ConfigOutOfDate` constructors. Both variants render HTTP 503, kind `config_out_of_date`, and `Retry-After: 60`. Public messages remain coarse; an explicit operator accessor provides approved details to logging. Applications opting in must account for the additional variant or use the shared diagnostic/classification accessor. + +CLI validate/push/diff use the same sanitizer after existing secret-validator pruning. Runtime validates resolved secrets; CLI validates key names and skips secret-field validators. CLI success does not certify a differently compiled guest. A diagnostic for a missing compiled implementation may explain its required Cargo feature and instruct rebuilding both CLI and serving guest. + +The existing validation result is inspected once; do not read the store again, parse the complete policy again, or run a second validation. Existing extraction/deadline/resource behavior is preserved. Adapter production behavior remains shared through core. + +## Alternatives + +A callback could construct explanations from resolved values and permits accidental disclosures. Static declarations provide a smaller trust boundary. Adding fields to `ConfigOutOfDate` breaks existing constructors; the new variant limits migration to applications opting in. Complete schema derivation solely to preserve all old field names would broaden macro scope substantially; unknown paths instead remain redacted. + +## Evidence required + +Tests must cover approved semantic refusal, compiled-availability success control, ordinary and nested/list validation, hostile keys/messages/parameters, resolved-secret and rejected-URL canaries, bounds, and the single-read invariant. Verify CLI entry points and logger/public response separation. Exercise affected adapter contracts with coarse 503 responses and report native tests separately from actual WASM runner execution.