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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions crates/edgezero-adapter-axum/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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![
Expand Down
23 changes: 23 additions & 0 deletions crates/edgezero-adapter-cloudflare/tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
19 changes: 19 additions & 0 deletions crates/edgezero-adapter-fastly/tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down
29 changes: 29 additions & 0 deletions crates/edgezero-adapter-spin/tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
173 changes: 165 additions & 8 deletions crates/edgezero-cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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| {
Comment thread
prk-Jr marked this conversation as resolved.
Resolved
format!(
"typed app-config failed validation: {}",
format_validation_error::<C>(&err)
)
})?;

typed_secret_checks(&typed, &ctx)?;
run_adapter_typed_checks::<C>(&ctx, AdapterValidationScope::All)?;
Expand Down Expand Up @@ -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: {}",
format_validation_error::<C>(&err)
)
})?;
typed_secret_checks(&typed, &ctx.validation)?;
run_adapter_typed_checks::<C>(&ctx.validation, validation_scope)?;

Expand Down Expand Up @@ -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: {}",
format_validation_error::<C>(&err)
)
})?;
typed_secret_checks(&typed, &ctx)?;
run_adapter_typed_checks::<C>(&ctx, validation_scope)?;

Expand Down Expand Up @@ -2077,6 +2090,20 @@ fn is_rust_ident(segment: &str) -> bool {
// Error formatting
// -------------------------------------------------------------------

fn format_validation_error<C>(errors: &validator::ValidationErrors) -> String
where
C: AppConfigMeta,
{
let report = ValidationReport::from_errors(errors, C::validation_diagnostics());
let mut message = report.operator_message();
if report.diagnostics().is_empty() {
message.push_str(
"; register matching diagnostics with #[app_config(diagnostics = ...)] to see field locations",
);
}
message
}

fn format_app_config_error(err: &AppConfigError) -> String {
err.to_string()
}
Expand All @@ -2087,6 +2114,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};
Expand Down Expand Up @@ -2975,8 +3006,115 @@ 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::<RefusedConfig>(&args_for(&manifest))
.expect_err("refused validate"),
run_config_push_typed::<RefusedConfig>(&push_args(&manifest, "axum"))
.expect_err("refused push"),
run_config_diff_typed::<RefusedConfig>(&diff).expect_err("refused diff"),
];
for error in errors {
assert!(error.contains("validation"));
assert_eq!(
error.contains(
"register matching diagnostics with #[app_config(diagnostics = ...)]"
),
selection == "unapproved",
"matching-registration hint must reflect diagnostic registration"
);
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),
"validator output must omit untrusted messages and rejected values"
);
}
}
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<SecretField> {
FixtureConfig::secret_fields()
}
fn validation_diagnostics() -> &'static [ApprovedDiagnostic] {
RULES
}
}
let app_config = r#"
api_token = "x"
greeting = "hi"
Expand All @@ -2989,8 +3127,27 @@ timeout_ms = 50
let err = run_config_validate_typed::<FixtureConfig>(&args_for(&manifest))
.expect_err("validator rule must error");
assert!(
err.to_lowercase().contains("validation"),
"error mentions validation: {err}"
err.contains("register matching diagnostics with #[app_config(diagnostics = ...)]"),
"unregistered validator failures must explain diagnostic registration"
);
assert!(
!err.contains("service.timeout_ms"),
"unregistered validator paths must remain private"
);

let approved = run_config_validate_typed::<RegisteredConfig>(&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."),
"registered validator failures must include the approved diagnostic"
);
assert!(
!approved.contains("<redacted>"),
"approved diagnostics must preserve their registered paths"
);
assert!(
!approved.contains("register matching diagnostics"),
"registered validator failures must omit the registration hint"
);
}

Expand Down
14 changes: 14 additions & 0 deletions crates/edgezero-core/src/app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<SecretField>;

/// 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! {
Expand Down Expand Up @@ -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};
Expand Down
Loading
Loading