guardrail_proxy/
audit_log.rs1use 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;
37pub const AUDIT_TARGET: &str = "guardrail::audit";
42
43#[derive(Debug, thiserror::Error)]
45pub enum AuditLogError {
46 #[error("failed to create audit log directory '{path}': {source}")]
48 CreateDir {
49 path: String,
51 #[source]
53 source: std::io::Error,
54 },
55 #[error("failed to open audit log file '{path}': {source}")]
57 OpenFile {
58 path: String,
60 #[source]
62 source: std::io::Error,
63 },
64}
65
66struct SizeRotatingWriter {
81 inner: Mutex<SizeRotatingState>,
82}
83
84struct SizeRotatingState {
85 path: PathBuf,
86 file: Option<File>,
89 current_size: u64,
90 max_size_bytes: u64,
91}
92
93impl SizeRotatingWriter {
94 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 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 if let Some(file) = self.file.as_mut() {
162 file.flush()?;
163 }
164 self.file.take(); 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 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(()), }
211 }
212}
213
214pub 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 assert!(
337 contents.contains("pipeline decision") || contents.contains("decision"),
338 "missing audit event in: {contents:?}"
339 );
340 assert!(!contents.contains("should not appear"));
342
343 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 #[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}