Skip to main content

vtcode_core/dotfile_protection/
audit.rs

1//! Immutable audit logging for dotfile access attempts.
2//!
3//! Provides comprehensive, tamper-evident logging of all dotfile
4//! access attempts with timestamps, outcomes, and contextual information.
5
6use std::fs::{File, OpenOptions};
7use std::io::{BufRead, BufReader, Write};
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11use anyhow::{Context, Result};
12use chrono::{DateTime, Utc};
13use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15use tokio::sync::Mutex;
16use vtcode_commons::VtCodePaths;
17use vtcode_commons::utils::calculate_sha256;
18
19/// Outcome of a dotfile access attempt.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum AuditOutcome {
23    /// Access was allowed after user confirmation.
24    AllowedWithConfirmation,
25    /// Access was allowed via whitelist (with secondary auth).
26    AllowedViaWhitelist,
27    /// Access was blocked (no confirmation given).
28    Blocked,
29    /// Access was denied (policy violation).
30    Denied,
31    /// User explicitly rejected the modification.
32    UserRejected,
33    /// Access was allowed without confirmation (protection disabled).
34    AllowedUnprotected,
35    /// Access is awaiting the user's decision (confirmation requested).
36    PendingConfirmation,
37}
38
39impl std::fmt::Display for AuditOutcome {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        match self {
42            AuditOutcome::AllowedWithConfirmation => write!(f, "ALLOWED_WITH_CONFIRMATION"),
43            AuditOutcome::AllowedViaWhitelist => write!(f, "ALLOWED_VIA_WHITELIST"),
44            AuditOutcome::Blocked => write!(f, "BLOCKED"),
45            AuditOutcome::Denied => write!(f, "DENIED"),
46            AuditOutcome::UserRejected => write!(f, "USER_REJECTED"),
47            AuditOutcome::AllowedUnprotected => write!(f, "ALLOWED_UNPROTECTED"),
48            AuditOutcome::PendingConfirmation => write!(f, "PENDING_CONFIRMATION"),
49        }
50    }
51}
52
53/// Type of access being attempted.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum AccessType {
57    /// Read access to a dotfile.
58    Read,
59    /// Write access to a dotfile.
60    Write,
61    /// Create a new dotfile.
62    Create,
63    /// Delete a dotfile.
64    Delete,
65    /// Modify an existing dotfile.
66    Modify,
67    /// Append to a dotfile.
68    Append,
69}
70
71impl std::fmt::Display for AccessType {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        match self {
74            AccessType::Read => write!(f, "READ"),
75            AccessType::Write => write!(f, "WRITE"),
76            AccessType::Create => write!(f, "CREATE"),
77            AccessType::Delete => write!(f, "DELETE"),
78            AccessType::Modify => write!(f, "MODIFY"),
79            AccessType::Append => write!(f, "APPEND"),
80        }
81    }
82}
83
84/// A single audit log entry.
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct AuditEntry {
87    /// Unique identifier for this entry.
88    pub id: String,
89    /// Timestamp of the access attempt (UTC).
90    pub timestamp: DateTime<Utc>,
91    /// Path to the dotfile being accessed.
92    pub file_path: String,
93    /// Type of access attempted.
94    pub access_type: AccessType,
95    /// Outcome of the access attempt.
96    pub outcome: AuditOutcome,
97    /// Tool or operation that initiated the access.
98    pub initiator: String,
99    /// Session identifier.
100    pub session_id: String,
101    /// Description of proposed changes (if applicable).
102    pub proposed_changes: Option<String>,
103    /// Hash of the previous entry (for tamper detection).
104    pub previous_hash: String,
105    /// Hash of this entry (computed after creation).
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub entry_hash: Option<String>,
108    /// Additional context or reason.
109    pub context: Option<String>,
110    /// Whether this was during an automated operation.
111    pub during_automation: bool,
112}
113
114impl AuditEntry {
115    /// Create a new audit entry.
116    pub fn new(
117        file_path: impl Into<String>,
118        access_type: AccessType,
119        outcome: AuditOutcome,
120        initiator: impl Into<String>,
121        session_id: impl Into<String>,
122        previous_hash: impl Into<String>,
123    ) -> Self {
124        Self {
125            id: uuid::Uuid::new_v4().to_string(),
126            timestamp: Utc::now(),
127            file_path: file_path.into(),
128            access_type,
129            outcome,
130            initiator: initiator.into(),
131            session_id: session_id.into(),
132            proposed_changes: None,
133            previous_hash: previous_hash.into(),
134            entry_hash: None,
135            context: None,
136            during_automation: false,
137        }
138    }
139
140    /// Set proposed changes description.
141    pub fn with_proposed_changes(mut self, changes: impl Into<String>) -> Self {
142        self.proposed_changes = Some(changes.into());
143        self
144    }
145
146    /// Set context/reason.
147    pub fn with_context(mut self, context: impl Into<String>) -> Self {
148        self.context = Some(context.into());
149        self
150    }
151
152    /// Mark as during automation.
153    pub fn during_automation(mut self) -> Self {
154        self.during_automation = true;
155        self
156    }
157
158    /// Compute and set the entry hash.
159    pub fn finalize(mut self) -> Self {
160        self.entry_hash = Some(self.compute_hash());
161        self
162    }
163
164    /// Compute SHA-256 hash of the entry (excluding entry_hash field).
165    fn compute_hash(&self) -> String {
166        let mut hasher = Sha256::new();
167        hasher.update(self.id.as_bytes());
168        hasher.update(self.timestamp.to_rfc3339().as_bytes());
169        hasher.update(self.file_path.as_bytes());
170        hasher.update(format!("{:?}", self.access_type).as_bytes());
171        hasher.update(format!("{:?}", self.outcome).as_bytes());
172        hasher.update(self.initiator.as_bytes());
173        hasher.update(self.session_id.as_bytes());
174        hasher.update(self.previous_hash.as_bytes());
175        if let Some(ref changes) = self.proposed_changes {
176            hasher.update(changes.as_bytes());
177        }
178        if let Some(ref ctx) = self.context {
179            hasher.update(ctx.as_bytes());
180        }
181        hasher.update([self.during_automation as u8]);
182        calculate_sha256(&hasher.finalize())
183    }
184
185    /// Verify the entry hash is valid.
186    pub fn verify(&self) -> bool {
187        self.entry_hash.as_ref().is_some_and(|hash| *hash == self.compute_hash())
188    }
189}
190
191/// Immutable audit log for dotfile access.
192///
193/// **Single-instance invariant**: exactly one `AuditLog` should exist per log
194/// file path. The `write_lock` and `last_hash` are in-process `Arc<Mutex>`
195/// fields — two separate instances for the same path would have independent
196/// locks and chain-hash caches, allowing interleaved appends that corrupt the
197/// tamper-evident chain. The sole production caller (`DotfileGuardian::new`)
198/// respects this by constructing one instance and sharing it via `Arc`.
199pub struct AuditLog {
200    /// Path to the log file.
201    log_path: PathBuf,
202    /// Lock for serializing writes and reads. Uses `tokio::sync::Mutex` so an
203    /// `OwnedMutexGuard` can be moved into `spawn_blocking` closures, keeping
204    /// operations serialized even if the calling task is cancelled.
205    write_lock: Arc<Mutex<()>>,
206    /// Hash of the last entry (for chaining). Uses `tokio::sync::Mutex` so an
207    /// `OwnedMutexGuard<String>` can be moved into `spawn_blocking` alongside
208    /// the write-lock guard — both survive task cancellation inside the
209    /// blocking closure, and no `std::sync::Mutex` poisoning can occur.
210    ///
211    /// Lock ordering: always acquire `write_lock` before `last_hash`. No
212    /// method acquires `last_hash` without first holding `write_lock`.
213    last_hash: Arc<Mutex<String>>,
214}
215
216impl AuditLog {
217    /// Create or open an audit log at the specified path.
218    pub async fn new(log_path: impl AsRef<Path>) -> Result<Self> {
219        let log_path = log_path.as_ref().to_path_buf();
220
221        // Create parent directories if needed
222        if let Some(parent) = log_path.parent() {
223            VtCodePaths::ensure_user_dir(parent)
224                .with_context(|| format!("Failed to create audit log directory: {parent:?}"))?;
225        }
226
227        // `read_last_hash` does a blocking file seek+read; run it off the async
228        // executor. See `# Blocking` docs in `src/agent/runloop/git.rs`.
229        let last_hash = if log_path.exists() {
230            let path = log_path.clone();
231            tokio::task::spawn_blocking(move || Self::read_last_hash(&path))
232                .await
233                .context("audit log hash read task panicked")??
234        } else {
235            // Genesis hash
236            "0000000000000000000000000000000000000000000000000000000000000000".to_string()
237        };
238
239        Ok(Self {
240            log_path,
241            write_lock: Arc::new(Mutex::new(())),
242            last_hash: Arc::new(Mutex::new(last_hash)),
243        })
244    }
245
246    /// Read the last entry's hash from the log file.
247    ///
248    /// Only the tail of the file is scanned (bounded window) so startup cost is
249    /// `O(window)` rather than `O(file size)` — the audit log grows unbounded
250    /// over the tool's lifetime, and the prior full-file scan made launch time
251    /// scale with historical audit volume.
252    fn read_last_hash(log_path: &Path) -> Result<String> {
253        use std::io::{Read, Seek, SeekFrom};
254
255        const DEFAULT_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000";
256
257        let mut file = File::open(log_path).with_context(|| "Failed to open audit log")?;
258        let len = file.metadata().with_context(|| "Failed to read audit log metadata")?.len();
259        if len == 0 {
260            return Ok(DEFAULT_HASH.to_string());
261        }
262
263        // Window large enough to contain the final (and longest plausible)
264        // entry; capped so the scan cost is bounded regardless of log size.
265        let window: u64 = (1 << 18).min(len); // 256 KiB cap
266        file.seek(SeekFrom::End(-(window as i64)))
267            .with_context(|| "Failed to seek audit log")?;
268        let mut buf = Vec::with_capacity(window as usize);
269        file.read_to_end(&mut buf).with_context(|| "Failed to read audit log tail")?;
270
271        let text = String::from_utf8_lossy(&buf);
272        let mut last_hash = DEFAULT_HASH.to_string();
273        for raw in text.lines().rev() {
274            let raw = raw.trim_end_matches(['\n', '\r']);
275            if raw.trim().is_empty() {
276                continue;
277            }
278            if let Ok(entry) = serde_json::from_str::<AuditEntry>(raw)
279                && let Some(hash) = entry.entry_hash
280            {
281                last_hash = hash;
282                break;
283            }
284        }
285        Ok(last_hash)
286    }
287
288    /// Log an access attempt.
289    ///
290    /// Both `write_lock` and `last_hash` are acquired as `OwnedMutexGuard`s
291    /// and moved into the `spawn_blocking` closure so that:
292    ///
293    /// 1. Appends stay serialized even if the calling task is cancelled —
294    ///    both guards survive in the blocking closure until the IO finishes.
295    /// 2. `last_hash` is updated only after the full append succeeds (the
296    ///    line is in the OS page cache, visible to subsequent reads) but
297    ///    before `sync_all()`. If `sync_all()` fails, the entry is still
298    ///    readable and the chain is consistent. If `open` or `write_all`
299    ///    fails, `last_hash` is not updated **and** any partial bytes are
300    ///    truncated back to the pre-append length, so the file never has a
301    ///    malformed tail that would break future reads.
302    pub async fn log(&self, mut entry: AuditEntry) -> Result<()> {
303        let write_guard = self.write_lock.clone().lock_owned().await;
304        let mut hash_guard = self.last_hash.clone().lock_owned().await;
305
306        // Build the finalized entry under serialization.
307        entry.previous_hash = hash_guard.clone();
308        let entry = entry.finalize();
309        let new_hash = entry.entry_hash.clone();
310        let json = serde_json::to_string(&entry).with_context(|| "Failed to serialize audit entry")?;
311
312        // File open + write + fsync are blocking; run them off the async
313        // executor. Both owned guards are moved into the closure so operations
314        // stay serialized even if the caller is cancelled. See `# Blocking`
315        // docs in `src/agent/runloop/git.rs`.
316        let log_path = self.log_path.clone();
317        tokio::task::spawn_blocking(move || -> Result<()> {
318            let _write_guard = write_guard; // held until closure returns
319
320            Self::append_entry_blocking(&log_path, &json)?;
321
322            // The append succeeded — the full line is in the OS page cache and
323            // visible to subsequent reads. Update the in-memory chain hash now,
324            // before fsync. An fsync failure does NOT undo the page-cache
325            // write, so the chain stays consistent with the readable file.
326            if let Some(hash) = new_hash {
327                *hash_guard = hash;
328            }
329
330            // Best-effort durability. A failure here does not roll back the
331            // append; the entry is readable and the chain is consistent.
332            // Reopen for sync_all to avoid keeping the append handle open
333            // longer than necessary.
334            let sync_result = File::open(&log_path).and_then(|f| f.sync_all());
335
336            if let Err(e) = sync_result {
337                // Chain hash already matches the readable entry. Report the
338                // durability error but keep in-memory state consistent.
339                drop(hash_guard);
340                return Err(e).with_context(|| "Failed to sync audit log");
341            }
342
343            drop(hash_guard);
344            Ok(())
345        })
346        .await
347        .context("audit log write task panicked")?
348    }
349
350    /// Append one finalized JSON line to the audit log file.
351    ///
352    /// Records the pre-append file length and truncates back to it on any
353    /// `write_all` failure, ensuring the file never has a partial/malformed
354    /// tail that would break `get_entries()`. The append uses a single
355    /// `write_all` of the pre-built line (including `\n`) to minimize the
356    /// chance of a partial write.
357    ///
358    /// # Blocking
359    /// Performs synchronous file open/write. Must not be called on a Tokio
360    /// worker thread.
361    fn append_entry_blocking(log_path: &Path, json: &str) -> Result<()> {
362        let mut file = OpenOptions::new()
363            .create(true)
364            .append(true)
365            .open(log_path)
366            .with_context(|| format!("Failed to open audit log: {log_path:?}"))?;
367
368        // Record the pre-append length so we can roll back on write failure.
369        let pre_len = file.metadata().with_context(|| "Failed to read audit log metadata")?.len();
370
371        // Build the full line in memory so the append is a single write_all,
372        // minimizing the chance of a partial line on failure.
373        let mut line = json.to_string();
374        line.push('\n');
375
376        if let Err(e) = file.write_all(line.as_bytes()) {
377            // Truncate any partial bytes back to the pre-append length so
378            // the file never has a malformed tail.
379            let _ = file.set_len(pre_len);
380            return Err(e).with_context(|| "Failed to write audit entry");
381        }
382
383        Ok(())
384    }
385
386    /// Get all entries from the log.
387    ///
388    /// Uses `lock_owned()` so the `write_lock` guard is moved into the
389    /// `spawn_blocking` closure — reads stay consistent with in-flight writes
390    /// even if the calling task is cancelled.
391    pub async fn get_entries(&self) -> Result<Vec<AuditEntry>> {
392        let guard = self.write_lock.clone().lock_owned().await;
393
394        // File open + read_line loop are blocking; run them off the async
395        // executor. The owned `write_lock` guard is moved into the closure so
396        // reads stay serialized even if the caller is cancelled. See `# Blocking`
397        // docs in `src/agent/runloop/git.rs`.
398        let log_path = self.log_path.clone();
399        tokio::task::spawn_blocking(move || -> Result<Vec<AuditEntry>> {
400            let _guard = guard; // held until closure returns
401
402            if !log_path.exists() {
403                return Ok(Vec::new());
404            }
405
406            let file = File::open(&log_path).with_context(|| "Failed to open audit log")?;
407            let mut reader = BufReader::new(file);
408            let mut entries = Vec::new();
409            let mut line = String::new();
410
411            loop {
412                line.clear();
413                if reader.read_line(&mut line).with_context(|| "Failed to read audit log line")? == 0 {
414                    break;
415                }
416                let raw = line.trim_end_matches(['\n', '\r']);
417                if raw.trim().is_empty() {
418                    continue;
419                }
420                let entry: AuditEntry = serde_json::from_str(raw).with_context(|| "Failed to parse audit entry")?;
421                entries.push(entry);
422            }
423
424            Ok(entries)
425        })
426        .await
427        .context("audit log read task panicked")?
428    }
429
430    /// Verify the integrity of the entire audit log.
431    pub async fn verify_integrity(&self) -> Result<bool> {
432        let entries = self.get_entries().await?;
433
434        if entries.is_empty() {
435            return Ok(true);
436        }
437
438        let mut expected_prev_hash = "0000000000000000000000000000000000000000000000000000000000000000".to_string();
439
440        for entry in entries {
441            // Verify entry hash
442            if !entry.verify() {
443                tracing::warn!("Audit log integrity violation: entry {} has invalid hash", entry.id);
444                return Ok(false);
445            }
446
447            // Verify chain
448            if entry.previous_hash != expected_prev_hash {
449                tracing::warn!("Audit log integrity violation: entry {} has broken chain", entry.id);
450                return Ok(false);
451            }
452
453            expected_prev_hash = entry.entry_hash.unwrap_or_default();
454        }
455
456        Ok(true)
457    }
458
459    /// Get entries for a specific file.
460    pub async fn get_entries_for_file(&self, file_path: &str) -> Result<Vec<AuditEntry>> {
461        let entries = self.get_entries().await?;
462        Ok(entries.into_iter().filter(|e| e.file_path == file_path).collect())
463    }
464
465    /// Get recent entries (last N).
466    pub async fn get_recent_entries(&self, count: usize) -> Result<Vec<AuditEntry>> {
467        let entries = self.get_entries().await?;
468        let len = entries.len();
469        if len <= count {
470            Ok(entries)
471        } else {
472            Ok(entries.into_iter().skip(len - count).collect())
473        }
474    }
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480    use tempfile::tempdir;
481
482    #[tokio::test]
483    async fn test_audit_log_creation() {
484        let dir = tempdir().unwrap();
485        let log_path = dir.path().join("audit.log");
486
487        let log = AuditLog::new(&log_path).await.unwrap();
488
489        let entry =
490            AuditEntry::new(".gitignore", AccessType::Write, AuditOutcome::Blocked, "write_file", "test-session", "");
491
492        log.log(entry).await.unwrap();
493
494        let entries = log.get_entries().await.unwrap();
495        assert_eq!(entries.len(), 1);
496        assert_eq!(entries[0].file_path, ".gitignore");
497    }
498
499    #[tokio::test]
500    async fn test_audit_log_integrity() {
501        let dir = tempdir().unwrap();
502        let log_path = dir.path().join("audit.log");
503
504        let log = AuditLog::new(&log_path).await.unwrap();
505
506        // Add multiple entries
507        for i in 0..5 {
508            let entry = AuditEntry::new(
509                format!(".env.{i}"),
510                AccessType::Modify,
511                AuditOutcome::Blocked,
512                "test_tool",
513                "test-session",
514                "",
515            );
516            log.log(entry).await.unwrap();
517        }
518
519        // Verify integrity
520        assert!(log.verify_integrity().await.unwrap());
521
522        // Entries should be chainable
523        let entries = log.get_entries().await.unwrap();
524        assert_eq!(entries.len(), 5);
525
526        for entry in &entries {
527            assert!(entry.verify());
528        }
529    }
530
531    #[test]
532    fn test_entry_hash() {
533        let entry =
534            AuditEntry::new(".bashrc", AccessType::Write, AuditOutcome::UserRejected, "shell", "sess-123", "prev-hash")
535                .finalize();
536
537        assert!(entry.verify());
538    }
539
540    /// After a failed write (file is read-only), `last_hash` must remain at
541    /// the old value so the next successful entry chains correctly. This
542    /// verifies the fix for the chain-corruption bug where `last_hash` was
543    /// updated before the durable write.
544    #[cfg(unix)]
545    #[tokio::test]
546    async fn test_failed_write_preserves_chain() {
547        use std::os::unix::fs::PermissionsExt;
548
549        let dir = tempdir().unwrap();
550        let log_path = dir.path().join("audit.log");
551
552        let log = AuditLog::new(&log_path).await.unwrap();
553
554        // Write one entry successfully.
555        let entry1 =
556            AuditEntry::new(".gitignore", AccessType::Write, AuditOutcome::Blocked, "write_file", "test-session", "");
557        log.log(entry1).await.unwrap();
558
559        let entries = log.get_entries().await.unwrap();
560        assert_eq!(entries.len(), 1);
561        let good_hash = entries[0].entry_hash.clone().unwrap();
562
563        // Make the log file read-only so append-mode open fails.
564        std::fs::set_permissions(&log_path, std::fs::Permissions::from_mode(0o444)).unwrap();
565
566        // Attempt a write — it must fail.
567        let entry2 =
568            AuditEntry::new(".env", AccessType::Modify, AuditOutcome::Blocked, "write_file", "test-session", "");
569        let result = log.log(entry2).await;
570        assert!(result.is_err(), "write to a read-only log should fail");
571
572        // Restore write permission.
573        std::fs::set_permissions(&log_path, std::fs::Permissions::from_mode(0o644)).unwrap();
574
575        // The next successful entry must chain against the first entry's hash,
576        // not the failed entry's hash.
577        let entry3 =
578            AuditEntry::new(".bashrc", AccessType::Read, AuditOutcome::AllowedWithConfirmation, "read_file", "s2", "");
579        log.log(entry3).await.unwrap();
580
581        let entries = log.get_entries().await.unwrap();
582        assert_eq!(entries.len(), 2);
583        assert_eq!(entries[1].previous_hash, good_hash, "chain must link to the last successful entry");
584        assert!(log.verify_integrity().await.unwrap(), "integrity must be intact");
585    }
586
587    /// Concurrent log calls must be serialized — entries must form a valid
588    /// chain with no duplicate or broken `previous_hash` links.
589    #[tokio::test]
590    async fn test_concurrent_writes_form_valid_chain() {
591        let dir = tempdir().unwrap();
592        let log_path = dir.path().join("audit.log");
593        let log = Arc::new(AuditLog::new(&log_path).await.unwrap());
594
595        let mut handles = Vec::new();
596        for i in 0..8 {
597            let log = log.clone();
598            handles.push(tokio::spawn(async move {
599                let entry = AuditEntry::new(
600                    format!(".env.{i}"),
601                    AccessType::Modify,
602                    AuditOutcome::Blocked,
603                    "test_tool",
604                    "test-session",
605                    "",
606                );
607                log.log(entry).await
608            }));
609        }
610        for handle in handles {
611            handle.await.unwrap().unwrap();
612        }
613
614        let entries = log.get_entries().await.unwrap();
615        assert_eq!(entries.len(), 8);
616        assert!(log.verify_integrity().await.unwrap(), "all 8 concurrent entries must form a valid chain");
617    }
618
619    /// `append_entry_blocking` must write a valid single JSON line followed
620    /// by `\n`. This verifies the pre-built-line + `write_all` approach.
621    #[test]
622    fn test_append_entry_blocking_writes_valid_line() {
623        let dir = tempdir().unwrap();
624        let log_path = dir.path().join("audit.log");
625
626        let entry = AuditEntry::new(".env", AccessType::Write, AuditOutcome::Blocked, "test", "s1", "").finalize();
627        let json = serde_json::to_string(&entry).unwrap();
628
629        AuditLog::append_entry_blocking(&log_path, &json).unwrap();
630
631        let content = std::fs::read_to_string(&log_path).unwrap();
632        assert!(content.ends_with('\n'), "line must be newline-terminated");
633        let line = content.trim_end();
634        let parsed: AuditEntry = serde_json::from_str(line).expect("written line must be valid JSON");
635        assert_eq!(parsed.file_path, ".env");
636    }
637
638    /// `append_entry_blocking` must append to an existing file without
639    /// corrupting prior entries.
640    #[test]
641    fn test_append_entry_blocking_appends_correctly() {
642        let dir = tempdir().unwrap();
643        let log_path = dir.path().join("audit.log");
644
645        for i in 0..3 {
646            let entry =
647                AuditEntry::new(format!(".env.{i}"), AccessType::Modify, AuditOutcome::Blocked, "test", "s1", "")
648                    .finalize();
649            let json = serde_json::to_string(&entry).unwrap();
650            AuditLog::append_entry_blocking(&log_path, &json).unwrap();
651        }
652
653        let content = std::fs::read_to_string(&log_path).unwrap();
654        let lines: Vec<&str> = content.lines().filter(|l| !l.trim().is_empty()).collect();
655        assert_eq!(lines.len(), 3, "must have exactly 3 lines");
656        for (i, line) in lines.iter().enumerate() {
657            let entry: AuditEntry = serde_json::from_str(line).unwrap();
658            assert_eq!(entry.file_path, format!(".env.{i}"));
659        }
660    }
661
662    /// `append_entry_blocking` must not leave a malformed tail when writing
663    /// to a directory that doesn't exist (open fails). The file simply won't
664    /// be created — no partial state.
665    #[test]
666    fn test_append_entry_blocking_missing_dir_is_clean_failure() {
667        let dir = tempdir().unwrap();
668        let nonexistent = dir.path().join("nonexistent_dir").join("audit.log");
669
670        let entry = AuditEntry::new(".env", AccessType::Write, AuditOutcome::Blocked, "test", "s1", "").finalize();
671        let json = serde_json::to_string(&entry).unwrap();
672
673        let result = AuditLog::append_entry_blocking(&nonexistent, &json);
674        assert!(result.is_err(), "writing to a missing directory must fail");
675        assert!(!nonexistent.exists(), "no file should be created on failure");
676    }
677}