From 4d74841c668c5506ab0f12172a67d3859356fad2 Mon Sep 17 00:00:00 2001 From: saket0187 Date: Thu, 3 Dec 2026 22:54:19 +0530 Subject: [PATCH] fix(admin): keep the admin audit log private to its owner (cherry picked from commit b3f0cacd8e608ea9dda84553bf0e9b9efe7b42aa) --- .changeset/admin-audit-owner-only.md | 6 + crates/nostream-admin/src/state.rs | 139 ++++++++++++- crates/nostream-admin/tests/audit.rs | 196 ++++++++++++++++-- .../decisions/0014-admin-http-surface.md | 9 + 4 files changed, 323 insertions(+), 27 deletions(-) create mode 100644 .changeset/admin-audit-owner-only.md diff --git a/.changeset/admin-audit-owner-only.md b/.changeset/admin-audit-owner-only.md new file mode 100644 index 000000000..f1571fa9a --- /dev/null +++ b/.changeset/admin-audit-owner-only.md @@ -0,0 +1,6 @@ +--- +--- + +fix(admin): keep the admin audit log private to its owner (#1187) + +`/admin-audit.jsonl`, which records admin actions and console client addresses, was created at `0666` less the umask (`0644` under the usual `022`, readable by any local account that can reach the config directory), and each compaction renamed a staging file created the same way over it. The append and the compaction now ask for `0600` at creation and set a regular file's permission bits to exactly `0600` through the open descriptor before writing, and the compaction replaces a leftover staging file instead of reusing it. Deliberate limits: the config directory keeps its mode; a wider mode an operator sets on the log is narrowed on the next append; a log another account owns gets no entry, and the relay logs a warning; a non-regular target such as a `/dev/null` link keeps its mode; and a reader that opened the log while it was wider keeps reading new entries through it until the next compaction. diff --git a/crates/nostream-admin/src/state.rs b/crates/nostream-admin/src/state.rs index d745b1122..c35668c54 100644 --- a/crates/nostream-admin/src/state.rs +++ b/crates/nostream-admin/src/state.rs @@ -616,14 +616,16 @@ impl AdminState { source, })?; } - let mut file = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(&path) + let mut file = open_private(std::fs::OpenOptions::new().create(true).append(true), &path) .map_err(|source| AdminError::Io { - path: path.clone(), - source, - })?; + path: path.clone(), + source, + })?; + #[cfg(unix)] + owner_only(&file).map_err(|source| AdminError::Io { + path: path.clone(), + source, + })?; let line = format!("{entry}\n"); std::io::Write::write_all(&mut file, line.as_bytes()).map_err(|source| AdminError::Io { path: path.clone(), @@ -815,10 +817,46 @@ fn write_audit_lines(path: &Path, lines: &[Value]) -> Result<(), AdminError> { .map(|line| format!("{line}\n")) .collect::>() .concat(); - std::fs::write(path, body).map_err(|source| AdminError::Io { + let io = |source| AdminError::Io { path: path.to_path_buf(), source, - }) + }; + // A leftover staging file would keep its mode, and any reader's descriptor, through a truncate. + match std::fs::remove_file(path) { + Err(source) if source.kind() != std::io::ErrorKind::NotFound => return Err(io(source)), + _ => {} + } + let mut file = open_private( + std::fs::OpenOptions::new().write(true).create_new(true), + path, + ) + .map_err(io)?; + #[cfg(unix)] + owner_only(&file).map_err(io)?; + std::io::Write::write_all(&mut file, body.as_bytes()).map_err(io) +} + +/// Opens with `options`, asking for mode `0600` (less the umask) for a file the open creates, so it +/// never has group or other bits; [`owner_only`] then sets the final bits. +fn open_private(options: &mut std::fs::OpenOptions, path: &Path) -> std::io::Result { + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + options.open(path) +} + +/// Sets a regular audit file's permission bits to `0600` before anything is written to it, whatever +/// the umask or an earlier build left; another target (a `/dev/null` link) is left alone. +#[cfg(unix)] +fn owner_only(file: &std::fs::File) -> std::io::Result<()> { + use std::os::unix::fs::PermissionsExt; + let metadata = file.metadata()?; + if metadata.is_file() && metadata.permissions().mode() & 0o777 != 0o600 { + file.set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + Ok(()) } /// `new Date().toISOString()` for a millisecond clock reading. @@ -855,6 +893,89 @@ mod tests { use super::*; + // `umask` is process-wide, so the case re-runs in a child under it; only the child asserts. + #[cfg(unix)] + fn is_child_under_umask(case: &str, umask: &str) -> bool { + const CHILD: &str = "NOSTREAM_ADMIN_STATE_UMASK_CHILD"; + if std::env::var_os(CHILD).is_some() { + return true; + } + let output = std::process::Command::new("/bin/sh") + .arg("-c") + .arg(r#"umask "$2"; exec "$0" --exact "$1""#) + .arg(std::env::current_exe().expect("the test binary")) + .arg(case) + .arg(umask) + .env(CHILD, "1") + .output() + .expect("the child test run"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("1 passed"), + "the child case failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr) + ); + false + } + + #[cfg(unix)] + fn mode(metadata: &std::fs::Metadata) -> String { + use std::os::unix::fs::PermissionsExt; + format!("{:o}", metadata.permissions().mode() & 0o777) + } + + #[cfg(unix)] + #[test] + fn a_file_the_audit_writers_create_starts_owner_only() { + if !is_child_under_umask( + "state::tests::a_file_the_audit_writers_create_starts_owner_only", + "022", + ) { + return; + } + let temp = tempfile::tempdir().unwrap(); + + let file = open_private( + std::fs::OpenOptions::new().write(true).create_new(true), + &temp.path().join("admin-audit.jsonl"), + ) + .unwrap(); + + assert_eq!( + mode(&file.metadata().unwrap()), + "600", + "the file is private before owner_only runs" + ); + } + + #[cfg(unix)] + #[test] + fn a_compacted_log_is_0600_under_an_owner_stripping_umask() { + if !is_child_under_umask( + "state::tests::a_compacted_log_is_0600_under_an_owner_stripping_umask", + "0400", + ) { + return; + } + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir().unwrap(); + std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let path = temp.path().join("admin-audit.jsonl"); + + write_audit_lines(&path, &[serde_json::json!({ "action": "admin.test" })]).unwrap(); + + assert_eq!( + mode(&std::fs::metadata(&path).unwrap()), + "600", + "the owner can read the log it wrote" + ); + assert!( + std::fs::read_to_string(&path) + .unwrap() + .contains("admin.test") + ); + } + /// The bearer credential must not reach a log through `Debug`: the derived impl printed it /// as decimal bytes. #[test] diff --git a/crates/nostream-admin/tests/audit.rs b/crates/nostream-admin/tests/audit.rs index e8beb8b6f..55e1a8670 100644 --- a/crates/nostream-admin/tests/audit.rs +++ b/crates/nostream-admin/tests/audit.rs @@ -5,13 +5,22 @@ //! |---|---| //! | `a_logout_appends_exactly_one_line` | the unauthenticated `POST /logout` that reaches the append writes one line | //! | `the_cap_survives_two_thousand_appends` | a file at the cap stays at the cap, with the newest entries kept | +//! | `a_new_audit_file_is_owner_only` | with a `022` umask the append creates the file `0600` | +//! | `an_append_narrows_an_audit_file_left_at_another_mode` | a `0644` or `0200` file an earlier build left is exactly `0600` after the next append, which still lands | +//! | `an_append_leaves_a_target_that_is_not_a_file_alone` | a target that is not a regular file (a drained pipe here) keeps its mode and still gets the entry | +//! | `the_compaction_keeps_the_file_owner_only` | with a `022` umask a `0600` file is still `0600` after a compaction renames over it | +//! | `the_compaction_replaces_a_stale_staging_file` | a `0644` staging file an interrupted compaction left is replaced, not reused: a reader holding it sees none of the log, which is `0600` | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod common; +use std::os::unix::fs::PermissionsExt; + use common::TestServer; +const UMASK_CHILD: &str = "NOSTREAM_ADMIN_AUDIT_MODE_CHILD"; + fn audit_path(server: &TestServer) -> std::path::PathBuf { server.config_dir.join("admin-audit.jsonl") } @@ -22,6 +31,61 @@ fn line_count(path: &std::path::Path) -> usize { .unwrap_or(0) } +fn mode(path: &std::path::Path) -> String { + let mode = std::fs::metadata(path) + .expect("the file exists") + .permissions() + .mode(); + format!("{:o}", mode & 0o777) +} + +fn seed_at_cap(path: &std::path::Path) { + let seeded: String = (0..nostream_admin::state::MAX_AUDIT_ENTRIES) + .map(|index| { + format!( + "{{\"id\":\"seed-{index}\",\"at\":\"2026-11-19T00:00:00Z\",\"action\":\"seed\"}}\n" + ) + }) + .collect(); + std::fs::write(path, seeded).unwrap(); +} + +fn append_through_a_compaction(server: &TestServer) { + for index in 0..nostream_admin::state::AUDIT_COMPACT_EVERY { + server + .state + .append_audit( + "admin.test", + None, + Some(serde_json::json!({ "index": index })), + ) + .unwrap(); + } +} + +// `umask` is process-wide, so the case re-runs in a child under `022`; only the child asserts. +fn is_umask_child(case: &str) -> bool { + if std::env::var_os(UMASK_CHILD).is_some() { + return true; + } + let executable = std::env::current_exe().expect("the test binary"); + let output = std::process::Command::new("/bin/sh") + .arg("-c") + .arg(r#"umask 022; exec "$0" --exact "$1""#) + .arg(&executable) + .arg(case) + .env(UMASK_CHILD, "1") + .output() + .expect("the child test run"); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("1 passed"), + "the child case failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr) + ); + false +} + #[tokio::test] async fn a_logout_appends_exactly_one_line() { let server = TestServer::start().await; @@ -48,26 +112,10 @@ async fn the_cap_survives_two_thousand_appends() { let path = audit_path(&server); // A file already at the cap, as a long-running daemon leaves it. - let seeded: String = (0..nostream_admin::state::MAX_AUDIT_ENTRIES) - .map(|index| { - format!( - "{{\"id\":\"seed-{index}\",\"at\":\"2026-11-19T00:00:00Z\",\"action\":\"seed\"}}\n" - ) - }) - .collect(); - std::fs::write(&path, seeded).unwrap(); + seed_at_cap(&path); assert_eq!(line_count(&path), nostream_admin::state::MAX_AUDIT_ENTRIES); - for index in 0..nostream_admin::state::AUDIT_COMPACT_EVERY { - server - .state - .append_audit( - "admin.test", - None, - Some(serde_json::json!({ "index": index })), - ) - .unwrap(); - } + append_through_a_compaction(&server); assert_eq!( line_count(&path), @@ -83,3 +131,115 @@ async fn the_cap_survives_two_thousand_appends() { let last: serde_json::Value = serde_json::from_str(&last).unwrap(); assert_eq!(last["action"], "admin.test", "the newest entry is kept"); } + +#[tokio::test] +async fn a_new_audit_file_is_owner_only() { + if !is_umask_child("a_new_audit_file_is_owner_only") { + return; + } + let server = TestServer::start().await; + let path = audit_path(&server); + + server.request("POST", "/admin/logout", &[], None).await; + assert_eq!(mode(&path), "600", "the file the append created is private"); +} + +#[tokio::test] +async fn an_append_narrows_an_audit_file_left_at_another_mode() { + let server = TestServer::start().await; + let path = audit_path(&server); + + for left in [0o644, 0o200] { + std::fs::write( + &path, + "{\"id\":\"old\",\"at\":\"2026-11-19T00:00:00Z\",\"action\":\"seed\"}\n", + ) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(left)).unwrap(); + + server.request("POST", "/admin/logout", &[], None).await; + assert_eq!( + mode(&path), + "600", + "a {left:o} file is narrowed by the append" + ); + assert_eq!(line_count(&path), 2, "the entry lands in the old file"); + } +} + +#[tokio::test] +async fn an_append_leaves_a_target_that_is_not_a_file_alone() { + let server = TestServer::start().await; + let path = audit_path(&server); + + let made = std::process::Command::new("mkfifo") + .arg(&path) + .status() + .expect("mkfifo runs"); + assert!(made.success(), "a pipe at the audit path"); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + let reader = { + let path = path.clone(); + std::thread::spawn(move || std::fs::read_to_string(path).unwrap()) + }; + + server.state.append_audit("admin.test", None, None).unwrap(); + + assert!( + reader.join().unwrap().contains("admin.test"), + "the entry reached the pipe" + ); + assert_eq!(mode(&path), "644", "the pipe keeps the mode it was given"); +} + +#[tokio::test] +async fn the_compaction_keeps_the_file_owner_only() { + if !is_umask_child("the_compaction_keeps_the_file_owner_only") { + return; + } + let server = TestServer::start().await; + let path = audit_path(&server); + + seed_at_cap(&path); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + + append_through_a_compaction(&server); + + assert_eq!( + line_count(&path), + nostream_admin::state::MAX_AUDIT_ENTRIES, + "the compaction ran" + ); + assert_eq!(mode(&path), "600", "the compacted log is still private"); +} + +#[tokio::test] +async fn the_compaction_replaces_a_stale_staging_file() { + let server = TestServer::start().await; + let path = audit_path(&server); + let staging = server.config_dir.join("admin-audit.jsonl.compact"); + + seed_at_cap(&path); + std::fs::write(&staging, "stale\n").unwrap(); + std::fs::set_permissions(&staging, std::fs::Permissions::from_mode(0o644)).unwrap(); + let mut held = std::fs::File::open(&staging).unwrap(); + + append_through_a_compaction(&server); + + assert_eq!( + line_count(&path), + nostream_admin::state::MAX_AUDIT_ENTRIES, + "the compaction ran" + ); + let mut seen = String::new(); + std::io::Read::read_to_string(&mut held, &mut seen).unwrap(); + assert_eq!( + seen, "stale\n", + "a reader of the old staging file sees none of the log" + ); + assert_eq!( + mode(&path), + "600", + "the log does not take the stale file's mode" + ); +} diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 728ecfb7d..f1ccd7513 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -270,6 +270,15 @@ answers while a login verification is still in flight. by a compaction that runs once per `AUDIT_COMPACT_EVERY` (2,000) appends, reading once and renaming a fresh file into place. +The file's permission bits are owner read and write only (`0600`), whatever the umask. The append +opens it with that creation mode and, before writing, sets a regular file found with any other +permission bits to `0600` through the descriptor it opened, so each append also costs one `fstat`. A +file it cannot narrow (another account owns it) gets no entry, and the caller warns as for any other +audit write error. Only a regular file is narrowed, so a link to `/dev/null` keeps its mode. The +compaction removes any staging file an interrupted compaction left and opens and narrows its own the +same way before writing, because the rename gives the log the staging file's mode, and a truncated +leftover would keep both its own mode and any reader that had it open. + The first cut read, parsed and rewrote the whole file under a mutex on every call — and an unauthenticated `POST /logout` reaches it, so any caller could drive a full-file read and rewrite. Measured on the `audit` target's cap case (2,000 appends at a full file): **34.5 s** before,