From 004132d8ae2628c1ac8d2d5a4cdeea99e1d11caf Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Wed, 1 Jul 2026 19:31:36 +0200 Subject: [PATCH 1/4] =?UTF-8?q?feat(server):=20rfc0020=20green=20pt2=20?= =?UTF-8?q?=E2=80=94=20YAML=20schema=20+=20scalar-value=20substitution=20w?= =?UTF-8?q?alk?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add `config::file`: the RFC 0020 configuration-file schema (`FileConfig`) and the walk that applies `${env:…}` substitution to the file. `parse` reads the YAML into a node tree, substitutes references in scalar **values** only (mapping keys left verbatim — §3.3 rule 4), then deserialises the substituted tree into a strict schema (`deny_unknown_fields`). A substituted value is a scalar `String` that is never re-parsed into YAML structure (rule 5), so it can neither rewrite keys nor inject a mapping/sequence. Type-after-substitution (§3.3 rule 7) is resolved at the typed boundary, not by re-tagging the node tree: `serde_yaml`'s `Value` does not preserve a scalar's quoting style, so a re-tag pass cannot distinguish a quoted string from a bare scalar and would coerce `"01"` to an integer. Instead every leaf is carried as its string form (a literal `3600` and a substituted `${env:W}`→`3600` both become `"3600"`) and the final type is resolved when that string flows through the existing `build_*` validators — the single validation path (§3.1), wired in the next slice. Observationally identical for the bounded schema, and a quoted scalar can never be corrupted into a number. Closes RFC0020.2 (substitution semantics through the file, pinned end-to-end via the un-ignored §5 scenario against the WG-conformant `env_subst` resolver). The malformed-reference and unknown-key arms of RFC0020.5 land here; its value-validation arm and RFC0020.1/.3/.4 follow with the `--config` wiring. `serde_yaml` is already vetted in the dep tree (ourios-querier pins the same `=0.9.34`), so this adds no new cargo-deny surface. Verified: `cargo fmt --all --check`, `cargo clippy --all-targets --all-features -D warnings`, `cargo test -p ourios-server --all-features` (config::file unit tests + RFC0020.2 scenario green). Co-Authored-By: Claude Opus 4.8 (1M context) --- Cargo.lock | 1 + crates/ourios-server/Cargo.toml | 5 + crates/ourios-server/src/config.rs | 10 +- crates/ourios-server/src/config/file.rs | 451 ++++++++++++++++++ .../tests/rfc0020_config_file.rs | 42 +- 5 files changed, 502 insertions(+), 7 deletions(-) create mode 100644 crates/ourios-server/src/config/file.rs diff --git a/Cargo.lock b/Cargo.lock index 7778eece0..341622c1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3165,6 +3165,7 @@ dependencies = [ "prost", "serde", "serde_json", + "serde_yaml", "tempfile", "testcontainers-modules", "tokio", diff --git a/crates/ourios-server/Cargo.toml b/crates/ourios-server/Cargo.toml index da9721286..fdc608fcf 100644 --- a/crates/ourios-server/Cargo.toml +++ b/crates/ourios-server/Cargo.toml @@ -48,6 +48,11 @@ ourios-querier = { path = "../ourios-querier" } # `parse_structured_statement`. serde = { version = "1", default-features = false, features = ["std", "derive"] } serde_json = { version = "1", default-features = false, features = ["std"] } +# RFC 0020 configuration-file schema (config::file): parse the YAML into a node +# tree, substitute `${env:…}` in scalar values, then deserialise the schema. +# Already vetted in the dep tree (ourios-querier pins the same version), so this +# adds no new cargo-deny surface. +serde_yaml = { version = "=0.9.34", default-features = false } # `LogsServiceServer` to host the receiver's `LogsService` impl over gRPC. opentelemetry-proto = { version = "0.32", default-features = false, features = ["gen-tonic", "logs"] } # gRPC transport (server) for the OTLP/gRPC listener (RFC0003.16). diff --git a/crates/ourios-server/src/config.rs b/crates/ourios-server/src/config.rs index 55c7c9bfe..cf2741026 100644 --- a/crates/ourios-server/src/config.rs +++ b/crates/ourios-server/src/config.rs @@ -1,12 +1,16 @@ //! Configuration for `ourios-server` (RFC 0020). //! //! The config file (`--config `) maps onto the resolved server config the -//! binary builds; this module holds the file-loading pieces. Today that is the -//! environment-variable substitution resolver ([`env_subst`]); the YAML schema, -//! `--config` wiring, and validation land in subsequent RFC 0020 green slices. +//! binary builds; this module holds the file-loading pieces: the +//! environment-variable substitution resolver ([`env_subst`]) and the YAML +//! schema plus its substitution walk ([`file`]). The `--config` CLI wiring and +//! the mapping onto the resolved `ServerConfig` (through the existing `build_*` +//! validators — the single validation path) land in a subsequent RFC 0020 green +//! slice. //! //! The standard `OTEL_*` SDK environment is deliberately **not** handled here — //! it configures the server's own telemetry SDK and is read by the SDK directly //! (RFC 0020 §3.8). See `docs/rfcs/0020-configuration-file.md`. pub mod env_subst; +pub mod file; diff --git a/crates/ourios-server/src/config/file.rs b/crates/ourios-server/src/config/file.rs new file mode 100644 index 000000000..7a2ce9ca4 --- /dev/null +++ b/crates/ourios-server/src/config/file.rs @@ -0,0 +1,451 @@ +//! The RFC 0020 YAML configuration schema and its environment-substitution walk. +//! +//! [`parse`] turns config-file text into a [`FileConfig`]: it parses the YAML +//! into a node tree, substitutes `${env:…}` references in the scalar **values** +//! ([`env_subst`](super::env_subst)), then deserialises the substituted tree +//! into the schema. Mapping onto the resolved server config (via the existing +//! `build_*` validators — the single validation path, RFC 0020 §3.1) is the +//! `--config` wiring layer in the binary; this module stops at a validated, +//! substituted view of the file. +//! +//! **Substitution operates on parsed scalar values, never raw text** (RFC 0020 +//! §3.3): the walk descends the node tree and rewrites only scalar *values*, so +//! mapping keys are left verbatim (rule 4) and a substituted value is inserted +//! as-is and never re-parsed into YAML structure (rule 5 — the security +//! boundary). It is not recursive: [`env_subst::resolve`](super::env_subst::resolve) +//! emits the resolved value without re-scanning it. +//! +//! **Type after substitution** (rule 7) is resolved at the typed boundary rather +//! than by re-tagging the node tree. `serde_yaml`'s `Value` does not preserve a +//! scalar's quoting style, so a literal "re-interpret the substituted scalar by +//! YAML's type rules" pass cannot tell a quoted string from a bare one and would +//! wrongly coerce `"01"` to an integer. Instead every leaf is carried as its +//! string form (a bare `3600` and a substituted `${env:W}`→`3600` both become +//! the string `"3600"`) and the final type is resolved when that string flows +//! through the existing `build_*` validators — the same path the environment +//! values take (§3.1). The observable result is identical for the bounded +//! schema, and a quoted scalar can never be corrupted into a number. +//! +//! See `docs/rfcs/0020-configuration-file.md` §3.3–§3.4. + +use std::fmt; + +use serde::Deserialize; +use serde_yaml::Value; + +use super::env_subst::{self, MalformedReference}; + +/// A failure loading a configuration file. +/// +/// Both variants name only structural locators — a YAML key path or a +/// non-conforming `${…}` reference — never a resolved value, so the error is +/// safe to surface even when a sibling scalar holds a secret (RFC 0020 §3.5 / +/// RFC 0019 §3.4). +#[derive(Debug)] +pub enum FileConfigError { + /// A `${…}` reference that does not conform to the substitution grammar. + Substitution(MalformedReference), + /// A YAML syntax error, an unknown key (`deny_unknown_fields`), or a value + /// whose shape does not match the schema. + Schema(serde_yaml::Error), +} + +impl fmt::Display for FileConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Substitution(e) => write!(f, "configuration file: {e}"), + Self::Schema(e) => write!(f, "configuration file: {e}"), + } + } +} + +impl std::error::Error for FileConfigError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Substitution(e) => Some(e), + Self::Schema(e) => Some(e), + } + } +} + +/// The parsed, substituted configuration file (RFC 0020 §3.4). +/// +/// Every leaf is an already-substituted scalar in string form; the binary maps +/// these onto the resolved `ServerConfig` through the existing `build_*` +/// validators (RFC 0020 §3.1). Absent sections and fields are the type default +/// (`None` / an empty section), matching an unset environment variable. +#[derive(Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct FileConfig { + /// Data + audit store backend (`storage.*`, RFC 0019). + pub storage: StorageSection, + /// OTLP receiver role (`receiver.*`, RFC 0003). + pub receiver: ReceiverSection, + /// Query role (`querier.*`, RFC 0016). + pub querier: QuerierSection, + /// Background compaction (`compaction.*`, RFC 0009). + pub compaction: CompactionSection, +} + +/// `storage.*` — the data + audit store backend selection (RFC 0019 §3.1/§3.2). +#[derive(Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct StorageSection { + /// `local` (default) or `s3`. + #[serde(deserialize_with = "scalar_opt")] + pub backend: Option, + /// S3 addressing + credentials (`storage.s3.*`). + pub s3: S3Section, + /// Local-backend store root (`storage.local.*`). + pub local: LocalSection, +} + +/// `storage.s3.*` — S3 addressing and (env-only) credentials (RFC 0019 §3.4). +#[derive(Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct S3Section { + #[serde(deserialize_with = "scalar_opt")] + pub bucket: Option, + #[serde(deserialize_with = "scalar_opt")] + pub endpoint: Option, + #[serde(deserialize_with = "scalar_opt")] + pub region: Option, + #[serde(deserialize_with = "scalar_opt")] + pub prefix: Option, + #[serde(deserialize_with = "scalar_opt")] + pub access_key_id: Option, + #[serde(deserialize_with = "scalar_opt")] + pub secret_access_key: Option, + #[serde(deserialize_with = "scalar_opt")] + pub session_token: Option, +} + +/// `storage.local.*` — the local store root (RFC 0019 §3.1). +#[derive(Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct LocalSection { + #[serde(deserialize_with = "scalar_opt")] + pub bucket_root: Option, +} + +/// `receiver.*` — the OTLP receiver role (RFC 0003 §6.2). +#[derive(Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ReceiverSection { + #[serde(deserialize_with = "scalar_opt")] + pub enabled: Option, + #[serde(deserialize_with = "scalar_opt")] + pub grpc_addr: Option, + #[serde(deserialize_with = "scalar_opt")] + pub http_addr: Option, + #[serde(deserialize_with = "scalar_opt")] + pub wal_root: Option, +} + +/// `querier.*` — the query role (RFC 0016 §3.2). +#[derive(Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct QuerierSection { + #[serde(deserialize_with = "scalar_opt")] + pub enabled: Option, + #[serde(deserialize_with = "scalar_opt")] + pub http_addr: Option, + #[serde(deserialize_with = "scalar_opt")] + pub default_window_secs: Option, +} + +/// `compaction.*` — the background compaction sweep (RFC 0009 §3.2). +#[derive(Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct CompactionSection { + #[serde(deserialize_with = "scalar_opt")] + pub enabled: Option, + #[serde(deserialize_with = "scalar_opt")] + pub interval_secs: Option, +} + +/// Parse configuration-file text into a validated, substituted [`FileConfig`]. +/// +/// `lookup` resolves an environment-variable name for `${env:…}` substitution +/// (`None` when unset); the binary passes `|n| std::env::var(n).ok()`. The file +/// is parsed into a node tree, scalar values are substituted, and the result is +/// deserialised into the schema — a strict pass (unknown keys are rejected, +/// RFC 0020 §3.4). +/// +/// # Errors +/// +/// Returns [`FileConfigError::Substitution`] for a malformed `${…}` reference in +/// a scalar value (RFC0020.5), or [`FileConfigError::Schema`] for a YAML syntax +/// error, an unknown key, or a value that does not fit the schema. Resolution is +/// all-or-nothing: on error no partial configuration is produced. +pub fn parse( + yaml: &str, + lookup: &dyn Fn(&str) -> Option, +) -> Result { + let mut tree: Value = serde_yaml::from_str(yaml).map_err(FileConfigError::Schema)?; + // An empty document parses to `Null`; treat it as an all-default config + // rather than a type error (deserialising `Null` into a struct fails). + if tree.is_null() { + return Ok(FileConfig::default()); + } + substitute_tree(&mut tree, lookup).map_err(FileConfigError::Substitution)?; + serde_yaml::from_value(tree).map_err(FileConfigError::Schema) +} + +/// Substitute `${env:…}` references in every scalar **value** of the tree. +/// +/// Mapping keys are never visited (rule 4 — a `${…}` in a key position is left +/// verbatim), and a substituted value is a `String` that is never re-parsed into +/// YAML structure (rule 5). Non-string scalars (`Number`/`Bool`/`Null`) hold no +/// `$` and are left untouched. +fn substitute_tree( + value: &mut Value, + lookup: &dyn Fn(&str) -> Option, +) -> Result<(), MalformedReference> { + match value { + Value::String(s) => { + *s = env_subst::resolve(s, lookup)?; + } + Value::Mapping(map) => { + for (_key, val) in map.iter_mut() { + substitute_tree(val, lookup)?; + } + } + Value::Sequence(seq) => { + for val in seq { + substitute_tree(val, lookup)?; + } + } + Value::Tagged(tagged) => substitute_tree(&mut tagged.value, lookup)?, + Value::Null | Value::Bool(_) | Value::Number(_) => {} + } + Ok(()) +} + +/// Deserialise an optional YAML scalar into its string form. +/// +/// A scalar of any type (string, boolean, number) is rendered as text so a bare +/// `interval_secs: 300` and a substituted `${env:I}` both reach the `build_*` +/// validators as `"300"` (the type-after-substitution model, RFC 0020 §3.3 +/// rule 7 — see the module docs). A mapping or sequence where a scalar is +/// expected is a schema error. +fn scalar_opt<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + Ok(Option::::deserialize(deserializer)?.map(|s| s.0)) +} + +/// A YAML scalar captured as its string form (see [`scalar_opt`]). +struct Scalar(String); + +impl<'de> Deserialize<'de> for Scalar { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + struct ScalarVisitor; + + impl serde::de::Visitor<'_> for ScalarVisitor { + type Value = Scalar; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a scalar value (string, boolean, or number)") + } + + fn visit_str(self, v: &str) -> Result { + Ok(Scalar(v.to_owned())) + } + + fn visit_string(self, v: String) -> Result { + Ok(Scalar(v)) + } + + fn visit_bool(self, v: bool) -> Result { + Ok(Scalar(v.to_string())) + } + + fn visit_i64(self, v: i64) -> Result { + Ok(Scalar(v.to_string())) + } + + fn visit_u64(self, v: u64) -> Result { + Ok(Scalar(v.to_string())) + } + + fn visit_f64(self, v: f64) -> Result { + Ok(Scalar(v.to_string())) + } + } + + deserializer.deserialize_any(ScalarVisitor) + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use super::{FileConfigError, parse, substitute_tree}; + use serde_yaml::Value; + + /// A lookup over a fixed environment map. + fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let map: HashMap = pairs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(); + move |name: &str| map.get(name).cloned() + } + + /// RFC0020.2 — `${env:NAME}`/`${NAME}` in scalar values resolve; `:-default` + /// applies on unset/empty; an undefined ref with no default becomes empty; + /// `$$` is a literal `$`. Type-after-substitution is exercised where a + /// numeric field carries a reference (`default_window_secs`). + #[test] + fn scalar_values_are_substituted() { + let lookup = env(&[ + ("BUCKET", "logs"), + ("REGION", "eu-west-1"), + ("WINDOW", "1800"), + ]); + let yaml = " +storage: + backend: ${env:BACKEND:-s3} + s3: + bucket: ${BUCKET} + region: ${env:REGION} + endpoint: ${env:MISSING:-} + prefix: a$$b +querier: + enabled: ${env:QUERIER_ON:-true} + default_window_secs: ${env:WINDOW} +"; + let cfg = parse(yaml, &lookup).expect("valid"); + assert_eq!(cfg.storage.backend.as_deref(), Some("s3")); // default applied + assert_eq!(cfg.storage.s3.bucket.as_deref(), Some("logs")); + assert_eq!(cfg.storage.s3.region.as_deref(), Some("eu-west-1")); + assert_eq!(cfg.storage.s3.endpoint.as_deref(), Some("")); // undefined, no default → empty + assert_eq!(cfg.storage.s3.prefix.as_deref(), Some("a$b")); // $$ → literal $ + assert_eq!(cfg.querier.enabled.as_deref(), Some("true")); + assert_eq!(cfg.querier.default_window_secs.as_deref(), Some("1800")); + } + + /// RFC0020.2 — native YAML scalars (a bare integer / boolean, no reference) + /// reach the schema as their string form, so a literal and a substituted + /// value are indistinguishable downstream (type-after-substitution). + #[test] + fn native_scalars_become_their_string_form() { + let lookup = env(&[]); + let yaml = " +querier: + enabled: true + default_window_secs: 3600 +compaction: + interval_secs: 300 +"; + let cfg = parse(yaml, &lookup).expect("valid"); + assert_eq!(cfg.querier.enabled.as_deref(), Some("true")); + assert_eq!(cfg.querier.default_window_secs.as_deref(), Some("3600")); + assert_eq!(cfg.compaction.interval_secs.as_deref(), Some("300")); + } + + /// RFC0020.2 rule 4 — substitution never touches a mapping **key**; a + /// `${…}` in key position is left verbatim (asserted at the tree level, as + /// the typed schema has no free-form-key field to carry one). + #[test] + fn mapping_keys_are_left_verbatim() { + let lookup = env(&[("K", "resolved"), ("V", "resolved")]); + let mut tree: Value = serde_yaml::from_str("${env:K}: ${env:V}").expect("yaml"); + substitute_tree(&mut tree, &lookup).expect("ok"); + let map = tree.as_mapping().expect("a mapping"); + let (key, value) = map.iter().next().expect("one entry"); + assert_eq!(key.as_str(), Some("${env:K}"), "the key is verbatim"); + assert_eq!(value.as_str(), Some("resolved"), "the value is substituted"); + } + + /// RFC0020.2 rule 5 — a substituted value is inserted as-is and never + /// re-parsed into YAML structure: a value that itself looks like a mapping + /// stays a single scalar string, injecting no keys. + #[test] + fn substituted_values_do_not_inject_structure() { + let lookup = env(&[("INJECT", "evil: true\nkey: value")]); + let cfg = parse("storage:\n backend: ${env:INJECT}\n", &lookup).expect("valid"); + assert_eq!( + cfg.storage.backend.as_deref(), + Some("evil: true\nkey: value"), + "the value is a scalar string, not a parsed mapping", + ); + } + + /// RFC0020.5 (partial) — a malformed `${…}` reference in a scalar value is a + /// whole-file error naming the reference, never a resolved value. + #[test] + fn malformed_reference_is_an_error() { + let lookup = env(&[]); + let err = parse("storage:\n backend: ${1BAD}\n", &lookup).expect_err("malformed"); + assert!( + matches!(err, FileConfigError::Substitution(_)), + "got {err:?}", + ); + assert!(err.to_string().contains("${1BAD}"), "names the reference"); + } + + /// RFC0020.5 (partial) — an unknown key is a schema error (strict parse, + /// `deny_unknown_fields`), naming the offending key. + #[test] + fn unknown_key_is_rejected() { + let lookup = env(&[]); + let err = parse("storage:\n backsend: s3\n", &lookup).expect_err("typo"); + assert!(matches!(err, FileConfigError::Schema(_)), "got {err:?}"); + assert!(err.to_string().contains("backend"), "suggests the schema"); + } + + /// An unknown **top-level** section is likewise rejected. + #[test] + fn unknown_top_level_section_is_rejected() { + let lookup = env(&[]); + let err = parse("queriar:\n enabled: true\n", &lookup).expect_err("typo"); + assert!(matches!(err, FileConfigError::Schema(_)), "got {err:?}"); + } + + /// A structure where a scalar is expected (a mapping under a scalar field) + /// is a schema error, not a silent stringification. + #[test] + fn a_structure_where_a_scalar_is_expected_errors() { + let lookup = env(&[]); + let err = + parse("storage:\n backend:\n nested: true\n", &lookup).expect_err("not a scalar"); + assert!(matches!(err, FileConfigError::Schema(_)), "got {err:?}"); + } + + /// An empty document is an all-default config (every role unset), not an + /// error — the equivalent of an empty environment. + #[test] + fn empty_document_is_all_default() { + let lookup = env(&[]); + let cfg = parse("", &lookup).expect("empty is valid"); + assert!(cfg.storage.backend.is_none()); + assert!(cfg.receiver.enabled.is_none()); + assert!(cfg.querier.enabled.is_none()); + assert!(cfg.compaction.enabled.is_none()); + } + + /// An omitted section leaves its fields unset (`None`), matching an unset + /// environment variable — the schema does not require every section. + #[test] + fn omitted_sections_default_to_unset() { + let lookup = env(&[("ROOT", "/var/lib/ourios")]); + let cfg = parse( + "storage:\n local:\n bucket_root: ${env:ROOT}\n", + &lookup, + ) + .expect("valid"); + assert_eq!( + cfg.storage.local.bucket_root.as_deref(), + Some("/var/lib/ourios") + ); + assert!(cfg.receiver.enabled.is_none()); + assert!(cfg.querier.enabled.is_none()); + } +} diff --git a/crates/ourios-server/tests/rfc0020_config_file.rs b/crates/ourios-server/tests/rfc0020_config_file.rs index afb06de84..28871a9ce 100644 --- a/crates/ourios-server/tests/rfc0020_config_file.rs +++ b/crates/ourios-server/tests/rfc0020_config_file.rs @@ -24,12 +24,46 @@ fn rfc0020_1_complete_file_resolves_to_expected_server_config() { /// Scenario RFC0020.2 — environment substitution follows the `OTel` Config WG model. /// See `docs/rfcs/0020-configuration-file.md` §5. +/// +/// Green: the resolver conformance vectors live in +/// `ourios_server::config::env_subst` (the WG input→output table + escape / +/// non-recursion invariants + proptest), and the scalar-value walk that applies +/// them to a parsed file — scalar-only (mapping keys verbatim), non-recursive +/// (no injected YAML structure), `$$` escaping, type-after-substitution — lives +/// in `ourios_server::config::file`. This end-to-end check pins the two together +/// through the public `parse` entry point. #[test] -#[ignore = "RFC0020.2 stub — implemented in the green slice"] fn rfc0020_2_env_substitution_follows_the_otel_config_wg_model() { - todo!( - "RFC0020.2 — ${{env:NAME}}/${{NAME}}, :-default, $$ escape; scalar-only, non-recursive; the WG vector table" - ); + let lookup = |name: &str| match name { + "BUCKET" => Some("logs".to_owned()), + "WINDOW" => Some("1800".to_owned()), + _ => None, + }; + let yaml = "\ +storage: + backend: ${env:BACKEND:-s3} + s3: + bucket: ${BUCKET} + endpoint: ${env:MISSING:-} + prefix: a$$b +querier: + enabled: ${QUERIER_ON:-true} + default_window_secs: ${env:WINDOW} +"; + let cfg = ourios_server::config::file::parse(yaml, &lookup).expect("valid file"); + + assert_eq!(cfg.storage.backend.as_deref(), Some("s3")); // :-default on unset + assert_eq!(cfg.storage.s3.bucket.as_deref(), Some("logs")); // ${env:} / ${} + assert_eq!(cfg.storage.s3.endpoint.as_deref(), Some("")); // undefined, no default + assert_eq!(cfg.storage.s3.prefix.as_deref(), Some("a$b")); // $$ → literal $ + assert_eq!(cfg.querier.enabled.as_deref(), Some("true")); + assert_eq!(cfg.querier.default_window_secs.as_deref(), Some("1800")); + + // A malformed reference in a scalar value fails the whole file (no partial + // resolution), naming the reference and not any resolved value. + let err = ourios_server::config::file::parse("storage:\n backend: ${1BAD}\n", &lookup) + .expect_err("malformed reference"); + assert!(err.to_string().contains("${1BAD}")); } /// Scenario RFC0020.3 — file is authoritative; a bare env var does not override. From 9af81e1fe482988ff7c432e34567fedfd774a604 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Wed, 1 Jul 2026 19:42:30 +0200 Subject: [PATCH 2/4] fix(server): disambiguate rustdoc `file` link + drop redundant explicit targets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cargo doc -D rustdoc::broken-intra-doc-links` failed: `[`file`]` is ambiguous (`file` module vs the `file!` macro). Disambiguate with `mod@file`. Also drop the now-redundant explicit `(super::env_subst…)` targets on the two `env_subst` links (the `use super::env_subst` import already resolves the bare labels), which were emitting `rustdoc::redundant_explicit_links` warnings. Verified: `RUSTDOCFLAGS="-D rustdoc::broken-intra-doc-links" cargo doc --workspace --no-deps --all-features` clean. Co-Authored-By: Claude Opus 4.8 (1M context) --- crates/ourios-server/src/config.rs | 2 +- crates/ourios-server/src/config/file.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ourios-server/src/config.rs b/crates/ourios-server/src/config.rs index cf2741026..a5dd6d416 100644 --- a/crates/ourios-server/src/config.rs +++ b/crates/ourios-server/src/config.rs @@ -3,7 +3,7 @@ //! The config file (`--config `) maps onto the resolved server config the //! binary builds; this module holds the file-loading pieces: the //! environment-variable substitution resolver ([`env_subst`]) and the YAML -//! schema plus its substitution walk ([`file`]). The `--config` CLI wiring and +//! schema plus its substitution walk ([`file`](mod@file)). The `--config` CLI wiring and //! the mapping onto the resolved `ServerConfig` (through the existing `build_*` //! validators — the single validation path) land in a subsequent RFC 0020 green //! slice. diff --git a/crates/ourios-server/src/config/file.rs b/crates/ourios-server/src/config/file.rs index 7a2ce9ca4..6aff10779 100644 --- a/crates/ourios-server/src/config/file.rs +++ b/crates/ourios-server/src/config/file.rs @@ -2,7 +2,7 @@ //! //! [`parse`] turns config-file text into a [`FileConfig`]: it parses the YAML //! into a node tree, substitutes `${env:…}` references in the scalar **values** -//! ([`env_subst`](super::env_subst)), then deserialises the substituted tree +//! ([`env_subst`]), then deserialises the substituted tree //! into the schema. Mapping onto the resolved server config (via the existing //! `build_*` validators — the single validation path, RFC 0020 §3.1) is the //! `--config` wiring layer in the binary; this module stops at a validated, @@ -12,8 +12,8 @@ //! §3.3): the walk descends the node tree and rewrites only scalar *values*, so //! mapping keys are left verbatim (rule 4) and a substituted value is inserted //! as-is and never re-parsed into YAML structure (rule 5 — the security -//! boundary). It is not recursive: [`env_subst::resolve`](super::env_subst::resolve) -//! emits the resolved value without re-scanning it. +//! boundary). It is not recursive: [`env_subst::resolve`] emits the resolved +//! value without re-scanning it. //! //! **Type after substitution** (rule 7) is resolved at the typed boundary rather //! than by re-tagging the node tree. `serde_yaml`'s `Value` does not preserve a From 1acc8fcaadcc8aa2a3cf619d8545b56c23f1f803 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Wed, 1 Jul 2026 19:55:49 +0200 Subject: [PATCH 3/4] =?UTF-8?q?fix(server):=20rfc0020=20review=20=E2=80=94?= =?UTF-8?q?=20schema-error=20secret=20leak,=20redact=20creds,=20hygiene?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address the CodeRabbit + Copilot review of #325: - **Schema errors could echo a resolved secret (CodeRabbit).** `from_value` ran *after* substitution, so `storage: ${env:SECRET}` (a scalar where a section is expected) produced `invalid type: string "", expected struct`. Fix by construction: validate the schema on the **raw** (pre-substitution) tree, then substitute the typed scalar leaves in place. `serde` never sees a substituted value, so a shape / unknown-key error names the file's own text (`${env:SECRET}` — the reference, not the value). Replaces the `Value`-tree `substitute_tree` walk with per-section `substitute` methods over the `Option` leaves; the scalar-only / non-recursive / no-structure-injection guarantees now hold structurally (keys are field names). Regression test asserts the error omits the resolved value and names the reference. - **`S3Section` derived `Debug` over credentials (Copilot).** Add a manual redacting `Debug` impl (presence only), mirroring `ourios_parquet::S3Config`; regression test asserts the access key / secret never render. - **`FileConfigError` → `#[non_exhaustive]` (Copilot)** — matches the public error-enum convention (`ourios_miner::tokenize::TokenizeError`); keeps adding the `--config` slice's I/O / validation variants non-breaking. - **Test comment accuracy (Copilot).** `${env:MISSING:-}` exercised the empty `:-default` path, not "undefined, no default"; switch to `${env:MISSING}` in both the unit and integration tests so the assertion matches its comment and covers the no-default branch. Verified: `cargo fmt --all --check`, `cargo clippy -p ourios-server --all-targets --all-features -D warnings`, `cargo test -p ourios-server --all-features`, `RUSTDOCFLAGS="-D rustdoc::broken-intra-doc-links" cargo doc`. Co-Authored-By: Claude Opus 4.8 (1M context) --- crates/ourios-server/src/config/file.rs | 278 +++++++++++++----- .../tests/rfc0020_config_file.rs | 2 +- 2 files changed, 213 insertions(+), 67 deletions(-) diff --git a/crates/ourios-server/src/config/file.rs b/crates/ourios-server/src/config/file.rs index 6aff10779..c51c3d94a 100644 --- a/crates/ourios-server/src/config/file.rs +++ b/crates/ourios-server/src/config/file.rs @@ -1,25 +1,29 @@ -//! The RFC 0020 YAML configuration schema and its environment-substitution walk. +//! The RFC 0020 YAML configuration schema and its environment substitution. //! -//! [`parse`] turns config-file text into a [`FileConfig`]: it parses the YAML -//! into a node tree, substitutes `${env:…}` references in the scalar **values** -//! ([`env_subst`]), then deserialises the substituted tree -//! into the schema. Mapping onto the resolved server config (via the existing -//! `build_*` validators — the single validation path, RFC 0020 §3.1) is the -//! `--config` wiring layer in the binary; this module stops at a validated, +//! [`parse`] turns config-file text into a [`FileConfig`]: it deserialises the +//! YAML into the schema, then substitutes `${env:…}` references in the scalar +//! **values** ([`env_subst`]). Mapping onto the resolved server config (via the +//! existing `build_*` validators — the single validation path, RFC 0020 §3.1) is +//! the `--config` wiring layer in the binary; this module stops at a validated, //! substituted view of the file. //! -//! **Substitution operates on parsed scalar values, never raw text** (RFC 0020 -//! §3.3): the walk descends the node tree and rewrites only scalar *values*, so -//! mapping keys are left verbatim (rule 4) and a substituted value is inserted -//! as-is and never re-parsed into YAML structure (rule 5 — the security -//! boundary). It is not recursive: [`env_subst::resolve`] emits the resolved -//! value without re-scanning it. +//! **Order: validate the schema, then substitute.** Deserialisation runs on the +//! *raw* (pre-substitution) tree, so a shape or unknown-key error references the +//! file's own text — a bare `${env:SECRET}` written where a section is expected +//! is reported as `invalid type: string "${env:SECRET}", …`, naming the +//! reference, never a resolved secret (RFC 0020 §3.5 / RFC 0019 §3.4). `serde` +//! never sees a substituted value. Substitution then rewrites the typed scalar +//! leaves in place — the parsed *values* only, so mapping keys (which became +//! field names) are never candidates (rule 4), and a substituted value stays in +//! its `Option` field, never re-parsed into YAML structure (rule 5, the +//! security boundary). It is not recursive: [`env_subst::resolve`] emits the +//! resolved value without re-scanning it. //! //! **Type after substitution** (rule 7) is resolved at the typed boundary rather -//! than by re-tagging the node tree. `serde_yaml`'s `Value` does not preserve a +//! than by re-tagging a node tree. `serde_yaml`'s `Value` does not preserve a //! scalar's quoting style, so a literal "re-interpret the substituted scalar by //! YAML's type rules" pass cannot tell a quoted string from a bare one and would -//! wrongly coerce `"01"` to an integer. Instead every leaf is carried as its +//! wrongly coerce `"01"` to an integer. Instead every leaf is captured as its //! string form (a bare `3600` and a substituted `${env:W}`→`3600` both become //! the string `"3600"`) and the final type is resolved when that string flows //! through the existing `build_*` validators — the same path the environment @@ -35,13 +39,30 @@ use serde_yaml::Value; use super::env_subst::{self, MalformedReference}; +/// Substitute `${env:…}` in one optional scalar leaf in place (RFC 0020 §3.3). +fn substitute( + field: &mut Option, + lookup: &dyn Fn(&str) -> Option, +) -> Result<(), MalformedReference> { + if let Some(value) = field { + *value = env_subst::resolve(value, lookup)?; + } + Ok(()) +} + /// A failure loading a configuration file. /// /// Both variants name only structural locators — a YAML key path or a /// non-conforming `${…}` reference — never a resolved value, so the error is /// safe to surface even when a sibling scalar holds a secret (RFC 0020 §3.5 / /// RFC 0019 §3.4). +/// +/// `#[non_exhaustive]` — the `--config` wiring slice adds file-I/O and +/// value-validation variants; forcing a wildcard arm keeps that non-breaking +/// for downstream matches (the codebase's public-error-enum convention, e.g. +/// `ourios_miner::tokenize::TokenizeError`). #[derive(Debug)] +#[non_exhaustive] pub enum FileConfigError { /// A `${…}` reference that does not conform to the substitution grammar. Substitution(MalformedReference), @@ -101,7 +122,11 @@ pub struct StorageSection { } /// `storage.s3.*` — S3 addressing and (env-only) credentials (RFC 0019 §3.4). -#[derive(Debug, Default, Deserialize)] +/// +/// The credential fields are **secret**: the manual [`fmt::Debug`] impl redacts +/// their values (showing only presence), mirroring `ourios_parquet::S3Config` so +/// a `Debug` rendering never leaks a key (RFC 0020 §3.5 / RFC 0019 §3.4). +#[derive(Default, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct S3Section { #[serde(deserialize_with = "scalar_opt")] @@ -120,6 +145,23 @@ pub struct S3Section { pub session_token: Option, } +impl fmt::Debug for S3Section { + /// Redacts the credential fields — a `Debug` rendering shows only whether a + /// credential is present, never its value (RFC 0020 §3.5 / RFC 0019 §3.4). + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let redact = |v: &Option| v.as_ref().map(|_| ""); + f.debug_struct("S3Section") + .field("bucket", &self.bucket) + .field("endpoint", &self.endpoint) + .field("region", &self.region) + .field("prefix", &self.prefix) + .field("access_key_id", &redact(&self.access_key_id)) + .field("secret_access_key", &redact(&self.secret_access_key)) + .field("session_token", &redact(&self.session_token)) + .finish() + } +} + /// `storage.local.*` — the local store root (RFC 0019 §3.1). #[derive(Debug, Default, Deserialize)] #[serde(default, deny_unknown_fields)] @@ -168,58 +210,115 @@ pub struct CompactionSection { /// /// `lookup` resolves an environment-variable name for `${env:…}` substitution /// (`None` when unset); the binary passes `|n| std::env::var(n).ok()`. The file -/// is parsed into a node tree, scalar values are substituted, and the result is -/// deserialised into the schema — a strict pass (unknown keys are rejected, -/// RFC 0020 §3.4). +/// is deserialised into the schema — a strict pass (unknown keys are rejected, +/// RFC 0020 §3.4) — on the **raw** tree, so a schema error references the file's +/// own text rather than a resolved value; substitution then runs on the typed +/// scalar leaves (see the module docs). /// /// # Errors /// -/// Returns [`FileConfigError::Substitution`] for a malformed `${…}` reference in -/// a scalar value (RFC0020.5), or [`FileConfigError::Schema`] for a YAML syntax -/// error, an unknown key, or a value that does not fit the schema. Resolution is +/// Returns [`FileConfigError::Schema`] for a YAML syntax error, an unknown key, +/// or a value that does not fit the schema, or [`FileConfigError::Substitution`] +/// for a malformed `${…}` reference in a scalar value (RFC0020.5). Resolution is /// all-or-nothing: on error no partial configuration is produced. pub fn parse( yaml: &str, lookup: &dyn Fn(&str) -> Option, ) -> Result { - let mut tree: Value = serde_yaml::from_str(yaml).map_err(FileConfigError::Schema)?; + let tree: Value = serde_yaml::from_str(yaml).map_err(FileConfigError::Schema)?; // An empty document parses to `Null`; treat it as an all-default config // rather than a type error (deserialising `Null` into a struct fails). if tree.is_null() { return Ok(FileConfig::default()); } - substitute_tree(&mut tree, lookup).map_err(FileConfigError::Substitution)?; - serde_yaml::from_value(tree).map_err(FileConfigError::Schema) + // Validate on the raw (pre-substitution) tree: any shape / unknown-key error + // then names the file's own text, never a resolved secret (RFC 0020 §3.5). + let mut config: FileConfig = serde_yaml::from_value(tree).map_err(FileConfigError::Schema)?; + config + .substitute(lookup) + .map_err(FileConfigError::Substitution)?; + Ok(config) } -/// Substitute `${env:…}` references in every scalar **value** of the tree. -/// -/// Mapping keys are never visited (rule 4 — a `${…}` in a key position is left -/// verbatim), and a substituted value is a `String` that is never re-parsed into -/// YAML structure (rule 5). Non-string scalars (`Number`/`Bool`/`Null`) hold no -/// `$` and are left untouched. -fn substitute_tree( - value: &mut Value, - lookup: &dyn Fn(&str) -> Option, -) -> Result<(), MalformedReference> { - match value { - Value::String(s) => { - *s = env_subst::resolve(s, lookup)?; - } - Value::Mapping(map) => { - for (_key, val) in map.iter_mut() { - substitute_tree(val, lookup)?; - } - } - Value::Sequence(seq) => { - for val in seq { - substitute_tree(val, lookup)?; - } - } - Value::Tagged(tagged) => substitute_tree(&mut tagged.value, lookup)?, - Value::Null | Value::Bool(_) | Value::Number(_) => {} +impl FileConfig { + /// Substitute `${env:…}` in every scalar leaf (RFC 0020 §3.3), in place. + fn substitute( + &mut self, + lookup: &dyn Fn(&str) -> Option, + ) -> Result<(), MalformedReference> { + self.storage.substitute(lookup)?; + self.receiver.substitute(lookup)?; + self.querier.substitute(lookup)?; + self.compaction.substitute(lookup) + } +} + +impl StorageSection { + fn substitute( + &mut self, + lookup: &dyn Fn(&str) -> Option, + ) -> Result<(), MalformedReference> { + substitute(&mut self.backend, lookup)?; + self.s3.substitute(lookup)?; + self.local.substitute(lookup) + } +} + +impl S3Section { + fn substitute( + &mut self, + lookup: &dyn Fn(&str) -> Option, + ) -> Result<(), MalformedReference> { + substitute(&mut self.bucket, lookup)?; + substitute(&mut self.endpoint, lookup)?; + substitute(&mut self.region, lookup)?; + substitute(&mut self.prefix, lookup)?; + substitute(&mut self.access_key_id, lookup)?; + substitute(&mut self.secret_access_key, lookup)?; + substitute(&mut self.session_token, lookup) + } +} + +impl LocalSection { + fn substitute( + &mut self, + lookup: &dyn Fn(&str) -> Option, + ) -> Result<(), MalformedReference> { + substitute(&mut self.bucket_root, lookup) + } +} + +impl ReceiverSection { + fn substitute( + &mut self, + lookup: &dyn Fn(&str) -> Option, + ) -> Result<(), MalformedReference> { + substitute(&mut self.enabled, lookup)?; + substitute(&mut self.grpc_addr, lookup)?; + substitute(&mut self.http_addr, lookup)?; + substitute(&mut self.wal_root, lookup) + } +} + +impl QuerierSection { + fn substitute( + &mut self, + lookup: &dyn Fn(&str) -> Option, + ) -> Result<(), MalformedReference> { + substitute(&mut self.enabled, lookup)?; + substitute(&mut self.http_addr, lookup)?; + substitute(&mut self.default_window_secs, lookup) + } +} + +impl CompactionSection { + fn substitute( + &mut self, + lookup: &dyn Fn(&str) -> Option, + ) -> Result<(), MalformedReference> { + substitute(&mut self.enabled, lookup)?; + substitute(&mut self.interval_secs, lookup) } - Ok(()) } /// Deserialise an optional YAML scalar into its string form. @@ -286,8 +385,7 @@ impl<'de> Deserialize<'de> for Scalar { mod tests { use std::collections::HashMap; - use super::{FileConfigError, parse, substitute_tree}; - use serde_yaml::Value; + use super::{FileConfigError, parse}; /// A lookup over a fixed environment map. fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { @@ -315,7 +413,7 @@ storage: s3: bucket: ${BUCKET} region: ${env:REGION} - endpoint: ${env:MISSING:-} + endpoint: ${env:MISSING} prefix: a$$b querier: enabled: ${env:QUERIER_ON:-true} @@ -350,18 +448,66 @@ compaction: assert_eq!(cfg.compaction.interval_secs.as_deref(), Some("300")); } - /// RFC0020.2 rule 4 — substitution never touches a mapping **key**; a - /// `${…}` in key position is left verbatim (asserted at the tree level, as - /// the typed schema has no free-form-key field to carry one). + /// RFC0020.2 rule 4 — a `${…}` in a mapping **key** position is never a + /// substitution candidate. `X` resolves to a *valid* section name, so if keys + /// were substituted the file would parse; it must not — keys deserialise as + /// field names and are left verbatim, so the reference-shaped key is rejected + /// as unknown. + #[test] + fn a_reference_in_key_position_is_left_verbatim() { + let lookup = env(&[("X", "storage")]); + let err = parse("${env:X}:\n backend: s3\n", &lookup).expect_err("verbatim key"); + assert!(matches!(err, FileConfigError::Schema(_)), "got {err:?}"); + } + + /// RFC0020.6 (schema-error hygiene) — a reference placed where a whole + /// section is expected fails on the **raw** tree, so the error names the + /// reference text, never the resolved secret value (RFC 0020 §3.5): `serde` + /// never sees a substituted value. + #[test] + fn schema_error_never_echoes_a_resolved_value() { + const SECRET: &str = "SUPER-SECRET-TOKEN"; + let lookup = env(&[("SECRET", SECRET)]); + let err = parse("storage: ${env:SECRET}\n", &lookup).expect_err("shape mismatch"); + assert!(matches!(err, FileConfigError::Schema(_)), "got {err:?}"); + let msg = err.to_string(); + assert!( + !msg.contains(SECRET), + "the resolved secret must not leak: {msg}" + ); + assert!( + msg.contains("${env:SECRET}"), + "names the reference instead: {msg}", + ); + } + + /// The S3 credential fields are redacted in `Debug` — presence only, never + /// the value (RFC 0020 §3.5 / RFC 0019 §3.4), mirroring `S3Config`. #[test] - fn mapping_keys_are_left_verbatim() { - let lookup = env(&[("K", "resolved"), ("V", "resolved")]); - let mut tree: Value = serde_yaml::from_str("${env:K}: ${env:V}").expect("yaml"); - substitute_tree(&mut tree, &lookup).expect("ok"); - let map = tree.as_mapping().expect("a mapping"); - let (key, value) = map.iter().next().expect("one entry"); - assert_eq!(key.as_str(), Some("${env:K}"), "the key is verbatim"); - assert_eq!(value.as_str(), Some("resolved"), "the value is substituted"); + fn s3_credentials_are_redacted_in_debug() { + let lookup = env(&[("KEY", "AKIAEXAMPLE"), ("SECRET", "s3cr3t-value")]); + let cfg = parse( + "storage:\n s3:\n bucket: b\n access_key_id: ${env:KEY}\n secret_access_key: ${env:SECRET}\n", + &lookup, + ) + .expect("valid"); + let rendered = format!("{:?}", cfg.storage.s3); + assert!( + rendered.contains("bucket"), + "non-secret fields stay visible" + ); + assert!( + !rendered.contains("AKIAEXAMPLE"), + "access key id redacted: {rendered}", + ); + assert!( + !rendered.contains("s3cr3t-value"), + "secret access key redacted: {rendered}", + ); + assert!( + rendered.contains(""), + "shows presence: {rendered}" + ); } /// RFC0020.2 rule 5 — a substituted value is inserted as-is and never diff --git a/crates/ourios-server/tests/rfc0020_config_file.rs b/crates/ourios-server/tests/rfc0020_config_file.rs index 28871a9ce..50997d5bb 100644 --- a/crates/ourios-server/tests/rfc0020_config_file.rs +++ b/crates/ourios-server/tests/rfc0020_config_file.rs @@ -44,7 +44,7 @@ storage: backend: ${env:BACKEND:-s3} s3: bucket: ${BUCKET} - endpoint: ${env:MISSING:-} + endpoint: ${env:MISSING} prefix: a$$b querier: enabled: ${QUERIER_ON:-true} From 07980003e16d86fc11e675a2cdab19189f07bd53 Mon Sep 17 00:00:00 2001 From: Jens Holdgaard Pedersen Date: Wed, 1 Jul 2026 20:05:04 +0200 Subject: [PATCH 4/4] =?UTF-8?q?refactor(server):=20rfc0020=20=E2=80=94=20d?= =?UTF-8?q?eserialize=20config=20from=20text,=20keep=20error=20locations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address Copilot's re-review of #325: - **Preserve source locations on schema errors.** `parse` deserialized via an intermediate `serde_yaml::Value` + `from_value`, which drops line/column from schema/shape/unknown-field errors. Since substitution now runs on the typed scalar leaves (not the node tree), the `Value` intermediate is no longer needed: deserialize straight from the text via `Option` (a null / empty document → `None` → all-default config). Errors keep their location, and validation still runs on the raw pre-substitution text — so it never echoes a resolved secret. Drops the now-unused `serde_yaml::Value` import. - **Fix the stale `serde_yaml` dep comment** — it still described the old substitute-then-deserialize order; corrected to deserialize-then-substitute and noted the order is security-relevant. Verified: `cargo test -p ourios-server --all-features`, `cargo clippy --all-targets --all-features -D warnings`, `cargo fmt --all --check`, `RUSTDOCFLAGS="-D rustdoc::broken-intra-doc-links" cargo doc`. Co-Authored-By: Claude Opus 4.8 (1M context) --- crates/ourios-server/Cargo.toml | 10 ++++++---- crates/ourios-server/src/config/file.rs | 25 ++++++++++++------------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/crates/ourios-server/Cargo.toml b/crates/ourios-server/Cargo.toml index fdc608fcf..1a13a9455 100644 --- a/crates/ourios-server/Cargo.toml +++ b/crates/ourios-server/Cargo.toml @@ -48,10 +48,12 @@ ourios-querier = { path = "../ourios-querier" } # `parse_structured_statement`. serde = { version = "1", default-features = false, features = ["std", "derive"] } serde_json = { version = "1", default-features = false, features = ["std"] } -# RFC 0020 configuration-file schema (config::file): parse the YAML into a node -# tree, substitute `${env:…}` in scalar values, then deserialise the schema. -# Already vetted in the dep tree (ourios-querier pins the same version), so this -# adds no new cargo-deny surface. +# RFC 0020 configuration-file schema (config::file): deserialise the YAML into +# the schema, then substitute `${env:…}` in the typed scalar leaves (schema +# validation runs on the raw text first, so an error never echoes a resolved +# secret — the order is security-relevant, see the module docs). Already vetted +# in the dep tree (ourios-querier pins the same version), so this adds no new +# cargo-deny surface. serde_yaml = { version = "=0.9.34", default-features = false } # `LogsServiceServer` to host the receiver's `LogsService` impl over gRPC. opentelemetry-proto = { version = "0.32", default-features = false, features = ["gen-tonic", "logs"] } diff --git a/crates/ourios-server/src/config/file.rs b/crates/ourios-server/src/config/file.rs index c51c3d94a..7bcb4f51c 100644 --- a/crates/ourios-server/src/config/file.rs +++ b/crates/ourios-server/src/config/file.rs @@ -8,9 +8,9 @@ //! substituted view of the file. //! //! **Order: validate the schema, then substitute.** Deserialisation runs on the -//! *raw* (pre-substitution) tree, so a shape or unknown-key error references the -//! file's own text — a bare `${env:SECRET}` written where a section is expected -//! is reported as `invalid type: string "${env:SECRET}", …`, naming the +//! *raw* (pre-substitution) YAML text, so a shape or unknown-key error references +//! the file's own text — a bare `${env:SECRET}` written where a section is +//! expected is reported as `invalid type: string "${env:SECRET}", …`, naming the //! reference, never a resolved secret (RFC 0020 §3.5 / RFC 0019 §3.4). `serde` //! never sees a substituted value. Substitution then rewrites the typed scalar //! leaves in place — the parsed *values* only, so mapping keys (which became @@ -35,7 +35,6 @@ use std::fmt; use serde::Deserialize; -use serde_yaml::Value; use super::env_subst::{self, MalformedReference}; @@ -225,15 +224,15 @@ pub fn parse( yaml: &str, lookup: &dyn Fn(&str) -> Option, ) -> Result { - let tree: Value = serde_yaml::from_str(yaml).map_err(FileConfigError::Schema)?; - // An empty document parses to `Null`; treat it as an all-default config - // rather than a type error (deserialising `Null` into a struct fails). - if tree.is_null() { - return Ok(FileConfig::default()); - } - // Validate on the raw (pre-substitution) tree: any shape / unknown-key error - // then names the file's own text, never a resolved secret (RFC 0020 §3.5). - let mut config: FileConfig = serde_yaml::from_value(tree).map_err(FileConfigError::Schema)?; + // Deserialise straight from the text (not via an intermediate `serde_yaml:: + // Value`) so a schema error keeps its source location. Validation runs on the + // raw (pre-substitution) text, so any shape / unknown-key error names the + // file's own text, never a resolved secret (RFC 0020 §3.5). `Option` lets an + // empty / null document resolve to an all-default config (`None`) rather than + // fail the `null`-into-struct type check. + let mut config: FileConfig = serde_yaml::from_str::>(yaml) + .map_err(FileConfigError::Schema)? + .unwrap_or_default(); config .substitute(lookup) .map_err(FileConfigError::Substitution)?;