1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum AuditOutcome {
23 AllowedWithConfirmation,
25 AllowedViaWhitelist,
27 Blocked,
29 Denied,
31 UserRejected,
33 AllowedUnprotected,
35 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum AccessType {
57 Read,
59 Write,
61 Create,
63 Delete,
65 Modify,
67 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#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct AuditEntry {
87 pub id: String,
89 pub timestamp: DateTime<Utc>,
91 pub file_path: String,
93 pub access_type: AccessType,
95 pub outcome: AuditOutcome,
97 pub initiator: String,
99 pub session_id: String,
101 pub proposed_changes: Option<String>,
103 pub previous_hash: String,
105 #[serde(skip_serializing_if = "Option::is_none")]
107 pub entry_hash: Option<String>,
108 pub context: Option<String>,
110 pub during_automation: bool,
112}
113
114impl AuditEntry {
115 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 pub fn with_proposed_changes(mut self, changes: impl Into<String>) -> Self {
142 self.proposed_changes = Some(changes.into());
143 self
144 }
145
146 pub fn with_context(mut self, context: impl Into<String>) -> Self {
148 self.context = Some(context.into());
149 self
150 }
151
152 pub fn during_automation(mut self) -> Self {
154 self.during_automation = true;
155 self
156 }
157
158 pub fn finalize(mut self) -> Self {
160 self.entry_hash = Some(self.compute_hash());
161 self
162 }
163
164 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 pub fn verify(&self) -> bool {
187 self.entry_hash.as_ref().is_some_and(|hash| *hash == self.compute_hash())
188 }
189}
190
191pub struct AuditLog {
200 log_path: PathBuf,
202 write_lock: Arc<Mutex<()>>,
206 last_hash: Arc<Mutex<String>>,
214}
215
216impl AuditLog {
217 pub async fn new(log_path: impl AsRef<Path>) -> Result<Self> {
219 let log_path = log_path.as_ref().to_path_buf();
220
221 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 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 "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 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 let window: u64 = (1 << 18).min(len); 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 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 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 let log_path = self.log_path.clone();
317 tokio::task::spawn_blocking(move || -> Result<()> {
318 let _write_guard = write_guard; Self::append_entry_blocking(&log_path, &json)?;
321
322 if let Some(hash) = new_hash {
327 *hash_guard = hash;
328 }
329
330 let sync_result = File::open(&log_path).and_then(|f| f.sync_all());
335
336 if let Err(e) = sync_result {
337 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 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 let pre_len = file.metadata().with_context(|| "Failed to read audit log metadata")?.len();
370
371 let mut line = json.to_string();
374 line.push('\n');
375
376 if let Err(e) = file.write_all(line.as_bytes()) {
377 let _ = file.set_len(pre_len);
380 return Err(e).with_context(|| "Failed to write audit entry");
381 }
382
383 Ok(())
384 }
385
386 pub async fn get_entries(&self) -> Result<Vec<AuditEntry>> {
392 let guard = self.write_lock.clone().lock_owned().await;
393
394 let log_path = self.log_path.clone();
399 tokio::task::spawn_blocking(move || -> Result<Vec<AuditEntry>> {
400 let _guard = guard; 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 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 if !entry.verify() {
443 tracing::warn!("Audit log integrity violation: entry {} has invalid hash", entry.id);
444 return Ok(false);
445 }
446
447 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 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 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 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 assert!(log.verify_integrity().await.unwrap());
521
522 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 #[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 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 std::fs::set_permissions(&log_path, std::fs::Permissions::from_mode(0o444)).unwrap();
565
566 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 std::fs::set_permissions(&log_path, std::fs::Permissions::from_mode(0o644)).unwrap();
574
575 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 #[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 #[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 #[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 #[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}