fix(auth): tail audit log as bytes and check last byte by seeking
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c757db209d
commit
fbaeeca60c
1 file changed
+40
-8
@@ -5,7 +5,7 @@ use crate::error::{AcauaError, Result};
|
|||||||
pub const CORRUPT_ACTION: &str = "audit.corrupt_line";
|
pub const CORRUPT_ACTION: &str = "audit.corrupt_line";
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::fs::{self, OpenOptions};
|
use std::fs::{self, OpenOptions};
|
||||||
use std::io::Write;
|
use std::io::{Read, Seek, SeekFrom, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use time::format_description::well_known::Rfc3339;
|
use time::format_description::well_known::Rfc3339;
|
||||||
use time::OffsetDateTime;
|
use time::OffsetDateTime;
|
||||||
@@ -51,17 +51,20 @@ impl AuditLog {
|
|||||||
let mut line = serde_json::to_vec(&AuditEntry { ts, event })?;
|
let mut line = serde_json::to_vec(&AuditEntry { ts, event })?;
|
||||||
line.push(b'\n');
|
line.push(b'\n');
|
||||||
let mut opts = OpenOptions::new();
|
let mut opts = OpenOptions::new();
|
||||||
opts.append(true).create(true);
|
opts.read(true).append(true).create(true);
|
||||||
set_mode(&mut opts, 0o600);
|
set_mode(&mut opts, 0o600);
|
||||||
let path = self.dir.join(AUDIT_FILE);
|
let path = self.dir.join(AUDIT_FILE);
|
||||||
// A crash can leave an unterminated fragment; close it so the new
|
// A crash can leave an unterminated fragment; close it so the new
|
||||||
// entry starts on its own line. `tail` reports the fragment.
|
// entry starts on its own line. `tail` reports the fragment.
|
||||||
if let Ok(existing) = fs::read(&path) {
|
let mut file = opts.open(&path)?;
|
||||||
if existing.last().is_some_and(|b| *b != b'\n') {
|
if file.metadata()?.len() > 0 {
|
||||||
|
let mut last = [0u8; 1];
|
||||||
|
file.seek(SeekFrom::End(-1))?;
|
||||||
|
file.read_exact(&mut last)?;
|
||||||
|
if last[0] != b'\n' {
|
||||||
line.insert(0, b'\n');
|
line.insert(0, b'\n');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut file = opts.open(&path)?;
|
|
||||||
file.write_all(&line)?;
|
file.write_all(&line)?;
|
||||||
file.sync_all()?;
|
file.sync_all()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -70,12 +73,16 @@ impl AuditLog {
|
|||||||
/// Last `limit` entries, oldest first.
|
/// Last `limit` entries, oldest first.
|
||||||
pub fn tail(&self, limit: usize) -> Result<Vec<AuditEntry>> {
|
pub fn tail(&self, limit: usize) -> Result<Vec<AuditEntry>> {
|
||||||
let _lock = DirLock::acquire(&self.dir, false)?;
|
let _lock = DirLock::acquire(&self.dir, false)?;
|
||||||
let raw = match fs::read_to_string(self.dir.join(AUDIT_FILE)) {
|
let raw = match fs::read(self.dir.join(AUDIT_FILE)) {
|
||||||
Ok(raw) => raw,
|
Ok(raw) => raw,
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||||
Err(e) => return Err(e.into()),
|
Err(e) => return Err(e.into()),
|
||||||
};
|
};
|
||||||
let lines: Vec<&str> = raw.lines().filter(|l| !l.trim().is_empty()).collect();
|
// Bytes, not str: a torn write may cut a multi-byte character.
|
||||||
|
let lines: Vec<&[u8]> = raw
|
||||||
|
.split(|b| *b == b'\n')
|
||||||
|
.filter(|l| !l.iter().all(u8::is_ascii_whitespace))
|
||||||
|
.collect();
|
||||||
let start = lines.len().saturating_sub(limit);
|
let start = lines.len().saturating_sub(limit);
|
||||||
// A torn line does not fail the read: it is surfaced as a visible
|
// A torn line does not fail the read: it is surfaced as a visible
|
||||||
// `audit.corrupt_line` entry (ok = false) at its position.
|
// `audit.corrupt_line` entry (ok = false) at its position.
|
||||||
@@ -83,7 +90,7 @@ impl AuditLog {
|
|||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(i, l)| {
|
.map(|(i, l)| {
|
||||||
serde_json::from_str(l).unwrap_or_else(|_| AuditEntry {
|
serde_json::from_slice(l).unwrap_or_else(|_| AuditEntry {
|
||||||
ts: String::new(),
|
ts: String::new(),
|
||||||
event: AuditEvent {
|
event: AuditEvent {
|
||||||
action: CORRUPT_ACTION.into(),
|
action: CORRUPT_ACTION.into(),
|
||||||
@@ -168,4 +175,29 @@ mod tests {
|
|||||||
assert_eq!(actions, ["a0", CORRUPT_ACTION, "a1"]);
|
assert_eq!(actions, ["a0", CORRUPT_ACTION, "a1"]);
|
||||||
assert!(t[2].event.ok);
|
assert!(t[2].event.ok);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn torn_multibyte_character_does_not_fail_tail() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let log = AuditLog::open(dir.path());
|
||||||
|
let ev = |a: &str| AuditEvent {
|
||||||
|
action: a.into(),
|
||||||
|
ok: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
log.record(ev("a0")).unwrap();
|
||||||
|
let path = dir.path().join(AUDIT_FILE);
|
||||||
|
// "é" is 0xC3 0xA9; cut after the first byte.
|
||||||
|
let mut f = OpenOptions::new().append(true).open(&path).unwrap();
|
||||||
|
f.write_all(b"{\"ts\":\"x\",\"action\":\"caf\xC3").unwrap();
|
||||||
|
drop(f);
|
||||||
|
let t = log.tail(10).unwrap();
|
||||||
|
assert_eq!(t.len(), 2);
|
||||||
|
assert_eq!(t[0].event.action, "a0");
|
||||||
|
assert_eq!(t[1].event.action, CORRUPT_ACTION);
|
||||||
|
log.record(ev("a1")).unwrap();
|
||||||
|
let t = log.tail(10).unwrap();
|
||||||
|
let actions: Vec<_> = t.iter().map(|e| e.event.action.as_str()).collect();
|
||||||
|
assert_eq!(actions, ["a0", CORRUPT_ACTION, "a1"]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user