1use chrono::Utc;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::io::{BufRead, Write};
5use std::path::PathBuf;
6
7use crate::core::dirs;
8use crate::core::scope::matches_wildcard;
9
10const MAX_ARG_VALUE_LEN: usize = 200;
11
12#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
13#[serde(rename_all = "lowercase")]
14pub enum AuditStatus {
15 Ok,
16 Error,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct AuditEntry {
21 pub ts: String,
22 pub tool: String,
23 pub args: Value,
24 pub status: AuditStatus,
25 pub duration_ms: u64,
26 pub agent_sub: String,
27 #[serde(skip_serializing_if = "Option::is_none")]
28 pub error: Option<String>,
29 #[serde(skip_serializing_if = "Option::is_none")]
30 pub exit_code: Option<i32>,
31}
32
33pub fn audit_file_path() -> PathBuf {
35 if let Ok(p) = std::env::var("ATI_AUDIT_FILE") {
36 PathBuf::from(p)
37 } else {
38 dirs::ati_dir().join("audit.jsonl")
39 }
40}
41
42pub fn append(entry: &AuditEntry) -> Result<(), std::io::Error> {
44 let path = audit_file_path();
45 if let Some(parent) = path.parent() {
46 std::fs::create_dir_all(parent)?;
47 }
48 let mut file = std::fs::OpenOptions::new()
49 .create(true)
50 .append(true)
51 .open(&path)?;
52 let line = serde_json::to_string(entry).map_err(std::io::Error::other)?;
53 writeln!(file, "{}", line)?;
54 Ok(())
55}
56
57pub fn tail(n: usize) -> Result<Vec<AuditEntry>, Box<dyn std::error::Error>> {
59 let path = audit_file_path();
60 if !path.exists() {
61 return Ok(Vec::new());
62 }
63 let file = std::fs::File::open(&path)?;
64 let reader = std::io::BufReader::new(file);
65 let entries: Vec<AuditEntry> = reader
66 .lines()
67 .map_while(|l| l.ok())
68 .filter(|l| !l.trim().is_empty())
69 .filter_map(|l| serde_json::from_str(&l).ok())
70 .collect();
71 let start = entries.len().saturating_sub(n);
72 Ok(entries[start..].to_vec())
73}
74
75pub fn search(
77 tool_pattern: Option<&str>,
78 since: Option<&str>,
79) -> Result<Vec<AuditEntry>, Box<dyn std::error::Error>> {
80 let path = audit_file_path();
81 if !path.exists() {
82 return Ok(Vec::new());
83 }
84
85 let since_ts = since.map(parse_duration_ago).transpose()?;
86
87 let file = std::fs::File::open(&path)?;
88 let reader = std::io::BufReader::new(file);
89 let entries: Vec<AuditEntry> = reader
90 .lines()
91 .map_while(|l| l.ok())
92 .filter(|l| !l.trim().is_empty())
93 .filter_map(|l| serde_json::from_str(&l).ok())
94 .filter(|e: &AuditEntry| {
95 if let Some(pattern) = tool_pattern {
96 if !matches_wildcard(&e.tool, pattern) {
97 return false;
98 }
99 }
100 if let Some(ref cutoff) = since_ts {
101 if e.ts.as_str() < cutoff.as_str() {
102 return false;
103 }
104 }
105 true
106 })
107 .collect();
108
109 Ok(entries)
110}
111
112pub fn sanitize_args(args: &Value) -> Value {
114 match args {
115 Value::Object(map) => {
116 let mut sanitized = serde_json::Map::new();
117 for (key, value) in map {
118 let key_lower = key.to_lowercase();
119 if key_lower.contains("password")
120 || key_lower.contains("secret")
121 || key_lower.contains("token")
122 || key_lower.contains("key")
123 || key_lower.contains("credential")
124 || key_lower.contains("auth")
125 {
126 sanitized.insert(key.clone(), Value::String("[REDACTED]".to_string()));
127 } else {
128 sanitized.insert(key.clone(), truncate_value(value));
129 }
130 }
131 Value::Object(sanitized)
132 }
133 other => truncate_value(other),
134 }
135}
136
137fn truncate_value(value: &Value) -> Value {
138 match value {
139 Value::String(s) if s.len() > MAX_ARG_VALUE_LEN => {
140 Value::String(format!("{}...[truncated]", &s[..MAX_ARG_VALUE_LEN]))
141 }
142 other => other.clone(),
143 }
144}
145
146fn parse_duration_ago(s: &str) -> Result<String, Box<dyn std::error::Error>> {
149 let s = s.trim();
150 if s.is_empty() {
151 return Err("Empty duration string".into());
152 }
153
154 let split_pos = s
156 .find(|c: char| !c.is_ascii_digit())
157 .ok_or_else(|| format!("Invalid duration: '{s}'. Use format like 1h, 30m, 7d"))?;
158 let (num_str, unit) = s.split_at(split_pos);
159
160 let count: i64 = num_str
161 .parse()
162 .map_err(|_| format!("Invalid number in duration: '{s}'"))?;
163
164 let secs_per_unit = dirs::unit_to_secs(unit)
165 .ok_or_else(|| format!("Invalid duration unit: '{unit}'. Use s, m, h, or d"))?;
166
167 let seconds = count * secs_per_unit as i64;
168 let cutoff = Utc::now() - chrono::Duration::seconds(seconds);
169 Ok(cutoff.to_rfc3339())
170}