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/admin-audit-owner-only.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
---

fix(admin): keep the admin audit log private to its owner (#1187)

`<config>/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.
139 changes: 130 additions & 9 deletions crates/nostream-admin/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -815,10 +817,46 @@ fn write_audit_lines(path: &Path, lines: &[Value]) -> Result<(), AdminError> {
.map(|line| format!("{line}\n"))
.collect::<Vec<String>>()
.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<std::fs::File> {
#[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.
Expand Down Expand Up @@ -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]
Expand Down
196 changes: 178 additions & 18 deletions crates/nostream-admin/tests/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand All @@ -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;
Expand All @@ -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),
Expand All @@ -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"
);
}
Loading
Loading