diff --git a/.changeset/settings-store-selection-refusal.md b/.changeset/settings-store-selection-refusal.md new file mode 100644 index 000000000..1c20d1b7b --- /dev/null +++ b/.changeset/settings-store-selection-refusal.md @@ -0,0 +1,18 @@ +--- +--- + +fix(settings): a rejected document no longer swaps the event store + +`nostream_config::load` discards the whole user document on any finding and returns the shipped +defaults, and the daemon's gate continued on them. Because the shipped `eventStore.backend` is +`postgres`, one bad field anywhere in `settings.yaml` made an LMDB deployment serve and write into +the old Postgres store while its data directory sat unused. + +`LoadOutcome` now records the store the discarded document selected +(`discarded_store_selection`), and the gate refuses to start when the substitution would override +it: a different `eventStore.backend`, or a fault at `eventStore` or below, prints one refusal line +naming the path, the value and the backend that would have served, then exits 2 before any store +is opened. `--check` output is byte-identical; a document that names no store, names the backend +that will serve, or cannot be parsed keeps continue-on-defaults. ADR 0022 records the rule, the +fields that are safe to default, and the unparseable-document limitation. Rust only: no published +package changes, so this entry carries no version bump. diff --git a/crates/nostream-config/src/lib.rs b/crates/nostream-config/src/lib.rs index cbe36c9f6..5d9763638 100644 --- a/crates/nostream-config/src/lib.rs +++ b/crates/nostream-config/src/lib.rs @@ -34,7 +34,10 @@ pub mod value; pub use error::ConfigError; pub use issue::Issue; -pub use load::{LoadOutcome, fit, load, load_defaults, load_document, load_user_settings, merge}; +pub use load::{ + DiscardedStoreSelection, LoadOutcome, fit, load, load_defaults, load_document, + load_user_settings, merge, +}; pub use paths::SettingsPaths; pub use settings::Settings; pub use validate::{validate, validate_document}; diff --git a/crates/nostream-config/src/load.rs b/crates/nostream-config/src/load.rs index 28f8c87ff..6be246cf2 100644 --- a/crates/nostream-config/src/load.rs +++ b/crates/nostream-config/src/load.rs @@ -4,6 +4,10 @@ //! The fallback rule is the capture's: a user configuration that cannot be read or does not //! validate never aborts the process. It is reported as [`Issue`] values and the caller gets //! the shipped defaults, so a broken `settings.yaml` cannot stop a relay from starting. +//! +//! `load` itself never refuses. On a rejection it also records what store the discarded +//! document selected ([`LoadOutcome::discarded_store_selection`]), so the daemon's gate can +//! refuse a substitution that would override it (ADR 0022). use std::fs; use std::path::{Path, PathBuf}; @@ -375,6 +379,18 @@ fn find_misfit(schema: &Value, candidate: &Value, path: &mut Vec) -> } } +/// A store selection the rejected user document made, so the daemon can refuse a +/// substitution that would override it (ADR 0022). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DiscardedStoreSelection { + /// The dotted path the document set: `eventStore.backend`, or the refused path at + /// `eventStore` or below it. + pub path: String, + /// The scalar at that path rendered as YAML text; `None` when the value there is not a + /// scalar. + pub value: Option, +} + /// The result of loading the effective settings. #[derive(Debug, Clone)] pub struct LoadOutcome { @@ -384,6 +400,12 @@ pub struct LoadOutcome { pub issues: Vec, /// Whether the user's document was rejected and the defaults were substituted. pub used_defaults: bool, + /// What the rejected document selected for the event store, when it selected one. + /// + /// `None` on a clean load, when the document names no `eventStore` key, and on the + /// unreadable arm, which has no document to read. It never alters `settings`, `issues` + /// or `used_defaults`. + pub discarded_store_selection: Option, } /// Loads and validates the effective settings, falling back to the defaults on any failure. @@ -402,6 +424,7 @@ pub fn load(paths: &SettingsPaths) -> Result { format!("failed to load user settings: {error}"), )], used_defaults: true, + discarded_store_selection: None, }); } }; @@ -411,16 +434,19 @@ pub fn load(paths: &SettingsPaths) -> Result { settings: defaults_settings, issues: Vec::new(), used_defaults: false, + discarded_store_selection: None, }); }; let merged = merge(&defaults, &user); let issues = validate_document(&merged, &defaults); if !issues.is_empty() { + let discarded_store_selection = discarded_store_selection(&user, &issues); return Ok(LoadOutcome { settings: defaults_settings, issues, used_defaults: true, + discarded_store_selection, }); } @@ -429,12 +455,49 @@ pub fn load(paths: &SettingsPaths) -> Result { settings, issues, used_defaults: false, + discarded_store_selection: None, }), - Err(issue) => Ok(LoadOutcome { - settings: defaults_settings, - issues: vec![issue], - used_defaults: true, - }), + Err(issue) => { + let discarded_store_selection = + discarded_store_selection(&user, std::slice::from_ref(&issue)); + Ok(LoadOutcome { + settings: defaults_settings, + issues: vec![issue], + used_defaults: true, + discarded_store_selection, + }) + } + } +} + +/// Records the store the rejected document selected: `eventStore.backend` when the document +/// states it, otherwise the first refused path at `eventStore` or below it. +fn discarded_store_selection( + document: &Value, + issues: &[Issue], +) -> Option { + if let Some(value) = lookup(document, "eventStore.backend") { + return Some(DiscardedStoreSelection { + path: "eventStore.backend".to_owned(), + value: yaml_scalar(value), + }); + } + let issue = issues + .iter() + .find(|issue| issue.path == "eventStore" || issue.path.starts_with("eventStore."))?; + Some(DiscardedStoreSelection { + path: issue.path.clone(), + value: lookup(document, &issue.path).and_then(yaml_scalar), + }) +} + +/// Renders a YAML scalar as its text; a mapping, sequence or tagged value is not a scalar. +fn yaml_scalar(value: &Value) -> Option { + match value { + Value::Mapping(_) | Value::Sequence(_) | Value::Tagged(_) => None, + scalar => serde_yaml::to_string(scalar) + .ok() + .map(|text| text.trim_end().to_owned()), } } diff --git a/crates/nostreamd/src/settings_gate.rs b/crates/nostreamd/src/settings_gate.rs index 45649cdd9..4ec2b3059 100644 --- a/crates/nostreamd/src/settings_gate.rs +++ b/crates/nostreamd/src/settings_gate.rs @@ -2,14 +2,17 @@ //! //! A user configuration that cannot be read or does not validate never aborts the process: //! `nostream_config::load` substitutes the shipped defaults and reports the findings. The -//! serve path logs every finding and continues on the defaults; `--check` is the one place -//! findings are fatal (exit 2), because its whole job is to report them. +//! serve path logs every finding and continues on the defaults, with one exception: when the +//! rejected document selected an event store the substitution would override, the gate +//! refuses to start (exit 2, ADR 0022) before any store is opened. `--check` reports the +//! findings as fatal (exit 2) whether or not a selection was discarded, because its whole job +//! is to report them. //! //! This module is also the workspace's one library-position writer to stdout/stderr *outside //! the `tracing` subscriber*: every other write a library crate makes goes through `tracing` //! and `telemetry::init`'s `tracing_subscriber::fmt()` layer (whose writer the mode chooses — //! stdout for the relay path, stderr for `--mcp-stdio` — and whose output the `EnvFilter` -//! governs). These three bypass that filter, so the rule that +//! governs). These writes bypass that filter, so the rule that //! keeps them honest is worth stating: output belongs to a process's entry point, and a //! library that writes to a stream the caller does not drain can block it — a per-record //! write stalls a whole subscription behind a full pipe. These writes are the operator report @@ -17,7 +20,9 @@ //! them newline-terminated (so each flushes per write). Nothing added here may run per //! request, per message or per streamed record. -use nostream_config::LoadOutcome; +use nostream_config::{DiscardedStoreSelection, LoadOutcome}; +use nostream_core::EventStoreBackend; +use nostream_storage::event_store::configured_backend; use crate::error::DaemonError; @@ -38,9 +43,40 @@ pub fn apply_settings_gate(outcome: &LoadOutcome, check: bool) -> Result<(), Dae count: outcome.issues.len(), }); } + if let Some(selection) = &outcome.discarded_store_selection { + let backend = configured_backend(&outcome.settings); + if !keeps_backend(selection, backend) { + match &selection.value { + Some(value) => eprintln!( + "nostreamd: refusing to start: the rejected settings document sets {}={value}; the shipped defaults would serve {backend}", + selection.path + ), + None => eprintln!( + "nostreamd: refusing to start: the rejected settings document sets {}; the shipped defaults would serve {backend}", + selection.path + ), + } + return Err(DaemonError::InvalidSettings { + count: outcome.issues.len(), + }); + } + } eprintln!( "nostreamd: continuing on the shipped defaults ({} issue(s) in the user settings)", outcome.issues.len() ); Ok(()) } + +/// Whether the substitution keeps the store backend the discarded document selected. +/// +/// Only an explicit `eventStore.backend` naming the backend that will serve can continue; a +/// refused subtree, a value outside the accepted spellings and a different backend all refuse. +fn keeps_backend(selection: &DiscardedStoreSelection, backend: EventStoreBackend) -> bool { + selection.path == "eventStore.backend" + && selection + .value + .as_deref() + .and_then(EventStoreBackend::parse) + == Some(backend) +} diff --git a/crates/nostreamd/tests/check_flag.rs b/crates/nostreamd/tests/check_flag.rs index 023de2f65..dd41c3705 100644 --- a/crates/nostreamd/tests/check_flag.rs +++ b/crates/nostreamd/tests/check_flag.rs @@ -310,3 +310,30 @@ fn check_reports_nothing_for_the_shipped_defaults() { assert_eq!(stdout.trim(), "settings valid: 0 issues"); assert_eq!(stderr, "", "the shipped defaults are not a violation"); } + +#[test] +fn check_exits_two_on_a_rejected_document_that_selected_lmdb() { + // A discarded store selection refuses the serve path (ADR 0022), but `--check` reported the + // same document before the rule existed: its verdict, its two stderr lines and its empty + // stdout are byte-identical, with no refusal line. + let directory = tempfile::tempdir().expect("tempdir"); + std::fs::write( + directory.path().join("settings.yaml"), + "eventStore:\n backend: lmdb\nlimits:\n rateLimiter:\n strategy: random\n", + ) + .expect("write"); + + let config_dir = directory.path().to_string_lossy().into_owned(); + let (code, stdout, stderr) = run_check( + Duration::from_secs(30), + &["--check", "--config-dir", &config_dir], + ); + assert_eq!(code, Some(2), "exit code"); + assert!(stdout.is_empty(), "nothing on stdout: {stdout:?}"); + assert_eq!( + stderr.trim(), + "limits.rateLimiter.strategy: strategy must be ewma or sliding_window\n\ + settings invalid: 1 issues", + "the check path is byte-identical and prints no refusal" + ); +} diff --git a/crates/nostreamd/tests/settings_gate.rs b/crates/nostreamd/tests/settings_gate.rs index 4e8c1a934..16766f51c 100644 --- a/crates/nostreamd/tests/settings_gate.rs +++ b/crates/nostreamd/tests/settings_gate.rs @@ -133,3 +133,111 @@ fn a_clean_document_passes_the_gate_both_ways() { assert!(outcome.issues.is_empty()); nostreamd::settings_gate::apply_settings_gate(&outcome, true).expect("check passes"); } + +/// Loads one `settings.yaml` body into an outcome, the way the daemon's `run` sees it. +fn load_body(body: &str) -> nostream_config::LoadOutcome { + let directory = tempfile::tempdir().expect("tempdir"); + fs::write(directory.path().join("settings.yaml"), body).expect("write"); + let paths = SettingsPaths::from_config_dir(&workspace_root(), directory.path()); + nostream_config::load(&paths).expect("the loader never refuses") +} + +#[test] +fn a_rejected_document_that_selected_lmdb_refuses_the_serve_path() { + // The document names the store the deployment runs on and carries one bad field, so the + // substitution would swap LMDB for the shipped Postgres. The gate must refuse it rather + // than serve a store nobody selected (ADR 0022, #1305). + let outcome = + load_body("eventStore:\n backend: lmdb\nlimits:\n rateLimiter:\n strategy: random\n"); + + assert!(outcome.used_defaults, "the defaults substitute"); + let error = nostreamd::settings_gate::apply_settings_gate(&outcome, false) + .expect_err("a discarded lmdb selection refuses the serve path"); + assert!(matches!( + error, + nostreamd::DaemonError::InvalidSettings { count: 1 } + )); +} + +#[test] +fn a_rejected_document_that_keeps_postgres_continues() { + // The substitution keeps the backend the document named, so it is a no-op selection and + // the serve path continues as it always has (ADR 0022's equality arm). + let outcome = load_body( + "eventStore:\n backend: postgres\nlimits:\n rateLimiter:\n strategy: random\n", + ); + + assert!(outcome.used_defaults, "the defaults substitute"); + nostreamd::settings_gate::apply_settings_gate(&outcome, false).expect("serve continues"); + assert_eq!( + nostream_storage::event_store::configured_backend(&outcome.settings), + nostream_core::EventStoreBackend::Postgres, + "the shipped backend is the one the document named" + ); +} + +#[test] +fn a_document_that_cannot_be_parsed_still_serves_on_the_defaults() { + // A document that does not parse has no readable selection, so the deliberate limitation + // stands: it is reported and the daemon serves the shipped defaults (ADR 0022, D5). + let outcome = load_body("eventStore: [\n"); + + assert!(outcome.used_defaults, "the defaults substitute"); + assert_eq!(outcome.issues[0].path, "$", "the whole document failed"); + assert!( + outcome.discarded_store_selection.is_none(), + "there is no document to read a selection from" + ); + nostreamd::settings_gate::apply_settings_gate(&outcome, false).expect("serve continues"); +} + +#[test] +fn a_document_that_fails_the_typed_fit_still_refuses_a_discarded_lmdb_selection() { + // `fit` rejects the document after the shape walk approves it, so the selection must be + // recorded on that arm too: otherwise the fit path silently swaps the store (ADR 0022). + let outcome = load_body( + "eventStore:\n backend: lmdb\nlimits:\n event:\n pow:\n periodMs: 1000.5\n", + ); + + assert!(outcome.used_defaults, "the defaults substitute"); + assert_eq!( + outcome + .issues + .iter() + .map(ToString::to_string) + .collect::>(), + ["limits.event.pow.periodMs: must be a whole number"], + "the walk approves the document and the fit names the number" + ); + let error = nostreamd::settings_gate::apply_settings_gate(&outcome, false) + .expect_err("the fit arm keeps the discarded selection"); + assert!(matches!( + error, + nostreamd::DaemonError::InvalidSettings { count: 1 } + )); +} + +#[test] +fn the_discarded_selection_names_only_a_selection_the_document_made() { + // The merged document always holds `eventStore.backend: postgres`; the report must hold + // what the operator's file said, so a document that names no store reports `None`. + let without_store = load_body("limits:\n rateLimiter:\n strategy: random\n"); + assert!( + without_store.discarded_store_selection.is_none(), + "a document with no eventStore key named no store" + ); + nostreamd::settings_gate::apply_settings_gate(&without_store, false).expect("serve continues"); + + let with_store = + load_body("eventStore:\n backend: lmdb\nlimits:\n rateLimiter:\n strategy: random\n"); + let selection = with_store + .discarded_store_selection + .as_ref() + .expect("the document selected a store"); + assert_eq!(selection.path, "eventStore.backend"); + assert_eq!(selection.value.as_deref(), Some("lmdb")); + assert!( + nostreamd::settings_gate::apply_settings_gate(&with_store, false).is_err(), + "the discarded selection refuses the serve path" + ); +} diff --git a/crates/nostreamd/tests/store_wiring.rs b/crates/nostreamd/tests/store_wiring.rs index 412238f3a..c377e1a8c 100644 --- a/crates/nostreamd/tests/store_wiring.rs +++ b/crates/nostreamd/tests/store_wiring.rs @@ -7,6 +7,8 @@ //! | Postgres: the same, from the same binary, selected by settings (needs `PARITY_ADMIN_URL`) | `an_event_survives_a_restart_on_postgres` | //! | the lmdb backend without `--data-dir` refuses to start, naming the flag | `the_lmdb_backend_without_a_data_dir_refuses_to_start` | //! | Postgres that cannot be reached refuses to start instead of serving an empty store | `an_unreachable_postgres_refuses_to_start` | +//! | a rejected document that selected lmdb refuses before opening a store | `a_rejected_document_that_selected_lmdb_refuses_before_opening_a_store` | +//! | a document refused under `eventStore` refuses too, naming the path and value | `a_refused_event_store_subtree_refuses_before_opening_a_store` | //! //! These targets may unwrap and assert by panicking: a failed assertion is a failed test. @@ -361,6 +363,133 @@ fn an_unreachable_postgres_refuses_to_start() { ); } +/// A Postgres target nothing listens on, so a regressed build fails at the dial in about two +/// seconds instead of serving CI's live Postgres on 5432. +const DEAD_POSTGRES: &str = "postgres://postgres:postgres@127.0.0.1:1/nostream"; + +#[test] +fn a_rejected_document_that_selected_lmdb_refuses_before_opening_a_store() { + // One bad field discards the document, and the substitution would serve the shipped + // Postgres while the deployment was configured for LMDB. The daemon must refuse before + // resolving a backend, opening a store or dialling the database (ADR 0022, #1305). + let config_dir = tempfile::tempdir().expect("tempdir"); + std::fs::write( + config_dir.path().join("settings.yaml"), + "eventStore:\n backend: lmdb\nlimits:\n rateLimiter:\n strategy: random\n", + ) + .expect("settings written"); + + let daemon = Daemon::spawn( + config_dir.path(), + None, + free_port(), + &[ + ("DB_URI", DEAD_POSTGRES), + ("DB_ACQUIRE_CONNECTION_TIMEOUT", "2000"), + ], + ); + let (code, logs) = daemon.exit(Duration::from_secs(30)); + + let refusal = "nostreamd: refusing to start: the rejected settings document sets \ + eventStore.backend=lmdb; the shipped defaults would serve postgres"; + assert_eq!(code, Some(2), "the refusal exits 2: {logs}"); + assert_eq!( + logs.matches(refusal).count(), + 1, + "the refusal line is printed once: {logs}" + ); + let issue = logs + .find("limits.rateLimiter.strategy: strategy must be ewma or sliding_window") + .expect("the finding is reported"); + let refusal_at = logs.find(refusal).expect("the refusal follows the finding"); + let verdict = logs + .find("settings invalid: 1 issues") + .expect("the gate's count reaches main"); + assert!(issue < refusal_at, "the finding comes first: {logs}"); + assert!(refusal_at < verdict, "the verdict comes last: {logs}"); + assert!( + !logs.contains("continuing on the shipped defaults"), + "the refusal does not continue: {logs}" + ); + assert!( + !logs.contains("event store backend resolved"), + "no backend is resolved: {logs}" + ); +} + +/// Spawns the daemon on `document` against a dead Postgres and asserts it refused before any +/// store was opened. +fn assert_store_selection_refused(document: &str, refusal: &str, issues: usize) { + let config_dir = tempfile::tempdir().expect("tempdir"); + std::fs::write(config_dir.path().join("settings.yaml"), document).expect("settings written"); + + let daemon = Daemon::spawn( + config_dir.path(), + None, + free_port(), + &[ + ("DB_URI", DEAD_POSTGRES), + ("DB_ACQUIRE_CONNECTION_TIMEOUT", "2000"), + ], + ); + let (code, logs) = daemon.exit(Duration::from_secs(30)); + + assert_eq!(code, Some(2), "the refusal exits 2: {logs}"); + assert_eq!( + logs.matches(refusal).count(), + 1, + "the refusal line is printed once: {logs}" + ); + assert!( + logs.contains(&format!("settings invalid: {issues} issues")), + "the gate's count reaches main: {logs}" + ); + assert!( + !logs.contains("continuing on the shipped defaults"), + "the refusal does not continue: {logs}" + ); + assert!( + !logs.contains("event store backend resolved"), + "no backend is resolved: {logs}" + ); +} + +#[test] +fn a_refused_event_store_subtree_refuses_before_opening_a_store() { + // Each document is refused at `eventStore` or below, so it has no readable selection: the + // gate refuses and names the refused path and the backend that would serve (ADR 0022). + let cases = [ + ( + "eventStore:\n backnd: lmdb\n", + "nostreamd: refusing to start: the rejected settings document sets \ + eventStore.backnd=lmdb; the shipped defaults would serve postgres", + 1, + ), + ( + "eventStore:\n backend: sqlite\n", + "nostreamd: refusing to start: the rejected settings document sets \ + eventStore.backend=sqlite; the shipped defaults would serve postgres", + 1, + ), + ( + "eventStore: lmdb\n", + "nostreamd: refusing to start: the rejected settings document sets \ + eventStore=lmdb; the shipped defaults would serve postgres", + 1, + ), + ( + "eventStore:\n backend: [lmdb]\n", + "nostreamd: refusing to start: the rejected settings document sets \ + eventStore.backend; the shipped defaults would serve postgres", + 2, + ), + ]; + + for (document, refusal, issues) in cases { + assert_store_selection_refused(document, refusal, issues); + } +} + /// Creates a scratch database migrated to the schema and returns its URL. async fn scratch_postgres(admin_url: &str, name: &str) -> String { use sqlx::Connection; diff --git a/docs/rewrite/decisions/0008-frame-memory-budget.md b/docs/rewrite/decisions/0008-frame-memory-budget.md index fa8c4bb82..90b150636 100644 --- a/docs/rewrite/decisions/0008-frame-memory-budget.md +++ b/docs/rewrite/decisions/0008-frame-memory-budget.md @@ -574,6 +574,14 @@ four measurements are pinned (`check_refuses_a_zero_bound`, `config_validate_ref `a_zero_bound_is_an_issue_at_the_gate`, and the serving path's " Ok(())" arm through that same gate test's `check = false` call). +**One exception, added by ADR 0022.** When the rejected document selected an event store the +substitution would override — `eventStore.backend` naming a backend other than the one that will +serve, or a refusal at `eventStore` or below it — a normal start refuses too. It prints +`nostreamd: refusing to start: the rejected settings document sets [=]; the shipped +defaults would serve ` and exits **2** before any store is opened, so this is the second +serve-path verdict beside "continues on the defaults". A document that names no store, names the +backend that will serve, or cannot be parsed keeps the rule above. + *Where nothing is substituted, there is a leaf to read and both doors read it.* With no user document — a fresh install, a different `--config-dir` — `load` returns the shipped defaults with `used_defaults` false, and with a valid document it returns the operator's typed settings. diff --git a/docs/rewrite/decisions/0009-settings-ceiling.md b/docs/rewrite/decisions/0009-settings-ceiling.md index 697d10236..3b1724bc3 100644 --- a/docs/rewrite/decisions/0009-settings-ceiling.md +++ b/docs/rewrite/decisions/0009-settings-ceiling.md @@ -153,9 +153,10 @@ Each of these was measured on this branch after the change: accepted cost of a ceiling that refuses rather than defaults; the second is additionally the cost of giving the cap its own ceiling. - At start-up stderr carries one `{path}: {message}` line per issue - (`crates/nostreamd/src/settings_gate.rs:32`) and then + (`crates/nostreamd/src/settings_gate.rs:38`) and then `nostreamd: continuing on the shipped defaults (N issue(s) in the user settings)` - (`crates/nostreamd/src/settings_gate.rs:41`). + (`crates/nostreamd/src/settings_gate.rs:64`) — unless the document selected a store the + substitution would override, which refuses to start (ADR 0022). - `nostreamd --check` exits 2, prints no `settings valid` line, and ends stderr with `settings invalid: N issues` (`crates/nostreamd/src/main.rs:43`). - `nostream-cli config validate` exits 2 with the issue lines then the same verdict @@ -214,7 +215,9 @@ ceiling only. - **The TypeScript application.** `src/` knows neither key, so no parity case can encode either ceiling and this record is their only specification. - **The whole-document substitution.** That `load` discards the file for one issue is `load`'s rule - and predates this job; this record states the cost rather than changing it. + and predates this job; this record states the cost rather than changing it. ADR 0022 narrows it + for one field: a rejected document that selected an event store the substitution would override + is refused at the daemon's gate rather than served on the defaults. - **A per-key fallback, or a report that is not an issue.** Both were deleted here and neither returns under another name. diff --git a/docs/rewrite/decisions/0022-store-selection-refusal.md b/docs/rewrite/decisions/0022-store-selection-refusal.md new file mode 100644 index 000000000..ed9cbee72 --- /dev/null +++ b/docs/rewrite/decisions/0022-store-selection-refusal.md @@ -0,0 +1,126 @@ +# ADR 0022: A rejected settings document must not swap the event store + +- **Status:** accepted (job 048, Phase 6) +- **Deciders:** the rewrite team, on the security finding F16 in + `docs/rewrite/reviews/2026-11-30-relay-storage.md` and this job's spec +- **Date:** 2026-12-04 + +## Context + +`nostream_config::load` applies the capture's fallback rule: a user document that cannot be read +or does not validate never aborts the process. It reports the findings as `Issue` values and +returns the shipped defaults with `used_defaults: true` +(`crates/nostream-config/src/load.rs`). The daemon's gate then logs each finding and, on the +serve path, continues on those defaults (`crates/nostreamd/src/settings_gate.rs`). + +That rule costs the operator's whole document, which ADR 0008 and ADR 0009 already state. It +also, until this record, cost something neither anticipated: the document's **store selection**. +`eventStore.backend` is the only settings field that decides which event store the daemon opens +(`crates/nostream-config/src/settings.rs`; `crates/nostream-storage/src/event_store.rs` +`configured_backend`), the shipped value is `postgres` +(`resources/default-settings.yaml`), and a rejected document is replaced by the shipped defaults. +So one bad field anywhere in `settings.yaml` made an LMDB deployment resolve Postgres and serve +and accept writes into the old Postgres store, while the data directory it was pointed at sat +unused. `used_defaults` recorded that the substitution happened; nothing read it. + +The gate is the one place both doors pass (`crates/nostreamd/src/main.rs:122`, and +`crates/nostreamd/src/mcp_stdio.rs:80` for `--mcp-stdio`), and it runs before the `--check` early +return and before either door resolves a backend. `load` still has the user document in scope at +its rejection arms, so it can report what the document selected even though it must not decide +fatality itself. + +The values that place a store are otherwise outside settings, and that is why the selection is +the only unsafe field: the LMDB root is the `--data-dir` flag +(`crates/nostreamd/src/main.rs:29-33`), Postgres comes from `DB_URI`/`DB_*` +(`crates/nostreamd/src/stores.rs`), and the LMDB map size is the fixed `LMDB_MAP_SIZE` +(`crates/nostream-storage/src/lmdb/mod.rs:51`). + +## Decisions + +### D1 — A rejected document's store selection is never replaced silently + +`LoadOutcome` carries `discarded_store_selection: Option`, set by +`load` on the two rejection arms that read a document — the shape walk's and the typed fit's. It +records the value at `eventStore.backend` when the document states that key, otherwise the first +refused path at `eventStore` or below it, with the scalar there rendered as YAML text (`None` +when the value is not a scalar). It is `None` on a clean load, on a document that names no +`eventStore` key, and on the unreadable/unparseable arm, which has no document to read; it never +alters `settings`, `issues` or `used_defaults`. + +On the serve path the gate continues exactly as before when the selection is absent, or when it +is `eventStore.backend` and its value parses to the backend `configured_backend` would serve: an +explicit `postgres` in a rejected document is a no-op substitution, not a refusal. Every other +selection — a different backend, a refused subtree, a value outside `{postgres, lmdb}`, a +non-scalar — refuses to start. `load` itself still never refuses. + +### D2 — Which fields are safe to default, and why + +Every settings field but `eventStore.backend` and the `eventStore` subtree is safe to replace +with the shipped default, because nothing else in settings can move where rows are written. +`--data-dir` fixes the LMDB root and is a flag, not a setting; `DB_URI`/`DB_*` fix the Postgres +target from the environment; `LMDB_MAP_SIZE` is a constant +(`crates/nostream-storage/src/lmdb/mod.rs:51`). `mirroring` is parsed and has no consumer outside +`nostream-config`. `EVENT_STORE_BACKEND` overrides the settings value only for a worker +(`is_worker = true`, `crates/nostream-storage/src/event_store.rs:29-46`), and both daemon doors +pass `false`, so the variable cannot select a backend in this process. The `eventStore` subtree +is unsafe as a whole: an unknown key such as `backnd`, a wrong-typed `eventStore`, or a `backend` +outside the accepted spellings discards the selection exactly as a bad sibling field does. + +### D3 — The operator contract + +A refusal prints one line, after the per-issue lines and before the error return: + +``` +nostreamd: refusing to start: the rejected settings document sets {path}={value}; the shipped defaults would serve {backend} +``` + +and, when the value there is not a scalar, the same line without `={value}`. It reuses +`DaemonError::InvalidSettings`, so `main` prints `settings invalid: {count} issues` and exits +**2**; no new error variant is added. Nothing is served and no store is opened: the gate is +reached before telemetry, before `Acceptor::bind`, before either backend is resolved and before +the MCP branch, so a refused start prints no `event store backend resolved` line, opens no LMDB +store and dials no Postgres. + +### D4 — The check path is unchanged, and why the refusal is not in `load` + +`--check` returns `InvalidSettings` before the refusal branch, so its exit code, its issue lines +and its `settings invalid: {count} issues` are byte-identical to what it printed before this +record, and it never prints the refusal line. A refusal in `load` was rejected: `run` maps a +`load` error to `DaemonError::Setup` (`crates/nostreamd/src/main.rs:120-121`), and every other +error exits **1** (`crates/nostreamd/src/main.rs:106-109`), so `--check` would lose its exit-2 +contract. Detection belongs where the document is, the decision where the one gate is. + +### D5 — The deliberate limitation + +A document that cannot be parsed has no readable selection, so it keeps continue-on-defaults: +refusing every broken YAML would change behaviour for deployments that never opted into a +non-default store. The residual risk is stated rather than hidden: a broken `settings.yaml` on an +LMDB deployment still serves the shipped Postgres. Refusing on `--data-dir` was considered and +rejected: the gate does not receive the flag, and the rule would then depend on a deployment +flag rather than on what the operator's document said. + +### D6 — The amendments, and what stays out + +`docs/rewrite/decisions/0009-settings-ceiling.md`'s "What this does not decide" and +`docs/rewrite/decisions/0008-frame-memory-budget.md`'s "What a rejected document leaves to +report" gain a live sentence pointing at this record and its exception. Out of scope: the admin's +per-request re-read fallback (`crates/nostream-admin/src/state.rs:407-416`), which is not the +start path, and the CLI, whose `config validate` already refuses a rejected document at exit 2. + +## Consequences + +The daemon refuses to start rather than silently serve a store the operator did not select. The +refusal is loud, names the field and the discarded value, and exits with the code settings +problems already use, so a script that treats exit 2 as "settings invalid" keeps working. A +document that selects the backend that would serve — including the shipped `postgres`, and +including every document that names no store — behaves exactly as before. + +The cost: an operator who writes `eventStore.backend: lmdb`, breaks an unrelated field, and +expects the relay to limp along on the defaults now gets a refusal and must fix the field or the +backend. That is the intended trade — a relay that serves the wrong store is worse than one that +does not start. The limitation in D5 remains: a YAML file that does not parse leaves no selection +to read, so that arm still continues on the defaults, and the residual risk of serving Postgres +on an LMDB deployment is recorded here rather than closed. + +The admin's per-request fallback and the CLI keep their own rules; this record covers the +daemon's start path only. diff --git a/docs/rewrite/deploying.md b/docs/rewrite/deploying.md index 4f9277c2e..86f39bb31 100644 --- a/docs/rewrite/deploying.md +++ b/docs/rewrite/deploying.md @@ -145,9 +145,11 @@ daemon setup failed: failed to read /tmp/resources/default-settings.yaml: No suc exit 1 ``` -**`--check` is the only mode that exits 2.** It validates and stops -(`crates/nostreamd/src/settings_gate.rs:1-11`). The exit codes are 0 for success, 2 for invalid -settings, 1 for anything else (`crates/nostreamd/src/main.rs:97-111`): +**`--check` and a refused store selection are the only modes that exit 2.** `--check` validates +and stops (`crates/nostreamd/src/settings_gate.rs`); a serve path refuses when the rejected +document selected an event store the substitution would override (ADR 0022, below). The exit +codes are 0 for success, 2 for invalid settings, 1 for anything else +(`crates/nostreamd/src/main.rs:97-111`): ``` $ nostreamd --check --config-dir /tmp/046-scratch/cfg @@ -165,16 +167,34 @@ settings invalid: 1 issues exit 2 ``` -**A bad setting does not stop a run** — the daemon says so and continues on the shipped -defaults, which is the behaviour to know before wondering why a setting had no effect: +**A bad setting in a document that names no store does not stop a run** — the daemon says so and +continues on the shipped defaults, which is the behaviour to know before wondering why a setting +had no effect: ``` -$ nostreamd --config-dir /tmp/046-scratch/cfg-bad --data-dir /tmp/046-scratch/data --listen-port 5744 -eventStore.backend: backend must be one of: postgres, lmdb +$ nostreamd --config-dir /tmp/046-scratch/cfg-limits --data-dir /tmp/046-scratch/data --listen-port 5744 +limits.rateLimiter.strategy: strategy must be ewma or sliding_window nostreamd: continuing on the shipped defaults (1 issue(s) in the user settings) INFO event store backend resolved backend=Postgres ``` +**A refused store selection stops a run.** A rejected document that selected an event store the +substitution would override — `eventStore.backend` naming a backend other than the one that +would serve, or a fault at `eventStore` or below it — refuses to start before the gate resolves a +backend or opens a store, because serving the shipped Postgres while the deployment was +configured for LMDB would write into the wrong store (ADR 0022): + +``` +$ DB_URI=postgres://postgres:postgres@127.0.0.1:1/nostream nostreamd --config-dir /tmp/048-scratch/cfg-bad-lmdb --listen-port 5744 +limits.rateLimiter.strategy: strategy must be ewma or sliding_window +nostreamd: refusing to start: the rejected settings document sets eventStore.backend=lmdb; the shipped defaults would serve postgres +settings invalid: 1 issues +exit 2 +``` + +A document that cannot be parsed has no readable selection, so it keeps the continuation above +(ADR 0022, decision 5). + **The port** is `--listen-port`, then `PORT`, then `RELAY_PORT`, then `8008` (`crates/nostreamd/src/main.rs:149-161`). Measured, each with the same `--data-dir`: