diff --git a/.changeset/redact-container-settings-writes.md b/.changeset/redact-container-settings-writes.md new file mode 100644 index 000000000..d121c6cd4 --- /dev/null +++ b/.changeset/redact-container-settings-writes.md @@ -0,0 +1,6 @@ +--- +--- + +fix(admin): redact the secrets inside a container-valued settings write (#1193) + +`PATCH /admin/settings` and the MCP `settings_set` tool echo each written value in their answer and in the `settings.changed` outbox row, and redacted that value only when it was itself a non-empty string at a secret path. A write to a whole block, such as `admin.notifications` or `admin.notifications.targets`, therefore answered and queued every target's `botToken`, signing `secret` and webhook `url` in the clear, and the outbox sends that row to every enabled target when notifications and the `settings.changed` event are on. The written value is now walked for secrets from the path it was written at, as `settings_get` walks the document, and that path is read once the way the settings reader reads it, so a padded `" admin.notifications "` redacts too. The walk classifies each value from its own key and whether its path starts with `admin.notifications.targets`, so a long key or index above a value is no longer copied into the path of everything below it. Secret classification strips only a trailing numeric index, as the TypeScript does, so a key such as `secret[label]` is no longer taken for `secret` in any redacted view. The saved settings keep the real values. Deliberate limits: only non-empty string values are redacted, so a secret written as a number or as a string inside a list is shown as before, and rows queued before this change are delivered as they were stored. diff --git a/crates/nostream-admin/tests/write_path.rs b/crates/nostream-admin/tests/write_path.rs index e23a0604a..5a33971f8 100644 --- a/crates/nostream-admin/tests/write_path.rs +++ b/crates/nostream-admin/tests/write_path.rs @@ -7,6 +7,7 @@ //! | `every_concurrent_settings_save_lands` | six overlapping `PATCH /settings` requests each keep their change | //! | `a_moderation_action_enqueues_the_settings_changed_row` | the action queues `settings.changed`, not an event the operator cannot toggle | //! | `a_limits_patch_enqueues_the_settings_changed_row` | the limits route goes through the same save flow and queues one too | +//! | `a_container_write_redacts_its_secrets_in_the_echo_and_the_row` | a write above a target's secrets, padded path included, echoes and queues `***` but saves the values (#1193) | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -210,3 +211,86 @@ async fn a_limits_patch_enqueues_the_settings_changed_row() { "the message names a settings path the patch changed" ); } + +const TARGET_SECRETS: [&str; 4] = [ + "tg-bot-token-value", + "slack-hook-value", + "https://ops.example/hook", + "hmac-key-value", +]; + +fn notifications_with_secrets() -> serde_json::Value { + json!({ + "enabled": true, + "targets": [ + { "id": "tg-ops", "type": "telegram", "enabled": true, + "botToken": "tg-bot-token-value", "chatId": "-100200" }, + { "id": "slack-ops", "type": "slack", "enabled": true, + "url": "https://hooks.slack.com/services/T00/B00/slack-hook-value" }, + { "id": "http-ops", "type": "http", "enabled": true, + "url": "https://ops.example/hook", "secret": "hmac-key-value" } + ] + }) +} + +fn notifications_redacted() -> serde_json::Value { + json!({ + "enabled": true, + "targets": [ + { "id": "tg-ops", "type": "telegram", "enabled": true, + "botToken": "***", "chatId": "-100200" }, + { "id": "slack-ops", "type": "slack", "enabled": true, "url": "***" }, + { "id": "http-ops", "type": "http", "enabled": true, "url": "***", "secret": "***" } + ] + }) +} + +#[tokio::test] +async fn a_container_write_redacts_its_secrets_in_the_echo_and_the_row() { + for path in ["admin.notifications", " admin.notifications "] { + let server = TestServer::start().await; + let cookie = server.login().await; + + let response = server + .send_json( + "PATCH", + "/admin/settings", + &cookie, + json!({ "path": path, "value": notifications_with_secrets() }), + ) + .await; + assert_eq!(response.status, 200, "{path:?}: {}", response.text()); + let echo = response.text(); + let rows = outbox_rows(&server).await; + assert_eq!(rows.len(), 1, "{path:?}: one settings-change message"); + let row = rows[0].payload.to_string(); + for secret in TARGET_SECRETS { + assert!( + !echo.contains(secret), + "{path:?}: the echo carries {secret}: {echo}" + ); + assert!( + !row.contains(secret), + "{path:?}: the row carries {secret}: {row}" + ); + } + + assert_eq!( + response.json()["value"], + notifications_redacted(), + "{path:?}" + ); + assert_eq!( + rows[0].payload["changes"][0]["value"], + notifications_redacted(), + "{path:?}" + ); + + let saved = user_settings(&server); + assert_eq!( + saved["admin"]["notifications"]["targets"][0]["botToken"], + serde_yaml::Value::String("tg-bot-token-value".to_owned()), + "{path:?}: only the echo is redacted, not what is saved" + ); + } +} diff --git a/crates/nostream-config/src/redaction.rs b/crates/nostream-config/src/redaction.rs index 1f67c3d6c..7887587a6 100644 --- a/crates/nostream-config/src/redaction.rs +++ b/crates/nostream-config/src/redaction.rs @@ -5,29 +5,88 @@ use serde_yaml::Value; /// Keys whose values are secrets wherever they appear. const SENSITIVE_SETTING_KEYS: [&str; 3] = ["passwordHash", "secret", "botToken"]; +const TARGETS_PREFIX: &str = "admin.notifications.targets"; + /// The placeholder a redacted value becomes. const REDACTED: &str = "***"; fn last_key(path: &str) -> &str { let last = path.rsplit('.').next().unwrap_or(path); - if last.ends_with(']') - && let Some(bracket) = last.rfind('[') + if let Some(inner) = last.strip_suffix(']') + && let Some(bracket) = inner.rfind('[') + && let Some(digits) = inner.get(bracket + 1..) + && !digits.is_empty() + && digits.bytes().all(|byte| byte.is_ascii_digit()) { return &last[..bracket]; } last } +/// As [`crate::path::parse_path`] reads a path: trimmed, and each segment trimmed. +fn normalize_settings_path(path: &str) -> String { + path.trim() + .split('.') + .map(str::trim) + .collect::>() + .join(".") +} + +/// The bytes of [`TARGETS_PREFIX`] a path has matched, `None` once it leaves it: all the `url` +/// rule reads of a path, so the walk carries this instead of building each descendant's path. +#[derive(Clone, Copy, PartialEq)] +struct TargetsPrefix(Option); + +impl TargetsPrefix { + fn of(path: &str) -> Self { + Self(Some(0)).then(path) + } + + fn then(self, text: &str) -> Self { + let Some(mut matched) = self.0 else { + return self; + }; + for byte in text.bytes() { + match TARGETS_PREFIX.as_bytes().get(matched) { + None => break, + Some(&expected) if expected == byte => matched += 1, + Some(_) => return Self(None), + } + } + Self(Some(matched)) + } + + fn key(self, key: &str) -> Self { + if self.0 == Some(0) { + self.then(key) + } else { + self.then(".").then(key) + } + } + + /// The prefix holds no `[`, so the bracket alone settles it. + fn index(self) -> Self { + self.then("[") + } + + fn matched(self) -> bool { + self.0 == Some(TARGETS_PREFIX.len()) + } +} + +/// `tail` is a path or a mapping key: only its last segment is read. +fn is_secret(tail: &str, prefix: TargetsPrefix) -> bool { + let key = last_key(tail); + SENSITIVE_SETTING_KEYS.contains(&key) || (key == "url" && prefix.matched()) +} + /// Whether a settings path holds a secret. /// /// Webhook URLs embed secrets (Discord/Slack tokens, signed HTTP endpoints), so `url` under /// `admin.notifications.targets` is sensitive too. pub fn is_sensitive_settings_path(path: &str) -> bool { - let key = last_key(path); - if SENSITIVE_SETTING_KEYS.contains(&key) { - return true; - } - key == "url" && path.starts_with("admin.notifications.targets") + let path = normalize_settings_path(path); + is_secret(&path, TargetsPrefix::of(&path)) } /// Whether a path may not be written through the settings editor. @@ -37,52 +96,47 @@ pub fn is_write_protected_settings_path(path: &str) -> bool { /// Redacts one value by path. pub fn redact_settings_value(path: &str, value: &Value) -> Value { + let path = normalize_settings_path(path); + let prefix = TargetsPrefix::of(&path); match value { - Value::String(text) if is_sensitive_settings_path(path) && !text.is_empty() => { + Value::String(text) if is_secret(&path, prefix) && !text.is_empty() => { Value::String(REDACTED.to_owned()) } - other => other.clone(), + other => walk(other, prefix), } } /// Redacts every secret in a settings document, walking arrays and objects. pub fn redact_settings_secrets(value: &Value) -> Value { - fn walk(value: &Value, path: &str) -> Value { - match value { - Value::Sequence(entries) => Value::Sequence( - entries - .iter() - .enumerate() - .map(|(index, entry)| walk(entry, &format!("{path}[{index}]"))) - .collect(), - ), - Value::Mapping(mapping) => { - let mut result = serde_yaml::Mapping::new(); - for (key, entry) in mapping { - let Some(key_name) = key.as_str() else { - result.insert(key.clone(), entry.clone()); - continue; - }; - let child_path = if path.is_empty() { - key_name.to_owned() - } else { - format!("{path}.{key_name}") - }; - let redacted = match entry { - Value::String(text) - if is_sensitive_settings_path(&child_path) && !text.is_empty() => - { - Value::String(REDACTED.to_owned()) - } - other => walk(other, &child_path), - }; - result.insert(key.clone(), redacted); - } - Value::Mapping(result) + walk(value, TargetsPrefix::of("")) +} + +fn walk(value: &Value, prefix: TargetsPrefix) -> Value { + match value { + Value::Sequence(entries) => Value::Sequence( + entries + .iter() + .map(|entry| walk(entry, prefix.index())) + .collect(), + ), + Value::Mapping(mapping) => { + let mut result = serde_yaml::Mapping::new(); + for (key, entry) in mapping { + let Some(key_name) = key.as_str() else { + result.insert(key.clone(), entry.clone()); + continue; + }; + let child = prefix.key(key_name); + let redacted = match entry { + Value::String(text) if is_secret(key_name, child) && !text.is_empty() => { + Value::String(REDACTED.to_owned()) + } + other => walk(other, child), + }; + result.insert(key.clone(), redacted); } - other => other.clone(), + Value::Mapping(result) } + other => other.clone(), } - - walk(value, "") } diff --git a/crates/nostream-config/tests/redaction.rs b/crates/nostream-config/tests/redaction.rs index c339d4978..9c7ebc0a2 100644 --- a/crates/nostream-config/tests/redaction.rs +++ b/crates/nostream-config/tests/redaction.rs @@ -177,3 +177,188 @@ fn the_typed_signing_secret_redacts_in_the_document_walk() { "admin.notifications.targets[0].secret" )); } + +fn targets() -> Value { + document( + "- id: slack-ops\n type: slack\n enabled: true\n url: https://hooks.slack.com/services/T00/B00/slack-hook-value\n- id: tg-ops\n type: telegram\n enabled: true\n botToken: tg-bot-token-value\n chatId: '-100200'\n- id: http-ops\n type: http\n enabled: true\n url: https://ops.example/hook\n secret: hmac-key-value\n", + ) +} + +fn redacted() -> Value { + Value::String("***".to_owned()) +} + +#[test] +fn a_value_written_at_a_parent_path_redacts_the_secrets_inside_it() { + let mut notifications = serde_yaml::Mapping::new(); + notifications.insert("targets".into(), targets()); + notifications.insert("recipients".into(), document("- ops@example.com\n")); + let notifications = Value::Mapping(notifications); + + let value = redact_settings_value("admin.notifications", ¬ifications); + assert_eq!(value["targets"][0]["url"], redacted()); + assert_eq!( + value["targets"][0]["id"], + Value::String("slack-ops".to_owned()) + ); + assert_eq!(value["targets"][1]["botToken"], redacted()); + assert_eq!( + value["targets"][1]["chatId"], + Value::String("-100200".to_owned()) + ); + assert_eq!(value["targets"][2]["url"], redacted()); + assert_eq!(value["targets"][2]["secret"], redacted()); + assert_eq!(value["recipients"], document("- ops@example.com\n")); + + let value = redact_settings_value("admin.notifications.targets", &targets()); + assert_eq!(value[0]["url"], redacted()); + assert_eq!(value[1]["botToken"], redacted()); + + let value = redact_settings_value("admin.notifications.targets[1]", &targets()[1]); + assert_eq!(value["botToken"], redacted()); + assert_eq!(value["chatId"], Value::String("-100200".to_owned())); + + let mut admin = serde_yaml::Mapping::new(); + admin.insert("notifications".into(), notifications); + let value = redact_settings_value("admin", &Value::Mapping(admin)); + assert_eq!(value["notifications"]["targets"][0]["url"], redacted()); + assert_eq!(value["notifications"]["targets"][1]["botToken"], redacted()); +} + +#[test] +fn a_path_with_whitespace_the_settings_reader_ignores_still_redacts() { + let mut notifications = serde_yaml::Mapping::new(); + notifications.insert("targets".into(), targets()); + let notifications = Value::Mapping(notifications); + + let value = redact_settings_value(" admin.notifications ", ¬ifications); + assert_eq!(value["targets"][0]["url"], redacted()); + assert_eq!(value["targets"][1]["botToken"], redacted()); + + let value = redact_settings_value("admin. notifications.targets", &targets()); + assert_eq!(value[0]["url"], redacted()); + + assert_eq!( + redact_settings_value( + "admin.notifications.targets[0]. url", + &Value::String("https://hooks.slack.com/services/T00".to_owned()) + ), + redacted() + ); + assert_eq!( + redact_settings_value( + "admin.notifications.targets[1].botToken ", + &Value::String("tg-bot-token-value".to_owned()) + ), + redacted() + ); + assert!(is_sensitive_settings_path( + " admin.notifications.targets[0].url" + )); +} + +#[test] +fn a_bracketed_suffix_that_is_not_an_index_is_part_of_the_key() { + assert!(is_sensitive_settings_path("mirroring.static[0].secret[2]")); + assert!(!is_sensitive_settings_path( + "admin.notifications.targets[0].secret[label]" + )); + + let target = document( + "id: http-ops\ntype: http\nurl: https://ops.example/hook\nsecret: hmac-key-value\n'secret[label]': signing key\n", + ); + let value = redact_settings_value("admin.notifications.targets[0]", &target); + assert_eq!(value["secret"], redacted()); + assert_eq!( + value["secret[label]"], + Value::String("signing key".to_owned()) + ); +} + +#[test] +fn the_walk_classifies_each_value_as_its_full_path_does() { + let input = document( + "admin:\n notifications:\n targets:\n - url: https://a.example/hook\n targetsX:\n - url: https://b.example/hook\n targ:\n url: https://c.example/hook\n ets:\n - url: https://h.example/hook\n notifications.targets:\n - url: https://d.example/hook\nadmin.notifications.targets:\n - url: https://e.example/hook\nother:\n url: https://f.example/\n a.botToken: dotted-token\n 'secret[2]': indexed-secret\n", + ); + let cases = [ + ( + "admin.notifications.targets[0].url", + &["admin", "notifications", "targets"][..], + Some(0), + "url", + true, + ), + ( + "admin.notifications.targetsX[0].url", + &["admin", "notifications", "targetsX"][..], + Some(0), + "url", + true, + ), + ( + "admin.notifications.targ.url", + &["admin", "notifications", "targ"][..], + None, + "url", + false, + ), + ( + "admin.notifications.targ.ets[0].url", + &["admin", "notifications", "targ", "ets"][..], + Some(0), + "url", + false, + ), + ( + "admin.notifications.targets[0].url", + &["admin", "notifications.targets"][..], + Some(0), + "url", + true, + ), + ( + "admin.notifications.targets[0].url", + &["admin.notifications.targets"][..], + Some(0), + "url", + true, + ), + ("other.url", &["other"][..], None, "url", false), + ("other.a.botToken", &["other"][..], None, "a.botToken", true), + ("other.secret[2]", &["other"][..], None, "secret[2]", true), + ]; + + let walked = redact_settings_secrets(&input); + for (path, parents, index, key, secret) in cases { + assert_eq!(is_sensitive_settings_path(path), secret, "{path}"); + let leaf = |document: &Value| { + let mut node = document; + for parent in parents { + node = &node[*parent]; + } + if let Some(index) = index { + node = &node[index]; + } + node[key].clone() + }; + let expected = if secret { redacted() } else { leaf(&input) }; + assert_eq!(leaf(&walked), expected, "{path} via {parents:?}"); + } + + let value = redact_settings_value("admin.notifications", &input["admin"]["notifications"]); + assert_eq!(value["targets"][0]["url"], redacted()); + assert_eq!(value["targetsX"][0]["url"], redacted()); + assert_eq!( + value["targ"]["url"], + Value::String("https://c.example/hook".to_owned()) + ); + + let listed = document("notifications:\n - targets:\n - url: https://g.example/hook\n"); + assert!(!is_sensitive_settings_path( + "admin.notifications[0].targets[0].url" + )); + assert_eq!( + redact_settings_value("admin", &listed)["notifications"][0]["targets"][0]["url"], + Value::String("https://g.example/hook".to_owned()) + ); +} diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs index 3e23499f1..046400450 100644 --- a/crates/nostream-mcp/tests/tool_payloads.rs +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -11,6 +11,7 @@ //! | `a_secret_is_redacted` | `settings_get` masks the secret and leaves a non-secret path verbatim | //! | `an_unknown_key_is_dropped` | `settings_get` drops a key the defaults lack | //! | `a_set_writes_the_file_its_records_and_a_backup` | a write has the controller's four side effects and its body | +//! | `a_container_write_echoes_no_secret` | a write above a secret answers and queues `***`, and the file keeps the value (#1193) | //! | `a_workers_change_is_restart_required` | the reload class is the path's own | //! | `a_sealed_path_is_refused` | a write-protected path answers the controller's body and writes nothing | //! | `a_null_value_is_a_validation_failure` | an explicit `null` reaches the validator | @@ -232,6 +233,41 @@ async fn a_set_writes_the_file_its_records_and_a_backup() { assert_eq!(fixture.backups().len(), 1, "one save, one backup"); } +#[tokio::test] +async fn a_container_write_echoes_no_secret() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client + .call( + TOOL_SETTINGS_SET, + json!({ + "path": "admin.notifications.targets", + "value": [{ "id": "tg-ops", "type": "telegram", "enabled": true, + "botToken": "tg-bot-token-value", "chatId": "-100200" }] + }), + ) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + assert_eq!(payload["value"][0]["botToken"], "***", "{payload}"); + assert_eq!(payload["value"][0]["chatId"], "-100200", "{payload}"); + assert!(!payload.to_string().contains("tg-bot-token-value")); + + let rows = fixture.outbox().await; + assert_eq!(rows.len(), 1, "one settings-change message"); + assert_eq!( + rows[0].payload["changes"][0]["value"], payload["value"], + "the row carries the answer's redacted value" + ); + assert!(!rows[0].payload.to_string().contains("tg-bot-token-value")); + assert_eq!( + fixture.settings_file()["admin"]["notifications"]["targets"][0]["botToken"], + serde_yaml::Value::String("tg-bot-token-value".to_owned()), + "the file keeps the value" + ); +} + #[tokio::test] async fn a_workers_change_is_restart_required() { let fixture = TestMcp::start().await;