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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/redact-container-settings-writes.md
Original file line number Diff line number Diff line change
@@ -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.
84 changes: 84 additions & 0 deletions crates/nostream-admin/tests/write_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]

Expand Down Expand Up @@ -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"
);
}
}
142 changes: 98 additions & 44 deletions crates/nostream-config/src/redaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>()
.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<usize>);

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.
Expand All @@ -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, "")
}
Loading
Loading