Skip to main content

shellfirm/
audit.rs

1//! Audit trail — optional local log of every intercepted command.
2//!
3//! Records are JSON Lines (one JSON object per line). Each record contains
4//! the [`AuditEvent`] fields written by the caller, plus metadata collected
5//! automatically at write time ([`AuditMeta`]: user, host, cwd, git repo and
6//! branch, schema version) and optional caller-provided details
7//! ([`AuditExtra`]: policy sources, effective challenge, deny reason).
8//!
9//! Writes are safe under concurrency: each record is serialized into one
10//! buffer and written with a single `write()` on an `O_APPEND` descriptor,
11//! under an exclusive `flock` on Unix, so lines from parallel writers never
12//! interleave. The file is created with mode `0600`. When the log grows past
13//! [`DEFAULT_MAX_AUDIT_BYTES`] it is rotated: `audit.log` becomes
14//! `audit.log.1`, `.1` becomes `.2`, … and only the newest
15//! [`DEFAULT_MAX_AUDIT_FILES`] generations are kept (configurable with the
16//! `audit_max_files` setting of the log's configuration directory, see
17//! [`max_files_for`]). `audit show` reads
18//! every generation.
19//!
20//! A stored command is capped at [`MAX_STORED_COMMAND_BYTES`]; longer
21//! commands are truncated and the record carries `command_bytes` and the
22//! `command_sha256` of the full command, so a few huge commands can never
23//! flush the history.
24//!
25//! Secrets are redacted before a command is stored (see [`redact_secrets`]):
26//! `mysql -pSECRET`, `--password=…`, `PGPASSWORD=…` and other
27//! `*_PASSWORD` / `*_TOKEN` / `*_SECRET` / `*_KEY` assignments, `user:pass@`
28//! in URLs, `Authorization:` headers, `curl -u user:pass` and well-known
29//! token formats (AWS `AKIA…`, GitHub `ghp_…`, Slack `xox…-`) become `***`.
30//! A redacted record carries `command_redacted: true`, and its
31//! `command_sha256` is computed over the **original** command, so a known
32//! command can still be matched against the log without storing the secret.
33//!
34//! Identity: `user` is the account name of the real uid (from the password
35//! database, falling back to `$USER`), `uid` is the numeric uid, and
36//! `env_user` records `$USER` when it differs from `user`.
37//!
38//! Older records (without the newer fields) are still readable through
39//! [`AuditEntry`].
40
41use std::{
42    fs::{self, OpenOptions},
43    io::Write,
44    path::{Path, PathBuf},
45};
46
47use crate::error::{Error, Result};
48use serde_derive::{Deserialize, Serialize};
49
50use crate::checks::Severity;
51
52/// Version of the on-disk record format written by this build.
53/// - 1 (implicit, no field): original format
54/// - 2: adds `schema_version`, `user`, `hostname`, `cwd`, `git_repo`,
55///   `git_branch` and the optional [`AuditExtra`] fields.
56/// - 3: `user` comes from the uid (not `$USER`); adds `uid`, `env_user`,
57///   `escalation_reasons`, `command_bytes`, `command_sha256`,
58///   `command_truncated`, `command_redacted` and the `NoTerminal` outcome.
59/// - 4: adds `version` (the shellfirm version that wrote the record).
60pub const AUDIT_SCHEMA_VERSION: u32 = 4;
61
62/// Size after which `audit.log` is rotated to `audit.log.1` (10 MiB).
63pub const DEFAULT_MAX_AUDIT_BYTES: u64 = 10 * 1024 * 1024;
64
65/// Rotated generations kept by default (`audit.log.1` … `audit.log.5`).
66pub const DEFAULT_MAX_AUDIT_FILES: usize = 5;
67
68/// Longest command stored verbatim in a record (8 KiB). Longer commands are
69/// truncated (at a character boundary) and hashed.
70pub const MAX_STORED_COMMAND_BYTES: usize = 8 * 1024;
71
72/// How many rotated generations are kept for the log at `audit_path`.
73///
74/// It is the `audit_max_files` setting of the configuration directory the
75/// log lives in (`settings.yaml` next to `audit.log`), so `--config-dir DIR`
76/// and `SHELLFIRM_CONFIG_DIR` rotate with DIR's own setting. The file is
77/// read only when a rotation is due. The value is clamped to `1..=100`: at
78/// least one rotated generation is always kept, so rotation never deletes
79/// the history it just rotated (`0`, which the settings parser rejects,
80/// means the default). Unset or unreadable: [`DEFAULT_MAX_AUDIT_FILES`].
81#[must_use]
82pub fn max_files_for(audit_path: &Path) -> usize {
83    let configured = audit_path
84        .parent()
85        .map(|d| d.join("settings.yaml"))
86        .and_then(|p| fs::read_to_string(p).ok())
87        .and_then(|c| serde_yaml::from_str::<serde_yaml::Value>(&c).ok())
88        .and_then(|v| v.get("audit_max_files").and_then(serde_yaml::Value::as_u64))
89        .and_then(|n| usize::try_from(n).ok())
90        .filter(|n| *n > 0)
91        .unwrap_or(DEFAULT_MAX_AUDIT_FILES);
92    clamp_max_files(configured)
93}
94
95const fn clamp_max_files(n: usize) -> usize {
96    if n == 0 {
97        1
98    } else if n > MAX_AUDIT_FILES_LIMIT {
99        MAX_AUDIT_FILES_LIMIT
100    } else {
101        n
102    }
103}
104
105/// Largest accepted `audit_max_files`.
106pub const MAX_AUDIT_FILES_LIMIT: usize = 100;
107
108/// The number of rotated generations kept for an `audit_max_files`
109/// setting (clamped like [`max_files_for`]).
110#[must_use]
111pub const fn max_files(setting: usize) -> usize {
112    clamp_max_files(setting)
113}
114
115/// The outcome of a challenge interaction.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub enum AuditOutcome {
118    Allowed,
119    Denied,
120    /// The check matched but was skipped because its severity was below
121    /// the configured `min_severity` threshold.
122    Skipped,
123    /// The challenge was declined or aborted by a human (Esc, Ctrl-C, a
124    /// wrong answer given up on). The record is written once, after the
125    /// prompt ends; a process killed with `SIGKILL` while the prompt is
126    /// shown writes no record (the command does not run either).
127    Cancelled,
128    /// The decision was handed back to a human (e.g. an AI-agent hook
129    /// returned "ask" so the tool's own permission prompt is shown).
130    Asked,
131    /// Blocked without asking because no terminal was available to answer
132    /// the challenge (fail closed). Distinct from `Cancelled`, which is a
133    /// human declining or aborting.
134    NoTerminal,
135}
136
137impl std::fmt::Display for AuditOutcome {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        match self {
140            Self::Allowed => write!(f, "ALLOWED"),
141            Self::Denied => write!(f, "DENIED"),
142            Self::Skipped => write!(f, "SKIPPED"),
143            Self::Cancelled => write!(f, "CANCELLED"),
144            Self::Asked => write!(f, "ASKED"),
145            Self::NoTerminal => write!(f, "NO-TTY"),
146        }
147    }
148}
149
150/// The outcome names accepted by [`AuditOutcome::parse`] (for help texts).
151pub const OUTCOME_VALUES: &str = "allowed, denied, skipped, cancelled, asked, no-terminal";
152
153impl AuditOutcome {
154    /// Parse an outcome name (case-insensitive).
155    ///
156    /// # Errors
157    /// Returns an error listing the valid values.
158    pub fn parse(s: &str) -> Result<Self> {
159        match s.to_lowercase().as_str() {
160            "allowed" => Ok(Self::Allowed),
161            "denied" => Ok(Self::Denied),
162            "skipped" => Ok(Self::Skipped),
163            "cancelled" | "canceled" => Ok(Self::Cancelled),
164            "asked" | "ask" => Ok(Self::Asked),
165            "noterminal" | "no-terminal" | "no_terminal" | "no-tty" | "notty" => {
166                Ok(Self::NoTerminal)
167            }
168            _ => Err(Error::Config(format!(
169                "invalid outcome '{s}'. Valid values: {OUTCOME_VALUES}"
170            ))),
171        }
172    }
173}
174
175/// A single audit log entry, as written by the interception paths.
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct AuditEvent {
178    /// Unique identifier of the decision. Older versions wrote a
179    /// pre-challenge record and a final record with the same id;
180    /// `audit show` still collapses those pairs.
181    pub event_id: String,
182    pub timestamp: String,
183    pub command: String,
184    pub matched_ids: Vec<String>,
185    pub challenge_type: String,
186    pub outcome: AuditOutcome,
187    pub context_labels: Vec<String>,
188    /// The highest severity among the matched checks.
189    pub severity: Severity,
190    /// Name of the AI agent that originated this command (if any).
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub agent_name: Option<String>,
193    /// Session ID of the AI agent (if any).
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub agent_session_id: Option<String>,
196    /// Blast radius scope (e.g. "PROJECT", "MACHINE").
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub blast_radius_scope: Option<String>,
199    /// Blast radius detail description.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub blast_radius_detail: Option<String>,
202    /// Number of challenge attempts made before the outcome (if tracked).
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub attempts: Option<u32>,
205}
206
207/// Metadata collected automatically by [`log_event`] for every record.
208#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
209pub struct AuditMeta {
210    pub schema_version: u32,
211    /// The shellfirm version that wrote the record (schema 4 and later).
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub version: Option<String>,
214    /// Account name of the real uid (password database), or `$USER` when
215    /// the lookup fails.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub user: Option<String>,
218    /// Numeric real uid (Unix).
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub uid: Option<u32>,
221    /// `$USER` / `$LOGNAME`, recorded only when it differs from `user`.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub env_user: Option<String>,
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub hostname: Option<String>,
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub cwd: Option<String>,
228    /// Top-level directory of the git repository containing `cwd`.
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub git_repo: Option<String>,
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub git_branch: Option<String>,
233}
234
235/// Optional details a caller can attach with [`log_event_with`].
236#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
237pub struct AuditExtra {
238    /// Paths of the policy files (org or `.shellfirm.yaml`) that enforce
239    /// the matched checks (for a policy deny: the files that deny them).
240    #[serde(default, skip_serializing_if = "Vec::is_empty")]
241    pub policy_sources: Vec<String>,
242    /// The challenge actually presented (after all escalation layers), as
243    /// opposed to `challenge_type` (the configured base challenge).
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    pub effective_challenge: Option<String>,
246    /// Why the command was denied: `"policy_deny"` (a policy `deny` entry),
247    /// `"user_deny"` (the personal `deny_patterns_ids`), or a caller-set
248    /// reason such as `"agent_auto_deny"`, `"no_tty"`, `"cancelled"` or
249    /// `"fail_closed"` (see [`deny_reason`]).
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub deny_reason: Option<String>,
252    /// Ids of matched checks that are enforced by the project policy.
253    #[serde(default, skip_serializing_if = "Vec::is_empty")]
254    pub policy_check_ids: Vec<String>,
255    /// Why the challenge was raised above the base challenge (e.g.
256    /// "protected branch `main`", "severity High").
257    #[serde(default, skip_serializing_if = "Vec::is_empty")]
258    pub escalation_reasons: Vec<String>,
259    /// The agent's id for the tool call (Claude Code `tool_use_id`).
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub tool_use_id: Option<String>,
262}
263
264/// The values of [`AuditExtra::deny_reason`].
265pub mod deny_reason {
266    use super::AuditOutcome;
267
268    /// A matched id is in a policy `deny` list (org or `.shellfirm.yaml`).
269    pub const POLICY_DENY: &str = "policy_deny";
270    /// A matched id is in the personal `deny_patterns_ids`.
271    pub const USER_DENY: &str = "user_deny";
272    /// An AI-agent hook denied it because the severity reached
273    /// `agent.auto_deny_severity`.
274    pub const AGENT_AUTO_DENY: &str = "agent_auto_deny";
275    /// No terminal was available to answer the challenge (fail closed).
276    pub const NO_TTY: &str = "no_tty";
277    /// A human cancelled the challenge (Esc, Ctrl-C, Ctrl-D / end of
278    /// input). The interactive prompt keeps asking after a wrong answer,
279    /// so a shell-hook challenge only ever ends unanswered this way.
280    pub const CANCELLED: &str = "cancelled";
281    /// The challenge was answered wrongly and given up. Written by older
282    /// versions for every cancelled challenge (they could not tell a
283    /// cancel from a wrong answer); read it as "not passed".
284    pub const CHALLENGE_FAILED: &str = "challenge_failed";
285
286    /// The deny reason implied by an outcome on its own (`NoTerminal` →
287    /// [`NO_TTY`], `Cancelled` → [`CANCELLED`]); `None` for the others.
288    #[must_use]
289    pub const fn for_outcome(outcome: &AuditOutcome) -> Option<&'static str> {
290        match outcome {
291            AuditOutcome::NoTerminal => Some(NO_TTY),
292            AuditOutcome::Cancelled => Some(CANCELLED),
293            _ => None,
294        }
295    }
296}
297
298impl AuditExtra {
299    /// Build the extra fields for one decision.
300    ///
301    /// - `merged`: the merged project policy of the pipeline run.
302    /// - `user_deny`: the user's personal `deny_patterns_ids`.
303    /// - `matched_ids`: ids of the active matches.
304    /// - `denied`: whether the command was denied by a deny list.
305    /// - `effective_challenge` / `escalation_reasons`: from the challenge
306    ///   display.
307    ///
308    /// `deny_reason` is `policy_deny` when a matched id is in the policy
309    /// deny list, otherwise `user_deny` when it is in the personal deny
310    /// list (callers set `agent_auto_deny`, `no_tty`, … themselves).
311    #[must_use]
312    pub fn for_decision(
313        merged: &crate::policy::MergedPolicy,
314        user_deny: &[String],
315        matched_ids: &[String],
316        denied: bool,
317        effective_challenge: Option<String>,
318        escalation_reasons: Vec<String>,
319    ) -> Self {
320        let deny_reason = if !denied {
321            None
322        } else if matched_ids.iter().any(|id| merged.is_denied(id)) {
323            Some(deny_reason::POLICY_DENY.to_string())
324        } else if matched_ids.iter().any(|id| user_deny.contains(id)) {
325            Some(deny_reason::USER_DENY.to_string())
326        } else {
327            Some("deny".to_string())
328        };
329        let policy_check_ids: Vec<String> = matched_ids
330            .iter()
331            .filter(|id| merged.is_enforced(id))
332            .cloned()
333            .collect();
334        // The files that name the relevant ids: for a policy deny the
335        // files that deny a matched id, otherwise those enforcing a match.
336        let relevant: Vec<&String> = if deny_reason.as_deref() == Some(deny_reason::POLICY_DENY) {
337            matched_ids
338                .iter()
339                .filter(|id| merged.is_denied(id))
340                .collect()
341        } else {
342            policy_check_ids.iter().collect()
343        };
344        let mut policy_sources: Vec<String> = Vec::new();
345        for id in relevant {
346            for p in merged.sources_for(id) {
347                let p = p.display().to_string();
348                if !policy_sources.contains(&p) {
349                    policy_sources.push(p);
350                }
351            }
352        }
353        Self {
354            policy_sources,
355            effective_challenge,
356            deny_reason,
357            policy_check_ids,
358            escalation_reasons,
359            tool_use_id: None,
360        }
361    }
362}
363
364/// Size information written when a command is longer than
365/// [`MAX_STORED_COMMAND_BYTES`].
366#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
367#[allow(clippy::struct_field_names)]
368struct CommandDigest {
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    command_bytes: Option<usize>,
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    command_sha256: Option<String>,
373    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
374    command_truncated: bool,
375    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
376    command_redacted: bool,
377}
378
379#[derive(Serialize)]
380struct AuditRecordOut<'a> {
381    #[serde(flatten)]
382    event: &'a AuditEvent,
383    #[serde(flatten)]
384    meta: AuditMeta,
385    #[serde(flatten)]
386    extra: &'a AuditExtra,
387    #[serde(flatten)]
388    digest: CommandDigest,
389}
390
391/// Read model for one audit record. Every field is optional so records
392/// written by older versions (or by hand) still load.
393#[derive(Debug, Clone, Default, Serialize, Deserialize)]
394#[serde(default)]
395pub struct AuditEntry {
396    pub event_id: String,
397    pub timestamp: String,
398    pub command: String,
399    pub matched_ids: Vec<String>,
400    pub challenge_type: String,
401    pub outcome: Option<AuditOutcome>,
402    pub context_labels: Vec<String>,
403    pub severity: Option<Severity>,
404    #[serde(skip_serializing_if = "Option::is_none")]
405    pub agent_name: Option<String>,
406    #[serde(skip_serializing_if = "Option::is_none")]
407    pub agent_session_id: Option<String>,
408    /// The agent's id for the tool call (Claude Code `tool_use_id`).
409    #[serde(skip_serializing_if = "Option::is_none")]
410    pub tool_use_id: Option<String>,
411    #[serde(skip_serializing_if = "Option::is_none")]
412    pub blast_radius_scope: Option<String>,
413    #[serde(skip_serializing_if = "Option::is_none")]
414    pub blast_radius_detail: Option<String>,
415    #[serde(skip_serializing_if = "Option::is_none")]
416    pub attempts: Option<u32>,
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub schema_version: Option<u32>,
419    /// The shellfirm version that wrote the record (schema 4 and later).
420    #[serde(default, skip_serializing_if = "Option::is_none")]
421    pub version: Option<String>,
422    #[serde(skip_serializing_if = "Option::is_none")]
423    pub user: Option<String>,
424    #[serde(skip_serializing_if = "Option::is_none")]
425    pub uid: Option<u32>,
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub env_user: Option<String>,
428    #[serde(skip_serializing_if = "Option::is_none")]
429    pub hostname: Option<String>,
430    #[serde(skip_serializing_if = "Option::is_none")]
431    pub cwd: Option<String>,
432    #[serde(skip_serializing_if = "Option::is_none")]
433    pub git_repo: Option<String>,
434    #[serde(skip_serializing_if = "Option::is_none")]
435    pub git_branch: Option<String>,
436    #[serde(skip_serializing_if = "Vec::is_empty")]
437    pub policy_sources: Vec<String>,
438    #[serde(skip_serializing_if = "Option::is_none")]
439    pub effective_challenge: Option<String>,
440    #[serde(skip_serializing_if = "Option::is_none")]
441    pub deny_reason: Option<String>,
442    #[serde(skip_serializing_if = "Vec::is_empty")]
443    pub policy_check_ids: Vec<String>,
444    #[serde(skip_serializing_if = "Vec::is_empty")]
445    pub escalation_reasons: Vec<String>,
446    #[serde(skip_serializing_if = "Option::is_none")]
447    pub command_bytes: Option<usize>,
448    #[serde(skip_serializing_if = "Option::is_none")]
449    pub command_sha256: Option<String>,
450    #[serde(skip_serializing_if = "std::ops::Not::not")]
451    pub command_truncated: bool,
452    #[serde(skip_serializing_if = "std::ops::Not::not")]
453    pub command_redacted: bool,
454}
455
456// ---------------------------------------------------------------------------
457// Metadata collection
458// ---------------------------------------------------------------------------
459
460fn env_user() -> Option<String> {
461    ["USER", "LOGNAME", "USERNAME"]
462        .iter()
463        .find_map(|k| std::env::var(k).ok().filter(|v| !v.is_empty()))
464}
465
466/// Real uid of this process (Unix).
467#[must_use]
468pub fn current_uid() -> Option<u32> {
469    #[cfg(unix)]
470    {
471        // SAFETY: getuid has no preconditions and cannot fail.
472        Some(unsafe { libc::getuid() })
473    }
474    #[cfg(not(unix))]
475    {
476        None
477    }
478}
479
480/// Account name for `uid` from the password database.
481#[cfg(unix)]
482fn passwd_name(uid: u32) -> Option<String> {
483    let mut buf = vec![0 as libc::c_char; 4096];
484    // SAFETY: an all-zero passwd struct is a valid out-parameter.
485    let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
486    let mut result: *mut libc::passwd = std::ptr::null_mut();
487    // SAFETY: every pointer is valid for the duration of the call and the
488    // buffer length matches the buffer.
489    let rc = unsafe {
490        libc::getpwuid_r(
491            uid,
492            &raw mut pwd,
493            buf.as_mut_ptr(),
494            buf.len(),
495            &raw mut result,
496        )
497    };
498    if rc != 0 || result.is_null() || pwd.pw_name.is_null() {
499        return None;
500    }
501    // SAFETY: getpwuid_r succeeded, so pw_name points to a NUL-terminated
502    // string inside `buf`.
503    let name = unsafe { std::ffi::CStr::from_ptr(pwd.pw_name) };
504    let name = name.to_string_lossy().to_string();
505    (!name.is_empty()).then_some(name)
506}
507
508/// `(user, uid, env_user)`: the account of the real uid (falling back to
509/// `$USER`), the uid, and `$USER` when it differs from the account name.
510fn identity() -> (Option<String>, Option<u32>, Option<String>) {
511    let uid = current_uid();
512    #[cfg(unix)]
513    let account = uid.and_then(passwd_name);
514    #[cfg(not(unix))]
515    let account: Option<String> = None;
516    let env = env_user();
517    match account {
518        Some(name) => {
519            let differs = env.filter(|e| *e != name);
520            (Some(name), uid, differs)
521        }
522        None => (env, uid, None),
523    }
524}
525
526fn current_hostname() -> Option<String> {
527    #[cfg(unix)]
528    {
529        if let Ok(h) = nix::unistd::gethostname() {
530            let h = h.to_string_lossy().to_string();
531            if !h.is_empty() {
532                return Some(h);
533            }
534        }
535    }
536    ["HOSTNAME", "COMPUTERNAME"]
537        .iter()
538        .find_map(|k| std::env::var(k).ok().filter(|v| !v.is_empty()))
539}
540
541/// Find the git repository root and current branch for `dir` by reading
542/// `.git/HEAD` directly (no subprocess).
543#[must_use]
544pub fn git_info(dir: &Path) -> (Option<PathBuf>, Option<String>) {
545    for d in dir.ancestors() {
546        let dot_git = d.join(".git");
547        let git_dir = if dot_git.is_dir() {
548            Some(dot_git)
549        } else if dot_git.is_file() {
550            // worktree / submodule: "gitdir: <path>"
551            fs::read_to_string(&dot_git).ok().and_then(|c| {
552                c.lines().find_map(|l| l.strip_prefix("gitdir:")).map(|p| {
553                    let p = PathBuf::from(p.trim());
554                    if p.is_absolute() {
555                        p
556                    } else {
557                        d.join(p)
558                    }
559                })
560            })
561        } else {
562            None
563        };
564        if let Some(gd) = git_dir {
565            let branch = fs::read_to_string(gd.join("HEAD")).ok().map(|head| {
566                let head = head.trim();
567                head.strip_prefix("ref: refs/heads/").map_or_else(
568                    || format!("(detached {})", head.chars().take(12).collect::<String>()),
569                    ToString::to_string,
570                )
571            });
572            return (Some(d.to_path_buf()), branch);
573        }
574    }
575    (None, None)
576}
577
578/// Collect the automatic metadata for a record.
579#[must_use]
580pub fn collect_meta() -> AuditMeta {
581    collect_meta_for(None)
582}
583
584/// [`collect_meta`] for `command`.
585///
586/// When the command works in another
587/// directory (`git -C ../infra …`, `cd ../infra && …`), `git_repo` /
588/// `git_branch` are that directory's repository; otherwise the current
589/// directory's. `cwd` is always the current directory.
590#[must_use]
591pub fn collect_meta_for(command: Option<&str>) -> AuditMeta {
592    let cwd = std::env::current_dir().ok();
593    let target = command.zip(cwd.as_deref()).and_then(|(c, cwd)| {
594        let home = crate::env::Environment::home_dir(&crate::env::RealEnvironment);
595        crate::context::command_work_dir(c, cwd, home.as_deref())
596    });
597    let (repo, branch) = target
598        .as_deref()
599        .or(cwd.as_deref())
600        .map_or((None, None), git_info);
601    let (user, uid, env_user) = identity();
602    AuditMeta {
603        schema_version: AUDIT_SCHEMA_VERSION,
604        version: Some(env!("CARGO_PKG_VERSION").to_string()),
605        user,
606        uid,
607        env_user,
608        hostname: current_hostname(),
609        cwd: cwd.map(|c| c.display().to_string()),
610        git_repo: repo.map(|r| r.display().to_string()),
611        git_branch: branch,
612    }
613}
614
615// ---------------------------------------------------------------------------
616// Writing
617// ---------------------------------------------------------------------------
618
619/// Append an audit event to the log file as a JSON line.
620///
621/// See [`log_event_with`].
622///
623/// # Errors
624/// Returns an error if the file cannot be opened/created or JSON serialization fails.
625pub fn log_event(audit_path: &Path, event: &AuditEvent) -> Result<()> {
626    log_event_with(audit_path, event, &AuditExtra::default())
627}
628
629/// Append an audit event plus caller-provided details as one JSON line.
630///
631/// The record is written with a single `write()` on an `O_APPEND` file
632/// descriptor (under an exclusive `flock` on Unix), so concurrent writers
633/// never interleave. A new file is created with mode `0600`; an existing
634/// file with wider permissions is tightened to `0600`. The log is rotated to
635/// `<name>.1` once it exceeds [`DEFAULT_MAX_AUDIT_BYTES`].
636///
637/// # Errors
638/// Returns an error if the file cannot be opened/created or JSON serialization fails.
639pub fn log_event_with(audit_path: &Path, event: &AuditEvent, extra: &AuditExtra) -> Result<()> {
640    log_event_with_limit(audit_path, event, extra, DEFAULT_MAX_AUDIT_BYTES)
641}
642
643fn open_append(path: &Path) -> std::io::Result<fs::File> {
644    let mut opts = OpenOptions::new();
645    opts.create(true).append(true);
646    #[cfg(unix)]
647    {
648        use std::os::unix::fs::OpenOptionsExt;
649        opts.mode(0o600);
650    }
651    let file = opts.open(path)?;
652    #[cfg(unix)]
653    {
654        use std::os::unix::fs::PermissionsExt;
655        if let Ok(meta) = file.metadata() {
656            if meta.permissions().mode() & 0o077 != 0 {
657                let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
658            }
659        }
660    }
661    Ok(file)
662}
663
664fn rotated_path_n(path: &Path, n: usize) -> PathBuf {
665    let mut name = path.file_name().unwrap_or_default().to_os_string();
666    name.push(format!(".{n}"));
667    path.with_file_name(name)
668}
669
670#[cfg(test)]
671fn rotated_path(path: &Path) -> PathBuf {
672    rotated_path_n(path, 1)
673}
674
675/// Every existing log generation, oldest first (`audit.log.N` …
676/// `audit.log.1`, then `audit.log`). Generations beyond the configured
677/// limit that are still on disk are included too.
678#[must_use]
679pub fn log_files(audit_path: &Path) -> Vec<PathBuf> {
680    let mut rotated: Vec<(usize, PathBuf)> = Vec::new();
681    let prefix = format!(
682        "{}.",
683        audit_path.file_name().unwrap_or_default().to_string_lossy()
684    );
685    if let Some(dir) = audit_path.parent() {
686        let dir = if dir.as_os_str().is_empty() {
687            Path::new(".")
688        } else {
689            dir
690        };
691        for e in fs::read_dir(dir).into_iter().flatten().flatten() {
692            let name = e.file_name().to_string_lossy().to_string();
693            if let Some(n) = name
694                .strip_prefix(&prefix)
695                .and_then(|r| r.parse::<usize>().ok())
696            {
697                rotated.push((n, rotated_path_n(audit_path, n)));
698            }
699        }
700    }
701    rotated.sort_by_key(|r| std::cmp::Reverse(r.0));
702    let mut out: Vec<PathBuf> = rotated.into_iter().map(|(_, p)| p).collect();
703    if audit_path.exists() {
704        out.push(audit_path.to_path_buf());
705    }
706    out
707}
708
709/// Shift `audit.log.k` → `audit.log.k+1` (dropping generations beyond
710/// `keep`) and move `audit.log` to `audit.log.1`.
711fn rotate_files(audit_path: &Path, keep: usize) -> std::io::Result<()> {
712    // Never delete the generation being rotated (see `max_files_for`).
713    let keep = keep.max(1);
714    // Remove generations at or beyond the limit.
715    for p in log_files(audit_path) {
716        let n = p
717            .file_name()
718            .and_then(|f| f.to_str())
719            .and_then(|f| f.rsplit('.').next())
720            .and_then(|n| n.parse::<usize>().ok());
721        if n.is_some_and(|n| n >= keep) && p != audit_path {
722            let _ = fs::remove_file(&p);
723        }
724    }
725    for n in (1..keep).rev() {
726        let from = rotated_path_n(audit_path, n);
727        if from.exists() {
728            fs::rename(&from, rotated_path_n(audit_path, n + 1))?;
729        }
730    }
731    fs::rename(audit_path, rotated_path_n(audit_path, 1))
732}
733
734/// Regexes for [`redact_secrets`]: `(regex, replacement)`.
735fn redaction_rules() -> &'static [(regex::Regex, &'static str)] {
736    static RULES: std::sync::OnceLock<Vec<(regex::Regex, &'static str)>> =
737        std::sync::OnceLock::new();
738    RULES.get_or_init(|| {
739        let v = r#"(?:"[^"]*"|'[^']*'|[^\s'";&|)]+)"#;
740        // A value that is not the next option (`mongosh -p --eval …` prompts).
741        let v_arg = r#"(?:"[^"]*"|'[^']*'|[^\s'";&|)\-][^\s'";&|)]*)"#;
742        let rules: Vec<(String, &'static str)> = vec![
743            // NAME=value assignments whose name says "secret".
744            (
745                format!(
746                    r"(?i)\b([A-Z0-9_]*(?:PASSWORD|PASSWD|_PWD|PASS|TOKEN|SECRET|API_?KEY|ACCESS_KEY|PRIVATE_KEY|CREDENTIALS?)[A-Z0-9_]*=){v}"
747                ),
748                "${1}***",
749            ),
750            // MYSQL_PWD=… (the name is exactly the suffix).
751            (format!(r"\b(MYSQL_PWD=){v}"), "${1}***"),
752            // REDISCLI_AUTH=… and other `*_AUTH` variables.
753            (format!(r"(?i)\b([A-Z0-9_]*_AUTH=){v}"), "${1}***"),
754            // redis-cli -a PASSWORD / --pass PASSWORD
755            (
756                format!(
757                    r"(\b(?:redis-cli|valkey-cli|keydb-cli)\b[^;&|\n]*?\s(?:-a|--pass)\s+){v_arg}"
758                ),
759                "${1}***",
760            ),
761            // mongosh -p PASSWORD / --password PASSWORD (space-separated)
762            (
763                format!(
764                    r"(\b(?:mongosh|mongo|mongodump|mongorestore|mongoexport|mongoimport|mongofiles|mongostat|mongotop)\b[^;&|\n]*?\s(?:-p|--password)\s+){v_arg}"
765                ),
766                "${1}***",
767            ),
768            // mongosh -pPASSWORD (attached value).
769            (
770                format!(
771                    r"(\b(?:mongosh|mongo|mongodump|mongorestore|mongoexport|mongoimport|mongofiles|mongostat|mongotop)\b[^;&|\n]*?\s-p){v}"
772                ),
773                "${1}***",
774            ),
775            // clickhouse-client --password PASSWORD (space-separated; a
776            // bare `--password` prompts).
777            (
778                format!(
779                    r"(\b(?:clickhouse-client|clickhouse)\b[^;&|\n]*?\s--password\s+){v_arg}"
780                ),
781                "${1}***",
782            ),
783            // cqlsh -p PASSWORD / --password PASSWORD (Cassandra).
784            (
785                format!(r"(\bcqlsh\b[^;&|\n]*?\s(?:-p|--password)\s+){v_arg}"),
786                "${1}***",
787            ),
788            // --password=… / --token=… / --secret=… / --api-key=…
789            (
790                format!(
791                    r"(?i)(--(?:password|passwd|pass|token|secret|api-?key|access-token|auth-token|client-secret)=){v}"
792                ),
793                "${1}***",
794            ),
795            // --token VALUE / --api-key VALUE (space-separated values).
796            (
797                format!(
798                    r"(?i)(--(?:token|secret|api-?key|access-token|auth-token|client-secret)\s+){v}"
799                ),
800                "${1}***",
801            ),
802            // sqlcmd / bcp -P PASSWORD and -PPASSWORD (SQL Server; only the
803            // upper-case `-P`, lower-case `-p` prints statistics).
804            (
805                format!(r"(\b(?:sqlcmd|bcp)\b[^;&|\n]*?\s-P\s+){v_arg}"),
806                "${1}***",
807            ),
808            (
809                format!(r"(\b(?:sqlcmd|bcp)\b[^;&|\n]*?\s-P){v}"),
810                "${1}***",
811            ),
812            // mysql/mariadb -pSECRET (attached value only; `-p` alone prompts).
813            (
814                format!(
815                    r"(\b(?:mysql|mysqldump|mysqladmin|mysqlimport|mysqlcheck|mariadb|mariadb-dump)\b[^;&|\n]*?\s-p){v}"
816                ),
817                "${1}***",
818            ),
819            // user:password@ in URLs.
820            (
821                r#"(\b[A-Za-z][A-Za-z0-9+.\-]*://[^\s:/@'"]+:)[^\s@/'"]+@"#.to_string(),
822                "${1}***@",
823            ),
824            // :password@ with an empty user (`redis://:pw@host`).
825            (
826                r#"(\b[A-Za-z][A-Za-z0-9+.\-]*://:)[^\s@/'"]+@"#.to_string(),
827                "${1}***@",
828            ),
829            // Authorization / token headers.
830            (
831                r#"(?i)((?:authorization|proxy-authorization|x-api-key|x-auth-token|private-token)\s*:\s*(?:(?:bearer|basic|token|digest)\s+)?)[^\s'"]+"#
832                    .to_string(),
833                "${1}***",
834            ),
835            // curl -u user:password / --user user:password
836            (
837                r#"(\b(?:curl|wget)\b[^;&|\n]*?\s(?:-u\s*|--user[=\s]+|--http-password[=\s]+)['"]?[^\s:'"]*:)[^\s'"]+"#
838                    .to_string(),
839                "${1}***",
840            ),
841            // Well-known token formats.
842            (r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b".to_string(), "***"),
843            (r"\bgh[pousr]_[A-Za-z0-9]{20,}\b".to_string(), "***"),
844            (r"\bgithub_pat_[A-Za-z0-9_]{20,}\b".to_string(), "***"),
845            (r"\bxox[abprs]-[A-Za-z0-9-]{10,}".to_string(), "***"),
846            (r"\bsk-[A-Za-z0-9_\-]{20,}".to_string(), "***"),
847        ];
848        rules
849            .into_iter()
850            .filter_map(|(re, rep)| regex::Regex::new(&re).ok().map(|r| (r, rep)))
851            .collect()
852    })
853}
854
855/// Undo [`crate::context::escape_invisible`].
856///
857/// Each `\u{XXXX}` that stands for an invisible or control character becomes
858/// that character again. Other `\u{…}` text (a printable character, an invalid code point) is
859/// kept as written.
860#[must_use]
861pub fn unescape_invisible(s: &str) -> String {
862    if !s.contains("\\u{") {
863        return s.to_string();
864    }
865    let mut out = String::with_capacity(s.len());
866    let mut rest = s;
867    while let Some(i) = rest.find("\\u{") {
868        out.push_str(&rest[..i]);
869        let after = &rest[i + 3..];
870        let decoded = after.find('}').and_then(|end| {
871            let hex = &after[..end];
872            let c = (!hex.is_empty() && hex.len() <= 6)
873                .then(|| u32::from_str_radix(hex, 16).ok())
874                .flatten()
875                .and_then(char::from_u32)
876                .filter(|c| {
877                    crate::context::is_invisible(*c) || (c.is_control() && *c != '\t' && *c != '\n')
878                })?;
879            Some((c, end))
880        });
881        if let Some((c, end)) = decoded {
882            out.push(c);
883            rest = &after[end + 1..];
884        } else {
885            out.push_str("\\u{");
886            rest = after;
887        }
888    }
889    out.push_str(rest);
890    out
891}
892
893/// Replace secrets in a command line with `***` before it is stored.
894///
895/// Covers `mysql -pSECRET`, `--password=…` (and `--token`, `--secret`,
896/// `--api-key`), `NAME=value` assignments whose name contains `PASSWORD`,
897/// `PASS`, `TOKEN`, `SECRET`, `KEY`, `CREDENTIAL` (`PGPASSWORD`,
898/// `MYSQL_PWD`, `GITHUB_TOKEN`, `AWS_SECRET_ACCESS_KEY`, …), `user:pass@`
899/// in URLs, `Authorization:`-style headers, `curl -u user:pass`, and AWS
900/// (`AKIA…`), GitHub (`ghp_…`), Slack (`xoxb-…`) and `sk-…` keys.
901///
902/// Returns the redacted text and whether anything was replaced. This is a
903/// best-effort safety net, not a guarantee: a secret passed positionally
904/// (`tool login s3cr3t`) cannot be recognised.
905#[must_use]
906pub fn redact_secrets(command: &str) -> (String, bool) {
907    let mut out = std::borrow::Cow::Borrowed(command);
908    for (re, rep) in redaction_rules() {
909        if re.is_match(&out) {
910            out = std::borrow::Cow::Owned(re.replace_all(&out, *rep).into_owned());
911        }
912    }
913    let changed = out != command;
914    (out.into_owned(), changed)
915}
916
917/// Truncate `s` to at most `max` bytes at a character boundary.
918fn truncate_at_char(s: &str, max: usize) -> &str {
919    if s.len() <= max {
920        return s;
921    }
922    let mut end = max;
923    while end > 0 && !s.is_char_boundary(end) {
924        end -= 1;
925    }
926    &s[..end]
927}
928
929/// Lowercase hex SHA-256 of `data` (small self-contained implementation so
930/// the audit log needs no extra dependency).
931#[must_use]
932#[allow(clippy::many_single_char_names, clippy::too_many_lines)]
933pub fn sha256_hex(data: &[u8]) -> String {
934    const K: [u32; 64] = [
935        0x428a_2f98,
936        0x7137_4491,
937        0xb5c0_fbcf,
938        0xe9b5_dba5,
939        0x3956_c25b,
940        0x59f1_11f1,
941        0x923f_82a4,
942        0xab1c_5ed5,
943        0xd807_aa98,
944        0x1283_5b01,
945        0x2431_85be,
946        0x550c_7dc3,
947        0x72be_5d74,
948        0x80de_b1fe,
949        0x9bdc_06a7,
950        0xc19b_f174,
951        0xe49b_69c1,
952        0xefbe_4786,
953        0x0fc1_9dc6,
954        0x240c_a1cc,
955        0x2de9_2c6f,
956        0x4a74_84aa,
957        0x5cb0_a9dc,
958        0x76f9_88da,
959        0x983e_5152,
960        0xa831_c66d,
961        0xb003_27c8,
962        0xbf59_7fc7,
963        0xc6e0_0bf3,
964        0xd5a7_9147,
965        0x06ca_6351,
966        0x1429_2967,
967        0x27b7_0a85,
968        0x2e1b_2138,
969        0x4d2c_6dfc,
970        0x5338_0d13,
971        0x650a_7354,
972        0x766a_0abb,
973        0x81c2_c92e,
974        0x9272_2c85,
975        0xa2bf_e8a1,
976        0xa81a_664b,
977        0xc24b_8b70,
978        0xc76c_51a3,
979        0xd192_e819,
980        0xd699_0624,
981        0xf40e_3585,
982        0x106a_a070,
983        0x19a4_c116,
984        0x1e37_6c08,
985        0x2748_774c,
986        0x34b0_bcb5,
987        0x391c_0cb3,
988        0x4ed8_aa4a,
989        0x5b9c_ca4f,
990        0x682e_6ff3,
991        0x748f_82ee,
992        0x78a5_636f,
993        0x84c8_7814,
994        0x8cc7_0208,
995        0x90be_fffa,
996        0xa450_6ceb,
997        0xbef9_a3f7,
998        0xc671_78f2,
999    ];
1000    let mut h: [u32; 8] = [
1001        0x6a09_e667,
1002        0xbb67_ae85,
1003        0x3c6e_f372,
1004        0xa54f_f53a,
1005        0x510e_527f,
1006        0x9b05_688c,
1007        0x1f83_d9ab,
1008        0x5be0_cd19,
1009    ];
1010    let mut msg = data.to_vec();
1011    let bit_len = (data.len() as u64).wrapping_mul(8);
1012    msg.push(0x80);
1013    while msg.len() % 64 != 56 {
1014        msg.push(0);
1015    }
1016    msg.extend_from_slice(&bit_len.to_be_bytes());
1017    // `msg.len()` is a multiple of 64 here: no remainder.
1018    for chunk in msg.as_chunks::<64>().0 {
1019        let mut w = [0u32; 64];
1020        for (i, word) in chunk.as_chunks::<4>().0.iter().enumerate() {
1021            w[i] = u32::from_be_bytes(*word);
1022        }
1023        for i in 16..64 {
1024            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
1025            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
1026            w[i] = w[i - 16]
1027                .wrapping_add(s0)
1028                .wrapping_add(w[i - 7])
1029                .wrapping_add(s1);
1030        }
1031        let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
1032        for i in 0..64 {
1033            let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
1034            let ch = (e & f) ^ (!e & g);
1035            let t1 = hh
1036                .wrapping_add(s1)
1037                .wrapping_add(ch)
1038                .wrapping_add(K[i])
1039                .wrapping_add(w[i]);
1040            let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
1041            let maj = (a & b) ^ (a & c) ^ (b & c);
1042            let t2 = s0.wrapping_add(maj);
1043            hh = g;
1044            g = f;
1045            f = e;
1046            e = d.wrapping_add(t1);
1047            d = c;
1048            c = b;
1049            b = a;
1050            a = t1.wrapping_add(t2);
1051        }
1052        for (slot, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
1053            *slot = slot.wrapping_add(v);
1054        }
1055    }
1056    h.iter().fold(String::with_capacity(64), |mut acc, v| {
1057        use std::fmt::Write as _;
1058        let _ = write!(acc, "{v:08x}");
1059        acc
1060    })
1061}
1062
1063fn log_event_with_limit(
1064    audit_path: &Path,
1065    event: &AuditEvent,
1066    extra: &AuditExtra,
1067    max_bytes: u64,
1068) -> Result<()> {
1069    if let Some(parent) = audit_path.parent() {
1070        if !parent.as_os_str().is_empty() {
1071            fs::create_dir_all(parent)?;
1072        }
1073    }
1074
1075    let meta = collect_meta_for(Some(&event.command));
1076    // Redact secrets, then cap the stored command so a few huge commands
1077    // cannot flush history. The digest is always of the original command.
1078    let (stored_event, digest);
1079    let (redacted, was_redacted) = redact_secrets(&event.command);
1080    let truncate = redacted.len() > MAX_STORED_COMMAND_BYTES;
1081    // The blast-radius description arrives escaped for display
1082    // (`src\u{202e}.txt`); the record keeps the real text, like `command`.
1083    let real_detail = event
1084        .blast_radius_detail
1085        .as_deref()
1086        .map(unescape_invisible)
1087        .filter(|d| Some(d.as_str()) != event.blast_radius_detail.as_deref());
1088    let event = if truncate || was_redacted || real_detail.is_some() {
1089        let mut e = event.clone();
1090        if let Some(d) = real_detail {
1091            e.blast_radius_detail = Some(d);
1092        }
1093        e.command = if truncate {
1094            format!(
1095                "{}…[truncated]",
1096                truncate_at_char(&redacted, MAX_STORED_COMMAND_BYTES)
1097            )
1098        } else {
1099            redacted
1100        };
1101        digest = CommandDigest {
1102            command_bytes: truncate.then_some(event.command.len()),
1103            command_sha256: Some(sha256_hex(event.command.as_bytes())),
1104            command_truncated: truncate,
1105            command_redacted: was_redacted,
1106        };
1107        stored_event = e;
1108        &stored_event
1109    } else {
1110        digest = CommandDigest::default();
1111        event
1112    };
1113    let record = AuditRecordOut {
1114        event,
1115        meta,
1116        extra,
1117        digest,
1118    };
1119    let mut line = serde_json::to_vec(&record)?;
1120    line.push(b'\n');
1121
1122    let file = open_append(audit_path)?;
1123
1124    #[cfg(unix)]
1125    let mut file = match nix::fcntl::Flock::lock(file, nix::fcntl::FlockArg::LockExclusive) {
1126        Ok(locked) => LockedOrPlain::Locked(locked),
1127        Err((plain, _)) => LockedOrPlain::Plain(plain),
1128    };
1129    #[cfg(not(unix))]
1130    let mut file = file;
1131
1132    // Another writer may have rotated the file between our open() and the
1133    // lock: then our descriptor points at a rotated generation. Re-open the
1134    // current file instead (once is enough; rotation needs a full file).
1135    #[cfg(unix)]
1136    {
1137        use std::os::unix::fs::MetadataExt;
1138        let same = match (file_ref(&file).metadata(), fs::metadata(audit_path)) {
1139            (Ok(a), Ok(b)) => a.ino() == b.ino() && a.dev() == b.dev(),
1140            _ => false,
1141        };
1142        if !same {
1143            drop(file);
1144            let fresh = open_append(audit_path)?;
1145            file = match nix::fcntl::Flock::lock(fresh, nix::fcntl::FlockArg::LockExclusive) {
1146                Ok(locked) => LockedOrPlain::Locked(locked),
1147                Err((plain, _)) => LockedOrPlain::Plain(plain),
1148            };
1149        }
1150    }
1151
1152    // Rotation (under the lock): if the file is over the limit, shift the
1153    // generations and continue with a fresh file.
1154    let len = file_ref(&file).metadata().map_or(0, |m| m.len());
1155    if max_bytes > 0
1156        && len >= max_bytes
1157        && rotate_files(audit_path, max_files_for(audit_path)).is_ok()
1158    {
1159        {
1160            drop(file);
1161            let fresh = open_append(audit_path)?;
1162            #[cfg(unix)]
1163            {
1164                file = match nix::fcntl::Flock::lock(fresh, nix::fcntl::FlockArg::LockExclusive) {
1165                    Ok(locked) => LockedOrPlain::Locked(locked),
1166                    Err((plain, _)) => LockedOrPlain::Plain(plain),
1167                };
1168            }
1169            #[cfg(not(unix))]
1170            {
1171                file = fresh;
1172            }
1173        }
1174    }
1175
1176    let f = file_mut(&mut file);
1177    let written = f.write(&line)?;
1178    if written < line.len() {
1179        // Extremely unlikely for a regular file; finish the record.
1180        f.write_all(&line[written..])?;
1181    }
1182    Ok(())
1183}
1184
1185#[cfg(unix)]
1186enum LockedOrPlain {
1187    Locked(nix::fcntl::Flock<fs::File>),
1188    Plain(fs::File),
1189}
1190
1191#[cfg(unix)]
1192fn file_ref(f: &LockedOrPlain) -> &fs::File {
1193    match f {
1194        LockedOrPlain::Locked(l) => l,
1195        LockedOrPlain::Plain(p) => p,
1196    }
1197}
1198
1199#[cfg(unix)]
1200fn file_mut(f: &mut LockedOrPlain) -> &mut fs::File {
1201    match f {
1202        LockedOrPlain::Locked(l) => l,
1203        LockedOrPlain::Plain(p) => p,
1204    }
1205}
1206
1207#[cfg(not(unix))]
1208const fn file_ref(f: &fs::File) -> &fs::File {
1209    f
1210}
1211
1212#[cfg(not(unix))]
1213fn file_mut(f: &mut fs::File) -> &mut fs::File {
1214    f
1215}
1216
1217// ---------------------------------------------------------------------------
1218// Reading
1219// ---------------------------------------------------------------------------
1220
1221/// Read and return all audit log lines.
1222///
1223/// # Errors
1224/// Returns an error if the file cannot be read.
1225pub fn read_log(audit_path: &Path) -> Result<String> {
1226    if !audit_path.exists() {
1227        return Ok("No audit events recorded yet.".into());
1228    }
1229    Ok(fs::read_to_string(audit_path)?)
1230}
1231
1232/// Parsed audit records plus the number of lines that could not be parsed.
1233#[derive(Debug, Default)]
1234pub struct AuditRead {
1235    pub entries: Vec<AuditEntry>,
1236    /// Lines skipped because they are not valid UTF-8, not JSON, or lack a
1237    /// `timestamp` / `outcome`.
1238    pub malformed: usize,
1239    /// The files that were read, oldest first.
1240    pub files: Vec<PathBuf>,
1241}
1242
1243/// Read every log generation (see [`log_files`]), oldest first.
1244///
1245/// # Errors
1246/// Returns an error if an existing log file cannot be read (e.g. it is a
1247/// directory or unreadable).
1248pub fn read_entries(audit_path: &Path) -> Result<AuditRead> {
1249    let mut out = AuditRead::default();
1250    for p in log_files(audit_path) {
1251        let bytes = fs::read(&p)
1252            .map_err(|e| Error::Other(format!("could not read audit log {}: {e}", p.display())))?;
1253        out.files.push(p);
1254        for raw in bytes.split(|b| *b == b'\n') {
1255            // A line that is not valid UTF-8 (or not a record) is counted
1256            // and skipped; it never makes the whole read fail.
1257            let Ok(line) = std::str::from_utf8(raw) else {
1258                out.malformed += 1;
1259                continue;
1260            };
1261            let line = line.trim();
1262            if line.is_empty() {
1263                continue;
1264            }
1265            match serde_json::from_str::<AuditEntry>(line) {
1266                Ok(e) if !e.timestamp.is_empty() && e.outcome.is_some() => out.entries.push(e),
1267                _ => out.malformed += 1,
1268            }
1269        }
1270    }
1271    Ok(out)
1272}
1273
1274/// Collapse records that share an `event_id` (the pre-challenge `Cancelled`
1275/// record followed by the final outcome), keeping the last one.
1276#[must_use]
1277pub fn collapse_events(entries: Vec<AuditEntry>) -> Vec<AuditEntry> {
1278    let mut last_index: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
1279    for (i, e) in entries.iter().enumerate() {
1280        if !e.event_id.is_empty() {
1281            last_index.insert(e.event_id.clone(), i);
1282        }
1283    }
1284    entries
1285        .into_iter()
1286        .enumerate()
1287        .filter(|(i, e)| e.event_id.is_empty() || last_index.get(&e.event_id) == Some(i))
1288        .map(|(_, e)| e)
1289        .collect()
1290}
1291
1292/// Filters for `audit show`.
1293#[derive(Debug, Clone, Default)]
1294pub struct AuditFilter {
1295    /// Only records at or after this timestamp (`YYYY-MM-DDTHH:MM:SSZ`).
1296    pub since: Option<String>,
1297    pub outcome: Option<AuditOutcome>,
1298    /// Only records at or above this severity.
1299    pub min_severity: Option<Severity>,
1300    /// Keep only the last N records (after the other filters).
1301    pub limit: Option<usize>,
1302}
1303
1304/// Apply a filter.
1305#[must_use]
1306pub fn filter_entries(entries: Vec<AuditEntry>, f: &AuditFilter) -> Vec<AuditEntry> {
1307    let mut v: Vec<AuditEntry> = entries
1308        .into_iter()
1309        .filter(|e| {
1310            f.since
1311                .as_ref()
1312                .is_none_or(|s| e.timestamp.as_str() >= s.as_str())
1313        })
1314        .filter(|e| {
1315            f.outcome
1316                .as_ref()
1317                .is_none_or(|o| e.outcome.as_ref() == Some(o))
1318        })
1319        .filter(|e| {
1320            f.min_severity
1321                .is_none_or(|min| e.severity.is_some_and(|s| s >= min))
1322        })
1323        .collect();
1324    if let Some(n) = f.limit {
1325        if v.len() > n {
1326            v.drain(..v.len() - n);
1327        }
1328    }
1329    v
1330}
1331
1332/// Parse a `--since` value into a comparable UTC timestamp.
1333///
1334/// Accepts a relative duration (`30m`, `12h`, `7d`, `2w`), a date
1335/// (`2026-01-31`) or a full timestamp (`2026-01-31T10:00:00Z`).
1336///
1337/// # Errors
1338/// Returns an error describing the accepted formats.
1339pub fn parse_since(value: &str) -> Result<String> {
1340    let v = value.trim();
1341    let err = || {
1342        Error::Config(format!(
1343            "invalid --since value '{value}'. Use a duration like 30m, 12h, 7d, 2w, \
1344             a date like 2026-01-31, or a timestamp like 2026-01-31T10:00:00Z"
1345        ))
1346    };
1347    let is_duration =
1348        v.is_ascii() && v.len() >= 2 && v[..v.len() - 1].chars().all(|c| c.is_ascii_digit());
1349    if let Some(unit) = v
1350        .chars()
1351        .last()
1352        .filter(|c| is_duration && c.is_ascii_alphabetic())
1353    {
1354        let num: u64 = v[..v.len() - 1].parse().map_err(|_| err())?;
1355        let secs = match unit {
1356            's' => num,
1357            'm' => num * 60,
1358            'h' => num * 3600,
1359            'd' => num * 86_400,
1360            'w' => num * 7 * 86_400,
1361            _ => return Err(err()),
1362        };
1363        let now = std::time::SystemTime::now()
1364            .duration_since(std::time::UNIX_EPOCH)
1365            .unwrap_or_default()
1366            .as_secs();
1367        return Ok(timestamp_from_epoch(now.saturating_sub(secs)));
1368    }
1369    let bytes = v.as_bytes();
1370    let is_date = v.len() == 10
1371        && bytes[4] == b'-'
1372        && bytes[7] == b'-'
1373        && v.chars()
1374            .enumerate()
1375            .all(|(i, c)| i == 4 || i == 7 || c.is_ascii_digit());
1376    if is_date {
1377        return if valid_date(&v[..10]) {
1378            Ok(format!("{v}T00:00:00Z"))
1379        } else {
1380            Err(err())
1381        };
1382    }
1383    let is_timestamp = v.len() == 20
1384        && v.is_ascii()
1385        && v.ends_with('Z')
1386        && bytes[10] == b'T'
1387        && bytes[13] == b':'
1388        && bytes[16] == b':'
1389        && valid_date(&v[..10])
1390        && [(11, 23), (14, 59), (17, 60)].iter().all(|&(i, max)| {
1391            v[i..i + 2]
1392                .parse::<u32>()
1393                .is_ok_and(|n| n <= max && v[i..i + 2].bytes().all(|b| b.is_ascii_digit()))
1394        });
1395    if is_timestamp {
1396        return Ok(v.to_string());
1397    }
1398    Err(err())
1399}
1400
1401/// `YYYY-MM-DD` with a real month and day.
1402fn valid_date(d: &str) -> bool {
1403    let b = d.as_bytes();
1404    if d.len() != 10 || !d.is_ascii() || b[4] != b'-' || b[7] != b'-' {
1405        return false;
1406    }
1407    let (Ok(y), Ok(m), Ok(day)) = (
1408        d[..4].parse::<u32>(),
1409        d[5..7].parse::<u32>(),
1410        d[8..10].parse::<u32>(),
1411    ) else {
1412        return false;
1413    };
1414    let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
1415    let days = match m {
1416        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1417        4 | 6 | 9 | 11 => 30,
1418        2 if leap => 29,
1419        2 => 28,
1420        _ => return false,
1421    };
1422    (1..=days).contains(&day)
1423}
1424
1425/// Render records as a human-readable table.
1426#[must_use]
1427pub fn format_table(entries: &[AuditEntry]) -> String {
1428    use std::fmt::Write as _;
1429    let mut out = String::new();
1430    let _ = writeln!(
1431        out,
1432        "{:<20}  {:<9}  {:<8}  {:<28}  COMMAND",
1433        "TIME (UTC)", "OUTCOME", "SEVERITY", "CHECKS"
1434    );
1435    for e in entries {
1436        let outcome = e
1437            .outcome
1438            .as_ref()
1439            .map_or_else(|| "?".to_string(), ToString::to_string);
1440        let sev = e
1441            .severity
1442            .map_or_else(|| "?".to_string(), |s| s.to_string());
1443        let mut checks = e.matched_ids.join(",");
1444        if checks.chars().count() > 28 {
1445            checks = format!("{}…", checks.chars().take(27).collect::<String>());
1446        }
1447        // Invisible and bidi characters are shown escaped (`\u{202e}`): the
1448        // JSON formats keep the real text.
1449        let mut cmd = crate::context::escape_invisible(&e.command.replace('\n', " "));
1450        if cmd.chars().count() > 80 {
1451            cmd = format!("{}…", cmd.chars().take(79).collect::<String>());
1452        }
1453        let mut extras = Vec::new();
1454        if let Some(a) = &e.agent_name {
1455            extras.push(format!("agent={}", crate::context::escape_invisible(a)));
1456        }
1457        if let Some(t) = &e.tool_use_id {
1458            extras.push(format!(
1459                "tool_use_id={}",
1460                crate::context::escape_invisible(t)
1461            ));
1462        }
1463        if let Some(r) = &e.deny_reason {
1464            extras.push(format!("reason={r}"));
1465        }
1466        // A kubectl / helm row names the cluster context it ran against;
1467        // the git branch is only shown for the other rows (and git checks).
1468        let k8s: Vec<&String> = e
1469            .context_labels
1470            .iter()
1471            .filter(|l| l.starts_with("k8s="))
1472            .collect();
1473        for l in &k8s {
1474            extras.push(crate::context::escape_invisible(l));
1475        }
1476        if let Some(b) = e
1477            .git_branch
1478            .as_ref()
1479            .filter(|_| k8s.is_empty() || e.matched_ids.iter().any(|id| id.starts_with("git")))
1480        {
1481            extras.push(format!("branch={}", crate::context::escape_invisible(b)));
1482        }
1483        let extras = if extras.is_empty() {
1484            String::new()
1485        } else {
1486            format!("  [{}]", extras.join(" "))
1487        };
1488        let _ = writeln!(
1489            out,
1490            "{:<20}  {outcome:<9}  {sev:<8}  {checks:<28}  {cmd}{extras}",
1491            e.timestamp
1492        );
1493    }
1494    out
1495}
1496
1497/// Clear the audit log (and every rotated generation).
1498///
1499/// # Errors
1500/// Returns an error if the file cannot be removed.
1501pub fn clear_log(audit_path: &Path) -> Result<()> {
1502    for p in log_files(audit_path) {
1503        if p.exists() {
1504            fs::remove_file(&p).map_err(|e| {
1505                Error::Other(format!("could not remove audit log {}: {e}", p.display()))
1506            })?;
1507        }
1508    }
1509    Ok(())
1510}
1511
1512/// Get the current timestamp in ISO 8601 format.
1513#[must_use]
1514pub fn now_timestamp() -> String {
1515    use std::time::{SystemTime, UNIX_EPOCH};
1516    let secs = SystemTime::now()
1517        .duration_since(UNIX_EPOCH)
1518        .unwrap_or_default()
1519        .as_secs();
1520    timestamp_from_epoch(secs)
1521}
1522
1523fn timestamp_from_epoch(secs: u64) -> String {
1524    let days = secs / 86400;
1525    let remaining = secs % 86400;
1526    let hours = remaining / 3600;
1527    let minutes = (remaining % 3600) / 60;
1528    let seconds = remaining % 60;
1529    let (year, month, day) = epoch_days_to_date(days);
1530    format!("{year:04}-{month:02}-{day:02}T{hours:02}:{minutes:02}:{seconds:02}Z")
1531}
1532
1533/// Convert epoch days to (year, month, day). Simplified algorithm.
1534const fn epoch_days_to_date(days: u64) -> (u64, u64, u64) {
1535    // Algorithm based on Howard Hinnant's civil_from_days
1536    let z = days + 719_468;
1537    let era = z / 146_097;
1538    let doe = z - era * 146_097;
1539    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
1540    let y = yoe + era * 400;
1541    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1542    let mp = (5 * doy + 2) / 153;
1543    let d = doy - (153 * mp + 2) / 5 + 1;
1544    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1545    let y = if m <= 2 { y + 1 } else { y };
1546    (y, m, d)
1547}
1548
1549#[cfg(test)]
1550mod tests {
1551    use super::*;
1552    use std::path::PathBuf;
1553
1554    fn event(id: &str, outcome: AuditOutcome, severity: Severity, ts: &str) -> AuditEvent {
1555        AuditEvent {
1556            event_id: id.into(),
1557            timestamp: ts.into(),
1558            command: "git push -f".into(),
1559            matched_ids: vec!["git:force_push".into()],
1560            challenge_type: "Math".into(),
1561            outcome,
1562            context_labels: vec!["branch=main".into()],
1563            severity,
1564            agent_name: None,
1565            agent_session_id: None,
1566            blast_radius_scope: None,
1567            blast_radius_detail: None,
1568            attempts: None,
1569        }
1570    }
1571
1572    #[test]
1573    fn test_log_and_read() {
1574        let temp = tree_fs::TreeBuilder::default()
1575            .create()
1576            .expect("create tree");
1577        let path = temp.root.join("audit.log");
1578
1579        let ev = event(
1580            "test-event-1",
1581            AuditOutcome::Allowed,
1582            Severity::High,
1583            "2026-02-15T10:00:00Z",
1584        );
1585        log_event(&path, &ev).unwrap();
1586        let content = read_log(&path).unwrap();
1587        // JSON lines format: each line is a valid JSON object, readable as
1588        // the original AuditEvent (backward compatible).
1589        let parsed: AuditEvent = serde_json::from_str(content.trim()).unwrap();
1590        assert_eq!(parsed.event_id, "test-event-1");
1591        assert_eq!(parsed.command, "git push -f");
1592        assert_eq!(parsed.outcome, AuditOutcome::Allowed);
1593        assert_eq!(parsed.matched_ids, vec!["git:force_push"]);
1594        assert_eq!(parsed.context_labels, vec!["branch=main"]);
1595        assert_eq!(parsed.severity, Severity::High);
1596
1597        let entry: AuditEntry = serde_json::from_str(content.trim()).unwrap();
1598        assert_eq!(entry.schema_version, Some(AUDIT_SCHEMA_VERSION));
1599        assert!(entry.cwd.is_some());
1600    }
1601
1602    #[test]
1603    fn extra_fields_are_written() {
1604        let temp = tree_fs::TreeBuilder::default().create().unwrap();
1605        let path = temp.root.join("audit.log");
1606        let extra = AuditExtra {
1607            policy_sources: vec!["/repo/.shellfirm.yaml".into()],
1608            effective_challenge: Some("Yes".into()),
1609            deny_reason: Some("policy_deny".into()),
1610            policy_check_ids: vec!["git:force_push".into()],
1611            escalation_reasons: vec!["protected branch `main`".into()],
1612            tool_use_id: Some("toolu_1".into()),
1613        };
1614        log_event_with(
1615            &path,
1616            &event(
1617                "x",
1618                AuditOutcome::Denied,
1619                Severity::High,
1620                "2026-02-15T10:00:00Z",
1621            ),
1622            &extra,
1623        )
1624        .unwrap();
1625        let read = read_entries(&path).unwrap();
1626        assert_eq!(read.entries.len(), 1);
1627        let e = &read.entries[0];
1628        assert_eq!(e.deny_reason.as_deref(), Some("policy_deny"));
1629        assert_eq!(e.effective_challenge.as_deref(), Some("Yes"));
1630        assert_eq!(e.policy_sources, vec!["/repo/.shellfirm.yaml".to_string()]);
1631        // `audit show --format json|jsonl` keeps the tool_use_id.
1632        assert_eq!(e.tool_use_id.as_deref(), Some("toolu_1"));
1633        let json = serde_json::to_value(e).unwrap();
1634        assert_eq!(json["tool_use_id"], "toolu_1");
1635        assert!(format_table(&read.entries).contains("tool_use_id=toolu_1"));
1636    }
1637
1638    #[test]
1639    fn table_shows_the_k8s_context_for_kubectl_rows() {
1640        let kube = AuditEntry {
1641            command: "kubectl delete deploy api".into(),
1642            matched_ids: vec!["kubernetes-strict:delete_resource".into()],
1643            context_labels: vec!["k8s=prod-eu".into()],
1644            git_branch: Some("main".into()),
1645            ..AuditEntry::default()
1646        };
1647        let git = AuditEntry {
1648            command: "git push -f".into(),
1649            matched_ids: vec!["git:force_push".into()],
1650            git_branch: Some("main".into()),
1651            ..AuditEntry::default()
1652        };
1653        let table = format_table(&[kube, git]);
1654        let lines: Vec<&str> = table.lines().collect();
1655        assert!(lines[1].contains("[k8s=prod-eu]"), "{table}");
1656        assert!(!lines[1].contains("branch="), "{table}");
1657        assert!(lines[2].contains("[branch=main]"), "{table}");
1658    }
1659
1660    #[test]
1661    fn sqlcmd_and_bcp_passwords_are_redacted() {
1662        for (cmd, want) in [
1663            (
1664                "sqlcmd -S db -U sa -P S3cret! -Q 'select 1'",
1665                "sqlcmd -S db -U sa -P *** -Q 'select 1'",
1666            ),
1667            (
1668                "sqlcmd -S db -U sa -PS3cret -i x.sql",
1669                "sqlcmd -S db -U sa -P*** -i x.sql",
1670            ),
1671            (
1672                "bcp dbo.t out t.dat -S db -U sa -P 'a b' -c",
1673                "bcp dbo.t out t.dat -S db -U sa -P *** -c",
1674            ),
1675            (
1676                "bcp dbo.t out t.dat -Uu -Ppw",
1677                "bcp dbo.t out t.dat -Uu -P***",
1678            ),
1679        ] {
1680            assert_eq!(redact_secrets(cmd).0, want, "{cmd}");
1681        }
1682        // `-p` (statistics) is not a password.
1683        assert!(!redact_secrets("sqlcmd -S db -p -Q 'select 1'").1);
1684    }
1685
1686    #[test]
1687    fn table_escapes_invisible_characters_but_json_keeps_them() {
1688        let e = AuditEntry {
1689            timestamp: "2026-02-15T10:00:00Z".into(),
1690            command: "rm -rf src\u{202e}.txt # \u{200b}x".into(),
1691            git_branch: Some("main\u{200b}".into()),
1692            ..AuditEntry::default()
1693        };
1694        let table = format_table(std::slice::from_ref(&e));
1695        assert!(table.contains("src\\u{202e}.txt"), "{table}");
1696        assert!(table.contains("branch=main\\u{200b}"), "{table}");
1697        assert!(!table.contains('\u{202e}'));
1698        let json = serde_json::to_value(&e).unwrap();
1699        assert_eq!(json["command"], "rm -rf src\u{202e}.txt # \u{200b}x");
1700    }
1701
1702    #[test]
1703    fn old_records_still_parse() {
1704        let temp = tree_fs::TreeBuilder::default().create().unwrap();
1705        let path = temp.root.join("audit.log");
1706        fs::write(
1707            &path,
1708            "{\"event_id\":\"a\",\"timestamp\":\"2026-01-01T00:00:00Z\",\"command\":\"rm -rf /\",\"matched_ids\":[\"fs:x\"],\"challenge_type\":\"Math\",\"outcome\":\"Allowed\",\"context_labels\":[],\"severity\":\"Critical\"}\nnot json\n",
1709        )
1710        .unwrap();
1711        let read = read_entries(&path).unwrap();
1712        assert_eq!(read.entries.len(), 1);
1713        assert_eq!(read.malformed, 1);
1714        assert_eq!(read.entries[0].schema_version, None);
1715    }
1716
1717    #[cfg(unix)]
1718    #[test]
1719    fn audit_file_is_private() {
1720        use std::os::unix::fs::PermissionsExt;
1721        let temp = tree_fs::TreeBuilder::default().create().unwrap();
1722        let path = temp.root.join("audit.log");
1723        fs::write(&path, "").unwrap();
1724        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
1725        log_event(
1726            &path,
1727            &event(
1728                "p",
1729                AuditOutcome::Allowed,
1730                Severity::Low,
1731                "2026-01-01T00:00:00Z",
1732            ),
1733        )
1734        .unwrap();
1735        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1736        assert_eq!(mode, 0o600);
1737    }
1738
1739    #[test]
1740    fn concurrent_writers_do_not_interleave() {
1741        let temp = tree_fs::TreeBuilder::default().create().unwrap();
1742        let path = temp.root.join("audit.log");
1743        let big = "x".repeat(8 * 1024);
1744        let handles: Vec<_> = (0..16)
1745            .map(|t| {
1746                let path = path.clone();
1747                let big = big.clone();
1748                std::thread::spawn(move || {
1749                    for i in 0..10 {
1750                        let mut ev = event(
1751                            &format!("{t}-{i}"),
1752                            AuditOutcome::Allowed,
1753                            Severity::Low,
1754                            "2026-01-01T00:00:00Z",
1755                        );
1756                        ev.command.clone_from(&big);
1757                        log_event(&path, &ev).unwrap();
1758                    }
1759                })
1760            })
1761            .collect();
1762        for h in handles {
1763            h.join().unwrap();
1764        }
1765        let read = read_entries(&path).unwrap();
1766        assert_eq!(read.malformed, 0);
1767        assert_eq!(read.entries.len(), 160);
1768    }
1769
1770    #[test]
1771    fn rotation_moves_old_log_aside() {
1772        let temp = tree_fs::TreeBuilder::default().create().unwrap();
1773        let path = temp.root.join("audit.log");
1774        let ev = event(
1775            "r",
1776            AuditOutcome::Allowed,
1777            Severity::Low,
1778            "2026-01-01T00:00:00Z",
1779        );
1780        log_event_with_limit(&path, &ev, &AuditExtra::default(), 10).unwrap();
1781        log_event_with_limit(&path, &ev, &AuditExtra::default(), 10).unwrap();
1782        assert!(rotated_path(&path).exists());
1783        let read = read_entries(&path).unwrap();
1784        assert_eq!(read.entries.len(), 2);
1785        clear_log(&path).unwrap();
1786        assert!(!path.exists());
1787        assert!(!rotated_path(&path).exists());
1788    }
1789
1790    #[test]
1791    fn collapse_and_filter() {
1792        let mk = |id: &str, o: AuditOutcome, s: Severity, ts: &str| -> AuditEntry {
1793            serde_json::from_str(&serde_json::to_string(&event(id, o, s, ts)).unwrap()).unwrap()
1794        };
1795        let entries = vec![
1796            mk(
1797                "a",
1798                AuditOutcome::Cancelled,
1799                Severity::High,
1800                "2026-01-01T00:00:00Z",
1801            ),
1802            mk(
1803                "a",
1804                AuditOutcome::Allowed,
1805                Severity::High,
1806                "2026-01-01T00:00:01Z",
1807            ),
1808            mk(
1809                "b",
1810                AuditOutcome::Denied,
1811                Severity::Critical,
1812                "2026-02-01T00:00:00Z",
1813            ),
1814            mk(
1815                "c",
1816                AuditOutcome::Skipped,
1817                Severity::Low,
1818                "2026-03-01T00:00:00Z",
1819            ),
1820        ];
1821        let collapsed = collapse_events(entries);
1822        assert_eq!(collapsed.len(), 3);
1823        assert_eq!(collapsed[0].outcome, Some(AuditOutcome::Allowed));
1824
1825        let f = AuditFilter {
1826            outcome: Some(AuditOutcome::Denied),
1827            ..Default::default()
1828        };
1829        assert_eq!(filter_entries(collapsed.clone(), &f).len(), 1);
1830        let f = AuditFilter {
1831            min_severity: Some(Severity::High),
1832            ..Default::default()
1833        };
1834        assert_eq!(filter_entries(collapsed.clone(), &f).len(), 2);
1835        let f = AuditFilter {
1836            since: Some("2026-02-01T00:00:00Z".into()),
1837            ..Default::default()
1838        };
1839        assert_eq!(filter_entries(collapsed.clone(), &f).len(), 2);
1840        let f = AuditFilter {
1841            limit: Some(1),
1842            ..Default::default()
1843        };
1844        let last = filter_entries(collapsed, &f);
1845        assert_eq!(last.len(), 1);
1846        assert_eq!(last[0].event_id, "c");
1847        assert!(format_table(&last).contains("SKIPPED"));
1848    }
1849
1850    #[test]
1851    fn parse_since_formats() {
1852        assert_eq!(parse_since("2026-01-31").unwrap(), "2026-01-31T00:00:00Z");
1853        assert_eq!(
1854            parse_since("2026-01-31T10:00:00Z").unwrap(),
1855            "2026-01-31T10:00:00Z"
1856        );
1857        assert_eq!(parse_since("7d").unwrap().len(), 20);
1858        assert!(parse_since("yesterday").is_err());
1859        assert!(parse_since("7y").is_err());
1860    }
1861
1862    #[test]
1863    fn outcome_parse() {
1864        assert_eq!(AuditOutcome::parse("DENIED").unwrap(), AuditOutcome::Denied);
1865        assert!(AuditOutcome::parse("nope").is_err());
1866    }
1867
1868    #[test]
1869    fn git_info_reads_head() {
1870        let temp = tree_fs::TreeBuilder::default()
1871            .add(".git/HEAD", "ref: refs/heads/feature/x\n")
1872            .add("sub/file", "")
1873            .create()
1874            .unwrap();
1875        let (repo, branch) = git_info(&temp.root.join("sub"));
1876        assert_eq!(repo.as_deref(), Some(temp.root.as_path()));
1877        assert_eq!(branch.as_deref(), Some("feature/x"));
1878    }
1879
1880    #[test]
1881    fn test_read_nonexistent_log() {
1882        let path = PathBuf::from("/tmp/nonexistent-audit-test.log");
1883        let result = read_log(&path).unwrap();
1884        assert!(result.contains("No audit events"));
1885    }
1886
1887    #[test]
1888    fn test_cancelled_outcome_serialization() {
1889        let temp = tree_fs::TreeBuilder::default()
1890            .create()
1891            .expect("create tree");
1892        let path = temp.root.join("audit.log");
1893        log_event(
1894            &path,
1895            &event(
1896                "cancel-test-1",
1897                AuditOutcome::Cancelled,
1898                Severity::Critical,
1899                "2026-02-15T10:00:00Z",
1900            ),
1901        )
1902        .unwrap();
1903        let content = read_log(&path).unwrap();
1904        let parsed: AuditEvent = serde_json::from_str(content.trim()).unwrap();
1905        assert_eq!(parsed.outcome, AuditOutcome::Cancelled);
1906        assert_eq!(format!("{}", parsed.outcome), "CANCELLED");
1907    }
1908
1909    #[test]
1910    fn git_meta_follows_the_target_repository() {
1911        let temp = tree_fs::TreeBuilder::default()
1912            .add("infra/.git/HEAD", "ref: refs/heads/infra-main\n")
1913            .add("infra/x", "")
1914            .create()
1915            .unwrap();
1916        // `/`-separated, as written in a shell command (on Windows
1917        // `C:/Users/…`; a `\` in a shell word is an escape).
1918        let infra = temp
1919            .root
1920            .join("infra")
1921            .display()
1922            .to_string()
1923            .replace('\\', "/");
1924        for command in [
1925            format!("git -C {infra} push -f"),
1926            format!("cd {infra} && git reset --hard"),
1927            format!("cd {infra} && rm -rf x"),
1928        ] {
1929            let meta = collect_meta_for(Some(&command));
1930            assert_eq!(meta.git_repo.as_deref(), Some(infra.as_str()), "{command}");
1931            assert_eq!(meta.git_branch.as_deref(), Some("infra-main"), "{command}");
1932            assert_eq!(
1933                meta.cwd,
1934                std::env::current_dir()
1935                    .ok()
1936                    .map(|c| c.display().to_string())
1937            );
1938        }
1939        // No other directory: the current one's repository.
1940        let here = collect_meta_for(Some("git push -f"));
1941        assert_eq!(here.git_repo, collect_meta().git_repo);
1942    }
1943
1944    #[test]
1945    fn test_now_timestamp_format() {
1946        let ts = now_timestamp();
1947        assert!(ts.contains('T'));
1948        assert!(ts.ends_with('Z'));
1949        assert_eq!(ts.len(), 20);
1950    }
1951
1952    #[test]
1953    fn sha256_matches_known_vectors() {
1954        assert_eq!(
1955            sha256_hex(b""),
1956            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
1957        );
1958        assert_eq!(
1959            sha256_hex(b"abc"),
1960            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1961        );
1962        assert_eq!(
1963            sha256_hex(&[b'a'; 1000]),
1964            "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3"
1965        );
1966    }
1967
1968    #[test]
1969    fn huge_commands_are_truncated_and_hashed() {
1970        let temp = tree_fs::TreeBuilder::default().create().unwrap();
1971        let path = temp.root.join("audit.log");
1972        let mut ev = event(
1973            "big",
1974            AuditOutcome::Asked,
1975            Severity::High,
1976            "2026-01-01T00:00:00Z",
1977        );
1978        ev.command = format!("echo {} && rm -rf ./src", "é".repeat(3 * 1024 * 1024));
1979        log_event(&path, &ev).unwrap();
1980        assert!(fs::metadata(&path).unwrap().len() < 16 * 1024);
1981        let e = &read_entries(&path).unwrap().entries[0];
1982        assert!(e.command_truncated);
1983        assert_eq!(e.command_bytes, Some(ev.command.len()));
1984        assert_eq!(
1985            e.command_sha256.as_deref(),
1986            Some(sha256_hex(ev.command.as_bytes()).as_str())
1987        );
1988    }
1989
1990    #[test]
1991    fn rotation_keeps_n_generations_and_show_reads_them() {
1992        let temp = tree_fs::TreeBuilder::default().create().unwrap();
1993        let path = temp.root.join("audit.log");
1994        for i in 0..5 {
1995            fs::write(
1996                &path,
1997                format!(
1998                    "{}\n",
1999                    serde_json::to_string(&event(
2000                        &format!("e{i}"),
2001                        AuditOutcome::Allowed,
2002                        Severity::Low,
2003                        "2026-01-01T00:00:00Z"
2004                    ))
2005                    .unwrap()
2006                ),
2007            )
2008            .unwrap();
2009            rotate_files(&path, 3).unwrap();
2010        }
2011        let files = log_files(&path);
2012        assert_eq!(files.len(), 3, "{files:?}");
2013        assert!(!rotated_path_n(&path, 4).exists());
2014        let ids: Vec<String> = read_entries(&path)
2015            .unwrap()
2016            .entries
2017            .into_iter()
2018            .map(|e| e.event_id)
2019            .collect();
2020        assert_eq!(ids, vec!["e2", "e3", "e4"]);
2021        clear_log(&path).unwrap();
2022        assert!(log_files(&path).is_empty());
2023    }
2024
2025    #[test]
2026    fn invalid_utf8_and_incomplete_lines_are_skipped() {
2027        let temp = tree_fs::TreeBuilder::default().create().unwrap();
2028        let path = temp.root.join("audit.log");
2029        let good = serde_json::to_string(&event(
2030            "g",
2031            AuditOutcome::Denied,
2032            Severity::High,
2033            "2026-01-01T00:00:00Z",
2034        ))
2035        .unwrap();
2036        let mut bytes = b"\xff\xfe\n{\"foo\":1}\n".to_vec();
2037        bytes.extend_from_slice(good.as_bytes());
2038        bytes.push(b'\n');
2039        fs::write(&path, bytes).unwrap();
2040        let r = read_entries(&path).unwrap();
2041        assert_eq!(r.entries.len(), 1);
2042        assert_eq!(r.malformed, 2);
2043    }
2044
2045    #[test]
2046    fn parse_since_rejects_impossible_dates() {
2047        assert!(parse_since("2026-13-01").is_err());
2048        assert!(parse_since("2026-02-30").is_err());
2049        assert!(parse_since("2024-02-29").is_ok());
2050        assert!(parse_since("2026-01-31T25:00:00Z").is_err());
2051        assert!(parse_since("2026-01-31TAB:00:00Z").is_err());
2052    }
2053
2054    #[test]
2055    fn no_terminal_outcome_round_trips() {
2056        assert_eq!(
2057            AuditOutcome::parse("no-terminal").unwrap(),
2058            AuditOutcome::NoTerminal
2059        );
2060        assert_eq!(
2061            serde_json::to_string(&AuditOutcome::NoTerminal).unwrap(),
2062            "\"NoTerminal\""
2063        );
2064    }
2065
2066    #[test]
2067    fn identity_comes_from_the_uid() {
2068        let meta = collect_meta();
2069        #[cfg(unix)]
2070        assert_eq!(meta.uid, current_uid());
2071        assert_eq!(meta.schema_version, AUDIT_SCHEMA_VERSION);
2072    }
2073
2074    #[test]
2075    fn extra_for_policy_deny() {
2076        let merged = crate::policy::MergedPolicy {
2077            extra_deny: vec!["git:force_push".into()],
2078            enforced_ids: ["git:force_push".to_string()].into_iter().collect(),
2079            sources: vec![PathBuf::from("/repo/.shellfirm.yaml")],
2080            ..Default::default()
2081        };
2082        let x = AuditExtra::for_decision(
2083            &merged,
2084            &[],
2085            &["git:force_push".into()],
2086            true,
2087            Some("Deny".into()),
2088            vec![],
2089        );
2090        assert_eq!(x.deny_reason.as_deref(), Some("policy_deny"));
2091        assert_eq!(x.policy_sources, vec!["/repo/.shellfirm.yaml".to_string()]);
2092        let y = AuditExtra::for_decision(
2093            &crate::policy::MergedPolicy::default(),
2094            &["git:reset".into()],
2095            &["git:reset".into()],
2096            true,
2097            None,
2098            vec![],
2099        );
2100        assert_eq!(y.deny_reason.as_deref(), Some("user_deny"));
2101        assert!(y.policy_sources.is_empty());
2102    }
2103
2104    #[test]
2105    fn extra_policy_sources_are_the_files_that_name_the_id() {
2106        let mut id_sources = std::collections::BTreeMap::new();
2107        id_sources.insert(
2108            "kubernetes:delete_namespace".to_string(),
2109            vec![PathBuf::from("/etc/shellfirm/policy.yaml")],
2110        );
2111        id_sources.insert(
2112            "git:reset".to_string(),
2113            vec![PathBuf::from("/repo/.shellfirm.yaml")],
2114        );
2115        let merged = crate::policy::MergedPolicy {
2116            extra_deny: vec!["kubernetes:delete_namespace".into()],
2117            enforced_ids: [
2118                "kubernetes:delete_namespace".to_string(),
2119                "git:reset".to_string(),
2120            ]
2121            .into_iter()
2122            .collect(),
2123            sources: vec![
2124                PathBuf::from("/etc/shellfirm/policy.yaml"),
2125                PathBuf::from("/repo/.shellfirm.yaml"),
2126            ],
2127            org_sources: vec![PathBuf::from("/etc/shellfirm/policy.yaml")],
2128            id_sources,
2129            ..Default::default()
2130        };
2131        let x = AuditExtra::for_decision(
2132            &merged,
2133            &[],
2134            &["kubernetes:delete_namespace".into()],
2135            true,
2136            Some("Deny".into()),
2137            vec![],
2138        );
2139        assert_eq!(x.deny_reason.as_deref(), Some("policy_deny"));
2140        assert_eq!(
2141            x.policy_sources,
2142            vec!["/etc/shellfirm/policy.yaml".to_string()]
2143        );
2144        // A personal deny of an id the policy only escalates is a user deny,
2145        // but the policy enforcement is still attributed.
2146        let y = AuditExtra::for_decision(
2147            &merged,
2148            &["git:reset".into()],
2149            &["git:reset".into()],
2150            true,
2151            None,
2152            vec![],
2153        );
2154        assert_eq!(y.deny_reason.as_deref(), Some("user_deny"));
2155        assert_eq!(y.policy_check_ids, vec!["git:reset".to_string()]);
2156        assert_eq!(y.policy_sources, vec!["/repo/.shellfirm.yaml".to_string()]);
2157        // Not denied: no reason.
2158        let z = AuditExtra::for_decision(&merged, &[], &["git:reset".into()], false, None, vec![]);
2159        assert!(z.deny_reason.is_none());
2160    }
2161
2162    #[test]
2163    fn max_files_is_never_zero() {
2164        assert_eq!(clamp_max_files(0), 1);
2165        assert_eq!(clamp_max_files(3), 3);
2166        assert_eq!(clamp_max_files(1000), MAX_AUDIT_FILES_LIMIT);
2167    }
2168
2169    #[test]
2170    fn rotation_with_keep_zero_still_keeps_one_generation() {
2171        let temp = tree_fs::TreeBuilder::default().create().unwrap();
2172        let path = temp.root.join("audit.log");
2173        fs::write(&path, "old\n").unwrap();
2174        rotate_files(&path, 0).unwrap();
2175        assert_eq!(fs::read_to_string(rotated_path(&path)).unwrap(), "old\n");
2176    }
2177
2178    /// Test inputs are assembled from pieces so this source file itself
2179    /// does not read like a risky command to shell hooks scanning it.
2180    fn j(parts: &[&str]) -> String {
2181        parts.concat()
2182    }
2183
2184    #[test]
2185    fn unescape_invisible_restores_only_invisible_characters() {
2186        let shown = crate::context::escape_invisible("src\u{202e}.txt and b\u{200b}");
2187        assert_eq!(shown, "src\\u{202e}.txt and b\\u{200b}");
2188        assert_eq!(unescape_invisible(&shown), "src\u{202e}.txt and b\u{200b}");
2189        // Printable or invalid code points stay as written.
2190        assert_eq!(unescape_invisible("a\\u{41}b"), "a\\u{41}b");
2191        assert_eq!(unescape_invisible("a\\u{zz}\\u{"), "a\\u{zz}\\u{");
2192        assert_eq!(unescape_invisible("plain"), "plain");
2193    }
2194
2195    #[test]
2196    fn deny_reason_for_outcome_tells_cancel_from_no_tty() {
2197        assert_eq!(
2198            deny_reason::for_outcome(&AuditOutcome::Cancelled),
2199            Some(deny_reason::CANCELLED)
2200        );
2201        assert_eq!(
2202            deny_reason::for_outcome(&AuditOutcome::NoTerminal),
2203            Some(deny_reason::NO_TTY)
2204        );
2205        assert_eq!(deny_reason::for_outcome(&AuditOutcome::Allowed), None);
2206        assert_ne!(deny_reason::CANCELLED, deny_reason::CHALLENGE_FAILED);
2207    }
2208
2209    #[test]
2210    fn stored_blast_radius_detail_is_the_real_text() {
2211        let tmp = tree_fs::TreeBuilder::default().create().unwrap();
2212        let path = tmp.root.join("audit.log");
2213        let mut ev = event(
2214            "e1",
2215            AuditOutcome::Cancelled,
2216            Severity::High,
2217            "2026-02-15T10:00:00Z",
2218        );
2219        ev.blast_radius_detail = Some(crate::context::escape_invisible(
2220            "Deletes 2 paths (src\u{202e}.txt, b)",
2221        ));
2222        log_event(&path, &ev).unwrap();
2223        let line = std::fs::read_to_string(&path).unwrap();
2224        let v: serde_json::Value = serde_json::from_str(line.trim()).unwrap();
2225        assert_eq!(
2226            v["blast_radius_detail"].as_str(),
2227            Some("Deletes 2 paths (src\u{202e}.txt, b)")
2228        );
2229    }
2230
2231    #[test]
2232    fn secrets_are_redacted() {
2233        let cases: Vec<(String, String)> = vec![
2234            (
2235                j(&["mysql -u root -pS3cret! db"]),
2236                j(&["mysql -u root -p*** db"]),
2237            ),
2238            (
2239                j(&["mysqldump --password=S3cret db"]),
2240                j(&["mysqldump --password=*** db"]),
2241            ),
2242            (
2243                j(&["PGPASSWORD=hunter2 psql -h db"]),
2244                j(&["PGPASSWORD=*** psql -h db"]),
2245            ),
2246            (j(&["MYSQL_PWD='a b' mysql"]), j(&["MYSQL_PWD=*** mysql"])),
2247            (
2248                j(&["export GITHUB_TOKEN=abc123; gh repo list"]),
2249                j(&["export GITHUB_TOKEN=***; gh repo list"]),
2250            ),
2251            (
2252                j(&["AWS_SECRET_ACCESS_KEY=xyz aws s3 ls"]),
2253                j(&["AWS_SECRET_ACCESS_KEY=*** aws s3 ls"]),
2254            ),
2255            (
2256                j(&["psql postgres://admin:pa55@db.prod:5432/app -c 'select 1'"]),
2257                j(&["psql postgres://admin:***@db.prod:5432/app -c 'select 1'"]),
2258            ),
2259            (
2260                j(&[r#"curl -H "Authorization: Bearer eyJhbGci.x.y" https://api/x"#]),
2261                j(&[r#"curl -H "Authorization: Bearer ***" https://api/x"#]),
2262            ),
2263            (
2264                j(&["curl -u admin:secret https://h/x"]),
2265                j(&["curl -u admin:*** https://h/x"]),
2266            ),
2267            (
2268                j(&["aws --profile x s3 ls # AKIA", "IOSFODNN7EXAMPLE"]),
2269                j(&["aws --profile x s3 ls # ***"]),
2270            ),
2271            (
2272                j(&["vault login --token s.abcdef"]),
2273                j(&["vault login --token ***"]),
2274            ),
2275            (
2276                j(&["redis-cli -a R3disPw PING"]),
2277                j(&["redis-cli -a *** PING"]),
2278            ),
2279            (
2280                j(&["redis-cli -h prod --pass RdPw33 PING"]),
2281                j(&["redis-cli -h prod --pass *** PING"]),
2282            ),
2283            (
2284                j(&["REDISCLI_AUTH=RcAuth5 redis-cli PING"]),
2285                j(&["REDISCLI_AUTH=*** redis-cli PING"]),
2286            ),
2287            (
2288                j(&["redis-cli -u redis://:UrlRedisPw@prod:6379 PING"]),
2289                j(&["redis-cli -u redis://:***@prod:6379 PING"]),
2290            ),
2291            (
2292                j(&["mongosh -u admin -p MgPw11 --eval 'db.x.find()'"]),
2293                j(&["mongosh -u admin -p *** --eval 'db.x.find()'"]),
2294            ),
2295            (
2296                j(&["mongosh --username admin --password MgPw22 --eval x"]),
2297                j(&["mongosh --username admin --password *** --eval x"]),
2298            ),
2299            (
2300                j(&[
2301                    "clickhouse-client --password ChPw10 -q 'DROP DATA",
2302                    "BASE prod'",
2303                ]),
2304                j(&[
2305                    "clickhouse-client --password *** -q 'DROP DATA",
2306                    "BASE prod'",
2307                ]),
2308            ),
2309            (
2310                j(&["clickhouse-client --password=ChPw11 -q x"]),
2311                j(&["clickhouse-client --password=*** -q x"]),
2312            ),
2313            (
2314                j(&["cqlsh -u cassandra -p CqPw12 -e 'DROP KEY", "SPACE prod'"]),
2315                j(&["cqlsh -u cassandra -p *** -e 'DROP KEY", "SPACE prod'"]),
2316            ),
2317            (
2318                j(&["cqlsh --password CqPw13 db1"]),
2319                j(&["cqlsh --password *** db1"]),
2320            ),
2321            (
2322                j(&["mongosh admin -u root -pMgPw15 --eval x"]),
2323                j(&["mongosh admin -u root -p*** --eval x"]),
2324            ),
2325            (j(&["mongo -pMgPw16 db"]), j(&["mongo -p*** db"])),
2326        ];
2327        for (input, want) in &cases {
2328            let (got, changed) = redact_secrets(input);
2329            assert!(changed, "{input}");
2330            assert_eq!(&got, want, "{input}");
2331        }
2332        for safe in [
2333            "git push -f origin main",
2334            "mkdir -p build && ls build",
2335            "ssh -p22 host",
2336            "docker run -p8080:80 img",
2337            "mysql -p db",
2338            "ls ./node_modules",
2339            "mongosh -u admin -p --eval x",
2340            "redis-cli -h prod PING",
2341            "clickhouse-client --password -q x",
2342            "cqlsh -p --help",
2343            "mongosh --port 27017 db",
2344            "mysql --password mydb",
2345        ] {
2346            let (got, changed) = redact_secrets(safe);
2347            assert!(!changed, "{safe} -> {got}");
2348            assert_eq!(got, safe);
2349        }
2350    }
2351
2352    #[test]
2353    fn redacted_record_keeps_the_original_digest() {
2354        let temp = tree_fs::TreeBuilder::default().create().unwrap();
2355        let path = temp.root.join("audit.log");
2356        let mut ev = event(
2357            "r",
2358            AuditOutcome::Denied,
2359            Severity::High,
2360            "2026-02-15T10:00:00Z",
2361        );
2362        ev.command = j(&["mysql -uroot -phunter2 -e 'select 1'"]);
2363        log_event(&path, &ev).unwrap();
2364        let line = read_log(&path).unwrap();
2365        assert!(!line.contains("hunter2"), "{line}");
2366        let entry: AuditEntry = serde_json::from_str(line.trim()).unwrap();
2367        assert_eq!(entry.command, "mysql -uroot -p*** -e 'select 1'");
2368        assert!(entry.command_redacted);
2369        assert!(!entry.command_truncated);
2370        assert_eq!(
2371            entry.command_sha256.as_deref(),
2372            Some(sha256_hex(ev.command.as_bytes()).as_str())
2373        );
2374        // A command without secrets is stored verbatim, with no digest.
2375        let temp2 = tree_fs::TreeBuilder::default().create().unwrap();
2376        let path2 = temp2.root.join("audit.log");
2377        let ev2 = event(
2378            "s",
2379            AuditOutcome::Denied,
2380            Severity::High,
2381            "2026-02-15T10:00:00Z",
2382        );
2383        log_event(&path2, &ev2).unwrap();
2384        let entry2: AuditEntry = serde_json::from_str(read_log(&path2).unwrap().trim()).unwrap();
2385        assert!(!entry2.command_redacted);
2386        assert!(entry2.command_sha256.is_none());
2387    }
2388}