Skip to main content

guardrail_proxy/
audit_log.rs

1//! NDJSON audit log writer (spec §10).
2//!
3//! When `observability.audit_log.enabled = true`, every pipeline decision is
4//! written as a newline-delimited JSON record to `observability.audit_log.path`.
5//! When the file would exceed `observability.audit_log.max_size_mb`, it is
6//! rotated: the current file is renamed to `<path>.<unix_timestamp>` and a
7//! fresh file is opened at `path`. Rotation is checked before each write
8//! (not on a timer), so the file never grows meaningfully past the
9//! configured limit.
10//!
11//! The returned [`tracing_appender::non_blocking::WorkerGuard`] must be kept
12//! alive for the process lifetime; dropping it stops the background writer.
13//!
14//! # Example
15//!
16//! ```rust,no_run
17//! use guardrail_config::schema::AuditLogConfig;
18//! use guardrail_proxy::audit_log;
19//! use tracing_subscriber::prelude::*;
20//!
21//! let config = AuditLogConfig {
22//!     enabled: true,
23//!     path: "/var/log/guardrail/audit.ndjson".into(),
24//!     max_size_mb: 100,
25//! };
26//!
27//! let _ = audit_log::build_layer(&config).unwrap();
28//! ```
29
30use std::fs::{File, OpenOptions};
31use std::io::{self, Write};
32use std::path::{Path, PathBuf};
33use std::sync::Mutex;
34
35use guardrail_config::schema::AuditLogConfig;
36use tracing_appender::non_blocking::WorkerGuard;
37// filter_fn/FmtSpan are composed by callers when constructing concrete
38// `fmt` layers; this module only builds the writer+guard pair.
39
40/// The tracing target audit records are emitted under.
41pub const AUDIT_TARGET: &str = "guardrail::audit";
42
43/// Errors that can occur while setting up the audit log writer.
44#[derive(Debug, thiserror::Error)]
45pub enum AuditLogError {
46    /// The parent directory could not be created.
47    #[error("failed to create audit log directory '{path}': {source}")]
48    CreateDir {
49        /// The directory path.
50        path: String,
51        /// Underlying I/O error.
52        #[source]
53        source: std::io::Error,
54    },
55    /// The audit log file could not be opened.
56    #[error("failed to open audit log file '{path}': {source}")]
57    OpenFile {
58        /// The file path.
59        path: String,
60        /// Underlying I/O error.
61        #[source]
62        source: std::io::Error,
63    },
64}
65
66/// A [`Write`] implementation that rotates the underlying file by renaming
67/// it to `<path>.<unix_timestamp>` once it would exceed `max_size_bytes`,
68/// then opening a fresh file at `path`.
69///
70/// Rotation is checked before each `write_all` call rather than on a timer,
71/// so a burst of writes can momentarily exceed the threshold within a single
72/// write (a single audit record is always written atomically, never split
73/// across the rotation boundary) but never by more than one record's worth.
74///
75/// Wrapped in a [`Mutex`] so it satisfies `Write + Send + 'static` as
76/// required by [`tracing_appender::non_blocking`] — the non-blocking
77/// appender already serializes writes onto a single background thread, so
78/// the lock is never contended in practice, but the type system requires
79/// `Sync` regardless since `non_blocking` stores the writer behind an `Arc`.
80struct SizeRotatingWriter {
81    inner: Mutex<SizeRotatingState>,
82}
83
84struct SizeRotatingState {
85    path: PathBuf,
86    /// `None` only transiently during `rotate()`, between dropping the old
87    /// handle and opening the new one — never observable outside this type.
88    file: Option<File>,
89    current_size: u64,
90    max_size_bytes: u64,
91}
92
93impl SizeRotatingWriter {
94    /// Open (or create) the file at `path` and prepare to rotate it once it
95    /// would exceed `max_size_bytes`.
96    fn open(path: &Path, max_size_bytes: u64) -> io::Result<Self> {
97        let file = OpenOptions::new().create(true).append(true).open(path)?;
98        let current_size = file.metadata()?.len();
99
100        Ok(Self {
101            inner: Mutex::new(SizeRotatingState {
102                path: path.to_path_buf(),
103                file: Some(file),
104                current_size,
105                max_size_bytes,
106            }),
107        })
108    }
109}
110
111impl SizeRotatingState {
112    /// Rotate the current file: rename it to `<path>.<unix_timestamp>` and
113    /// open a fresh file at `path`. If a file with the timestamped name
114    /// already exists (clock resolution collision), append an incrementing
115    /// suffix until a free name is found.
116    ///
117    /// The old file handle is flushed and dropped (via `self.file.take()`)
118    /// *before* the rename syscall runs. On POSIX this would work either way
119    /// (rename operates on the inode regardless of open handles), but on
120    /// Windows `std::fs::File` does not request `FILE_SHARE_DELETE` by
121    /// default, so renaming a file that is still open elsewhere in the
122    /// process can fail with an access-denied error. Dropping the handle
123    /// first avoids that failure mode on every platform.
124    ///
125    /// `self.file` is `None` only for the brief window between the
126    /// `.take()` and the reassignment a few lines later; if anything in
127    /// between returns early via `?`, the writer is left in a permanently
128    /// broken state (every subsequent `write()` call returns an error)
129    /// rather than silently losing data or writing to a stale handle —
130    /// this is the only sound choice once the rename itself has failed,
131    /// since there is no original file left to fall back to write into.
132    fn rotate(&mut self) -> io::Result<()> {
133        let timestamp = std::time::SystemTime::now()
134            .duration_since(std::time::UNIX_EPOCH)
135            .map(|d| d.as_secs())
136            .unwrap_or(0);
137
138        let rotated_extension = |suffix: Option<u32>| {
139            let base_ext = self
140                .path
141                .extension()
142                .and_then(|e| e.to_str())
143                .unwrap_or("ndjson");
144            match suffix {
145                Some(n) => format!("{base_ext}.{timestamp}.{n}"),
146                None => format!("{base_ext}.{timestamp}"),
147            }
148        };
149
150        let mut rotated_path = self.path.with_extension(rotated_extension(None));
151        let mut suffix = 1u32;
152        while rotated_path.exists() {
153            rotated_path = self.path.with_extension(rotated_extension(Some(suffix)));
154            suffix += 1;
155        }
156
157        // Flush any buffered bytes, then explicitly drop the handle (via
158        // `.take()`) so no file-share restriction (most relevant on
159        // Windows, where `std::fs::File` does not request
160        // `FILE_SHARE_DELETE` by default) blocks the rename below.
161        if let Some(file) = self.file.as_mut() {
162            file.flush()?;
163        }
164        self.file.take(); // drops the old handle here
165
166        std::fs::rename(&self.path, &rotated_path)?;
167
168        self.file = Some(
169            OpenOptions::new()
170                .create(true)
171                .append(true)
172                .open(&self.path)?,
173        );
174        self.current_size = 0;
175
176        Ok(())
177    }
178}
179
180impl Write for SizeRotatingWriter {
181    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
182        let mut state = self
183            .inner
184            .lock()
185            .unwrap_or_else(std::sync::PoisonError::into_inner);
186
187        // Rotate first if this write would push us over the threshold and
188        // we've already written at least one byte (never rotate an empty
189        // file just because a single record is itself huge).
190        if state.current_size > 0 && state.current_size + buf.len() as u64 > state.max_size_bytes {
191            state.rotate()?;
192        }
193
194        let file = state.file.as_mut().ok_or_else(|| {
195            io::Error::other("audit log file handle unexpectedly absent after rotation")
196        })?;
197        let written = file.write(buf)?;
198        state.current_size += written as u64;
199        Ok(written)
200    }
201
202    fn flush(&mut self) -> io::Result<()> {
203        let mut state = self
204            .inner
205            .lock()
206            .unwrap_or_else(std::sync::PoisonError::into_inner);
207        match state.file.as_mut() {
208            Some(file) => file.flush(),
209            None => Ok(()), // transient mid-rotation state; nothing to flush
210        }
211    }
212}
213
214/// Build a `tracing_subscriber::Layer` writing audit events as NDJSON to
215/// `config.path`, rotating by size per `config.max_size_mb`. Returns
216/// `Ok(None)` when `config.enabled = false`.
217///
218/// # Errors
219///
220/// Returns [`AuditLogError::CreateDir`] if the parent directory cannot be
221/// created, or [`AuditLogError::OpenFile`] if the audit log file itself
222/// cannot be opened (e.g. permissions).
223pub fn build_layer(
224    config: &AuditLogConfig,
225) -> Result<Option<(tracing_appender::non_blocking::NonBlocking, WorkerGuard)>, AuditLogError>
226where
227{
228    if !config.enabled {
229        return Ok(None);
230    }
231
232    let audit_path = Path::new(&config.path);
233    if let Some(parent) = audit_path.parent() {
234        if !parent.as_os_str().is_empty() {
235            std::fs::create_dir_all(parent).map_err(|source| AuditLogError::CreateDir {
236                path: parent.to_string_lossy().into_owned(),
237                source,
238            })?;
239        }
240    }
241
242    let max_size_bytes = config.max_size_mb.saturating_mul(1024 * 1024);
243    let writer = SizeRotatingWriter::open(audit_path, max_size_bytes).map_err(|source| {
244        AuditLogError::OpenFile {
245            path: config.path.clone(),
246            source,
247        }
248    })?;
249
250    let (non_blocking, guard) = tracing_appender::non_blocking(writer);
251
252    Ok(Some((non_blocking, guard)))
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use crate::audit::AuditRecord;
259    use guardrail_core::{decision::Decision, test_helpers::clean_request};
260    use tracing_subscriber::filter::filter_fn;
261    use tracing_subscriber::prelude::*;
262
263    fn temp_config() -> (tempfile::TempDir, AuditLogConfig) {
264        let dir = tempfile::tempdir().unwrap();
265        let path = dir
266            .path()
267            .join("audit-test.ndjson")
268            .to_string_lossy()
269            .into_owned();
270        let config = AuditLogConfig {
271            enabled: true,
272            path,
273            max_size_mb: 100,
274        };
275        (dir, config)
276    }
277
278    #[test]
279    fn test_disabled_returns_none() {
280        let config = AuditLogConfig {
281            enabled: false,
282            path: "/tmp/x.ndjson".into(),
283            max_size_mb: 100,
284        };
285        assert!(build_layer(&config).unwrap().is_none());
286    }
287
288    #[test]
289    fn test_builds_with_valid_config() {
290        let (_dir, config) = temp_config();
291        assert!(build_layer(&config).unwrap().is_some());
292    }
293
294    #[test]
295    fn test_creates_parent_directory() {
296        let tmp = tempfile::tempdir().unwrap();
297        let path = tmp
298            .path()
299            .join("sub")
300            .join("dir")
301            .join("audit.ndjson")
302            .to_string_lossy()
303            .into_owned();
304        let config = AuditLogConfig {
305            enabled: true,
306            path,
307            max_size_mb: 100,
308        };
309        assert!(build_layer(&config).is_ok());
310    }
311
312    #[test]
313    fn test_writes_audit_events_as_ndjson() {
314        let (_dir, config) = temp_config();
315        let path = config.path.clone();
316
317        let (non_blocking, _guard) = build_layer(&config).unwrap().unwrap();
318        let layer = tracing_subscriber::fmt::layer()
319            .json()
320            .with_writer(non_blocking)
321            .with_filter(filter_fn(|meta| meta.target().starts_with(AUDIT_TARGET)));
322
323        let subscriber = tracing_subscriber::registry().with(layer);
324
325        tracing::subscriber::with_default(subscriber, || {
326            let req = clean_request();
327            AuditRecord::from_decision(&req, &Decision::Allow, 0.05, 120.0).emit();
328            tracing::info!(target: "unrelated::module", "should not appear");
329        });
330
331        std::thread::sleep(std::time::Duration::from_millis(250));
332
333        let contents = std::fs::read_to_string(&path).unwrap_or_default();
334
335        // Must contain an audit event.
336        assert!(
337            contents.contains("pipeline decision") || contents.contains("decision"),
338            "missing audit event in: {contents:?}"
339        );
340        // Must NOT contain the unrelated event.
341        assert!(!contents.contains("should not appear"));
342
343        // Every non-empty line must be valid JSON.
344        for line in contents.lines().filter(|l| !l.trim().is_empty()) {
345            serde_json::from_str::<serde_json::Value>(line)
346                .unwrap_or_else(|e| panic!("not valid JSON: {line:?}: {e}"));
347        }
348    }
349
350    // ── SizeRotatingWriter unit tests ───────────────────────────────────────
351    // These exercise the rotation logic directly (no tracing machinery, no
352    // async flushing delay) for fast, precise coverage of the size threshold.
353
354    #[test]
355    fn test_rotating_writer_no_rotation_under_threshold() {
356        let dir = tempfile::tempdir().unwrap();
357        let path = dir.path().join("audit.ndjson");
358
359        let mut writer = SizeRotatingWriter::open(&path, 1024).unwrap();
360        writer.write_all(b"a short line\n").unwrap();
361        writer.flush().unwrap();
362
363        let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
364        assert_eq!(
365            entries.len(),
366            1,
367            "expected exactly one file, found: {entries:?}"
368        );
369
370        let contents = std::fs::read_to_string(&path).unwrap();
371        assert_eq!(contents, "a short line\n");
372    }
373
374    #[test]
375    fn test_rotating_writer_rotates_when_threshold_exceeded() {
376        let dir = tempfile::tempdir().unwrap();
377        let path = dir.path().join("audit.ndjson");
378
379        let mut writer = SizeRotatingWriter::open(&path, 20).unwrap();
380        writer.write_all(b"0123456789012345\n").unwrap();
381        writer.flush().unwrap();
382        writer.write_all(b"this write pushes us over\n").unwrap();
383        writer.flush().unwrap();
384
385        let entries: Vec<_> = std::fs::read_dir(dir.path())
386            .unwrap()
387            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
388            .collect();
389
390        assert_eq!(
391            entries.len(),
392            2,
393            "expected original + 1 rotated file, found: {entries:?}"
394        );
395        assert!(entries.iter().any(|n| n == "audit.ndjson"));
396        assert!(
397            entries
398                .iter()
399                .any(|n| n.starts_with("audit.") && n != "audit.ndjson"),
400            "expected a rotated backup file, found: {entries:?}"
401        );
402
403        let current_contents = std::fs::read_to_string(&path).unwrap();
404        assert_eq!(current_contents, "this write pushes us over\n");
405    }
406
407    #[test]
408    fn test_rotating_writer_preserves_old_content_in_backup() {
409        let dir = tempfile::tempdir().unwrap();
410        let path = dir.path().join("audit.ndjson");
411
412        let mut writer = SizeRotatingWriter::open(&path, 10).unwrap();
413        writer.write_all(b"first\n").unwrap();
414        writer.flush().unwrap();
415        writer.write_all(b"second\n").unwrap();
416        writer.flush().unwrap();
417
418        let backup = std::fs::read_dir(dir.path())
419            .unwrap()
420            .map(|e| e.unwrap().path())
421            .find(|p| {
422                p.file_name()
423                    .unwrap()
424                    .to_string_lossy()
425                    .starts_with("audit.")
426                    && p.file_name().unwrap() != "audit.ndjson"
427            })
428            .expect("expected a rotated backup file");
429
430        let backup_contents = std::fs::read_to_string(&backup).unwrap();
431        assert_eq!(backup_contents, "first\n");
432
433        let current_contents = std::fs::read_to_string(&path).unwrap();
434        assert_eq!(current_contents, "second\n");
435    }
436
437    #[test]
438    fn test_rotating_writer_never_rotates_an_empty_file() {
439        let dir = tempfile::tempdir().unwrap();
440        let path = dir.path().join("audit.ndjson");
441
442        let mut writer = SizeRotatingWriter::open(&path, 5).unwrap();
443        writer
444            .write_all(b"this single line is longer than 5 bytes\n")
445            .unwrap();
446        writer.flush().unwrap();
447
448        let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
449        assert_eq!(
450            entries.len(),
451            1,
452            "must not rotate an empty file: {entries:?}"
453        );
454    }
455
456    #[test]
457    fn test_rotating_writer_resumes_existing_file_size() {
458        let dir = tempfile::tempdir().unwrap();
459        let path = dir.path().join("audit.ndjson");
460
461        std::fs::write(&path, b"pre-existing content (20 bytes)\n").unwrap();
462        let preexisting_size = std::fs::metadata(&path).unwrap().len();
463        assert!(preexisting_size > 0);
464
465        let mut writer = SizeRotatingWriter::open(&path, preexisting_size + 5).unwrap();
466        writer.write_all(b"more than 5 extra bytes here\n").unwrap();
467        writer.flush().unwrap();
468
469        let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
470        assert_eq!(
471            entries.len(),
472            2,
473            "expected rotation on resumed file size, found: {entries:?}"
474        );
475    }
476
477    #[test]
478    fn test_max_size_mb_zero_does_not_panic() {
479        let dir = tempfile::tempdir().unwrap();
480        let path = dir.path().join("audit.ndjson");
481
482        let mut writer = SizeRotatingWriter::open(&path, 0).unwrap();
483        writer.write_all(b"first\n").unwrap();
484        writer.flush().unwrap();
485        writer.write_all(b"second\n").unwrap();
486        writer.flush().unwrap();
487
488        let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
489        assert!(!entries.is_empty());
490    }
491}