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/write-protected-above-a-path.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
---

fix(admin): refuse a write above a protected value

`PATCH /admin/settings` and the MCP `settings_set` tool checked the paths the request named, so a write at a path that *holds* `admin.passwordHash` was allowed: replacing `admin` replaced the hash, and a settings write could take over the console. What is protected is now read from the stored document and from the document as it would be saved, and a write that moves one is refused with `Path is write-protected`, as `main`'s console already did (`settings-redaction.ts:56-86`, `patch-settings-controller.ts:92-100`).
16 changes: 16 additions & 0 deletions crates/nostream-admin/src/controllers/patch_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,22 @@ pub async fn apply(
});
};

// The paths of the request were checked above, but a change to a path that holds a
// protected value, such as replacing `admin`, writes that value too. Compare what would
// be saved with what is stored.
let changed_protected =
nostream_config::redaction::changed_write_protected_settings_paths(&user, &next_user);
if !changed_protected.is_empty() {
let issues: Vec<nostream_config::Issue> = changed_protected
.into_iter()
.map(|path| nostream_config::Issue::new(path, "Path is write-protected"))
.collect();
return Ok(SettingsWrite::Refused {
status: StatusCode::BAD_REQUEST,
body: validation_failed_body(&issues),
});
}

let validation = nostream_config::validate_document(&next_merged, &defaults);
if !validation.is_empty() {
return Ok(SettingsWrite::Refused {
Expand Down
35 changes: 35 additions & 0 deletions crates/nostream-admin/tests/write_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,3 +294,38 @@ async fn a_container_write_redacts_its_secrets_in_the_echo_and_the_row() {
);
}
}

/// A change to a path above `admin.passwordHash` writes that value too, so the guard compares
/// the stored document with what would be saved, not only the paths the request names
/// (`patch-settings-controller.ts:92-100`).
#[tokio::test]
async fn a_write_above_the_password_hash_is_refused() {
let server = TestServer::start().await;
let cookie = server.login().await;
let before = user_settings(&server)["admin"]["passwordHash"].clone();
assert!(!before.is_null(), "the fixture stores a hash");

let response = server
.send_json(
"PATCH",
"/admin/settings",
&cookie,
json!({ "path": "admin", "value": { "passwordHash": "scrypt$attacker" } }),
)
.await;
assert_eq!(response.status, 400, "{}", response.text());
assert!(
response.text().contains("Path is write-protected"),
"{}",
response.text()
);
assert_eq!(
user_settings(&server)["admin"]["passwordHash"],
before,
"the stored hash is unchanged"
);
assert!(
outbox_rows(&server).await.is_empty(),
"a refused write announces nothing"
);
}
54 changes: 54 additions & 0 deletions crates/nostream-config/src/redaction.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Secret classification and redaction. Mirrors `src/utils/settings-redaction.ts`.

use std::collections::{BTreeMap, BTreeSet};

use serde_yaml::Value;

/// Keys whose values are secrets wherever they appear.
Expand Down Expand Up @@ -94,6 +96,58 @@ pub fn is_write_protected_settings_path(path: &str) -> bool {
path == "admin.passwordHash" || path.ends_with(".passwordHash")
}

/// Every write-protected value in a settings document, by its path.
///
/// A request names the path it writes, but a path above a protected value (replacing `admin`,
/// which holds `admin.passwordHash`) writes it too, so what is protected is read from the
/// document as it would be saved, not from the paths of the request.
pub fn collect_write_protected_settings(settings: &Value) -> BTreeMap<String, Value> {
let mut found = BTreeMap::new();
collect_write_protected(settings, "", &mut found);
found
}

fn collect_write_protected(value: &Value, path: &str, found: &mut BTreeMap<String, Value>) {
match value {
Value::Sequence(entries) => {
for (index, entry) in entries.iter().enumerate() {
collect_write_protected(entry, &format!("{path}[{index}]"), found);
}
}
Value::Mapping(mapping) => {
for (key, entry) in mapping {
let Some(name) = key.as_str() else {
continue;
};
let child = if path.is_empty() {
name.to_owned()
} else {
format!("{path}.{name}")
};
if is_write_protected_settings_path(&child) {
found.insert(child, entry.clone());
} else {
collect_write_protected(entry, &child, found);
}
}
}
_ => {}
}
}

/// The write-protected paths whose value differs between two documents, added or removed ones
/// included.
pub fn changed_write_protected_settings_paths(before: &Value, after: &Value) -> Vec<String> {
let before = collect_write_protected_settings(before);
let after = collect_write_protected_settings(after);
let paths: BTreeSet<&String> = before.keys().chain(after.keys()).collect();
paths
.into_iter()
.filter(|path| before.get(*path) != after.get(*path))
.cloned()
.collect()
}

/// Redacts one value by path.
pub fn redact_settings_value(path: &str, value: &Value) -> Value {
let path = normalize_settings_path(path);
Expand Down
59 changes: 59 additions & 0 deletions crates/nostream-config/tests/redaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

use nostream_config::path::get_by_path;
use nostream_config::redaction::{
changed_write_protected_settings_paths, collect_write_protected_settings,
is_sensitive_settings_path, is_write_protected_settings_path, redact_settings_secrets,
redact_settings_value,
};
Expand Down Expand Up @@ -362,3 +363,61 @@ fn the_walk_classifies_each_value_as_its_full_path_does() {
Value::String("https://g.example/hook".to_owned())
);
}

/// The document comparison behind the write-protected refusal: a path above a protected value
/// writes that value too, so what is protected is read from the document, not from the paths
/// of the request (`settings-redaction.ts:56-86`).
#[test]
fn a_write_above_a_protected_value_moves_it() {
let before = document(
"admin:\n passwordHash: scrypt:old\n notifications:\n targets: []\nother: 1\n",
);
assert_eq!(
collect_write_protected_settings(&before)
.keys()
.collect::<Vec<_>>(),
vec!["admin.passwordHash"]
);

let replaced = document("admin:\n passwordHash: scrypt:new\n");
assert_eq!(
changed_write_protected_settings_paths(&before, &replaced),
vec!["admin.passwordHash".to_owned()],
"replacing `admin` writes its hash"
);

let removed = document("admin:\n notifications:\n targets: []\n");
assert_eq!(
changed_write_protected_settings_paths(&before, &removed),
vec!["admin.passwordHash".to_owned()],
"removing the value counts too"
);

assert!(
changed_write_protected_settings_paths(&before, &before).is_empty(),
"an unchanged document moves nothing"
);
assert!(
changed_write_protected_settings_paths(
&before,
&document("admin:\n passwordHash: scrypt:old\n"),
)
.is_empty(),
"a write elsewhere under `admin` leaves the hash alone"
);
}

#[test]
fn protected_values_are_collected_inside_lists() {
let listed = document("accounts:\n - passwordHash: one\n - passwordHash: two\n");
assert_eq!(
collect_write_protected_settings(&listed)
.keys()
.cloned()
.collect::<Vec<_>>(),
vec![
"accounts[0].passwordHash".to_owned(),
"accounts[1].passwordHash".to_owned(),
]
);
}
Loading