Skip to main content

lean_ctx/core/
audit_trail.rs

1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256};
3use std::fs::{self, OpenOptions};
4use std::io::{BufRead, Write};
5use std::path::{Path, PathBuf};
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct AuditEntry {
9    pub timestamp: String,
10    pub agent_id: String,
11    pub tool: String,
12    pub action: Option<String>,
13    pub input_hash: String,
14    pub output_tokens: u32,
15    pub role: String,
16    pub event_type: AuditEventType,
17    pub prev_hash: String,
18    pub entry_hash: String,
19    /// Ed25519 signature over `entry_hash`, proving provenance from the local
20    /// lean-ctx identity. `None` only when the keypair is unavailable (early boot).
21    #[serde(skip_serializing_if = "Option::is_none", default)]
22    pub signature: Option<String>,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26#[serde(rename_all = "snake_case")]
27pub enum AuditEventType {
28    ToolCall,
29    ToolDenied,
30    PathJailViolation,
31    BudgetExceeded,
32    CrossProjectAccess,
33    RateLimited,
34    SecurityViolation,
35    RoleChanged,
36    SecretDetected,
37    // Agent identity lifecycle (GL #433) — additive OCP Part 4 evolution.
38    AgentRegistered,
39    AgentSuspended,
40    AgentResumed,
41    AgentDecommissioned,
42}
43
44pub struct AuditEntryData {
45    pub agent_id: String,
46    pub tool: String,
47    pub action: Option<String>,
48    pub input_hash: String,
49    pub output_tokens: u32,
50    pub role: String,
51    pub event_type: AuditEventType,
52}
53
54pub struct ChainVerifyResult {
55    pub total_entries: usize,
56    pub valid: bool,
57    pub first_invalid_at: Option<usize>,
58}
59
60fn trail_path() -> Option<PathBuf> {
61    let dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
62    let audit_dir = dir.join("audit");
63    fs::create_dir_all(&audit_dir).ok()?;
64    Some(audit_dir.join("trail.jsonl"))
65}
66
67/// Read the chain tail from the file itself. Called under the exclusive
68/// file lock — the file is the ONLY source of truth for `prev_hash`. (A
69/// per-process cache forked the chain whenever two processes appended
70/// concurrently — found by `leanctx-verify` on a real trail, GL #425.)
71fn read_last_hash_tail(file: &fs::File) -> String {
72    use std::io::{Read, Seek, SeekFrom};
73    const TAIL: i64 = 64 * 1024;
74
75    let mut f = file;
76    let Ok(len) = f.seek(SeekFrom::End(0)) else {
77        return "genesis".to_string();
78    };
79    if len == 0 {
80        return "genesis".to_string();
81    }
82    let start = if (len as i64) > TAIL {
83        -TAIL
84    } else {
85        -(len as i64)
86    };
87    if f.seek(SeekFrom::End(start)).is_err() {
88        return "genesis".to_string();
89    }
90    let mut buf = String::new();
91    if f.read_to_string(&mut buf).is_err() {
92        return "genesis".to_string();
93    }
94    // Concurrent-append history may hold multiple objects per line; a
95    // stream parse of the last non-empty line yields the true tail entry.
96    for line in buf.lines().rev() {
97        if line.trim().is_empty() {
98            continue;
99        }
100        let mut last: Option<String> = None;
101        for v in serde_json::Deserializer::from_str(line)
102            .into_iter::<serde_json::Value>()
103            .flatten()
104        {
105            if let Some(h) = v.get("entry_hash").and_then(|h| h.as_str()) {
106                last = Some(h.to_string());
107            }
108        }
109        if let Some(h) = last {
110            return h;
111        }
112    }
113    "genesis".to_string()
114}
115
116fn compute_entry_hash(prev_hash: &str, data_json: &str) -> String {
117    let mut hasher = Sha256::new();
118    hasher.update(prev_hash.as_bytes());
119    hasher.update(data_json.as_bytes());
120    crate::core::agent_identity::hex_encode(&hasher.finalize())
121}
122
123pub fn record(data: AuditEntryData) {
124    let Some(path) = trail_path() else { return };
125    record_at(&path, data);
126}
127
128/// Appends `data` to the trail at `path` (chained and signed like [`record`]).
129pub fn record_at(path: &Path, data: AuditEntryData) {
130    use fs2::FileExt;
131
132    let Ok(mut file) = OpenOptions::new()
133        .create(true)
134        .append(true)
135        .read(true)
136        .open(path)
137    else {
138        return;
139    };
140    // Advisory lock serializes appends ACROSS processes; prev_hash is read
141    // from the file under the same lock, so the chain cannot fork.
142    if file.lock_exclusive().is_err() {
143        return;
144    }
145    let prev_hash = read_last_hash_tail(&file);
146
147    let partial = serde_json::json!({
148        "agent_id": data.agent_id,
149        "tool": data.tool,
150        "action": data.action,
151        "input_hash": data.input_hash,
152        "output_tokens": data.output_tokens,
153        "role": data.role,
154        "event_type": data.event_type,
155    });
156    let data_json = serde_json::to_string(&partial).unwrap_or_default();
157    let entry_hash = compute_entry_hash(&prev_hash, &data_json);
158
159    let signature = crate::core::agent_identity::sign_bytes("lean-ctx", entry_hash.as_bytes())
160        .map(|sig| crate::core::agent_identity::hex_encode(&sig))
161        .ok();
162
163    let entry = AuditEntry {
164        timestamp: chrono::Utc::now().to_rfc3339(),
165        agent_id: data.agent_id,
166        tool: data.tool,
167        action: data.action,
168        input_hash: data.input_hash,
169        output_tokens: data.output_tokens,
170        role: data.role,
171        event_type: data.event_type,
172        prev_hash,
173        entry_hash,
174        signature,
175    };
176
177    if let Ok(line) = serde_json::to_string(&entry) {
178        let _ = writeln!(file, "{line}");
179    }
180    let _ = FileExt::unlock(&file);
181}
182
183/// Path of the local audit trail (`<data_dir>/audit/trail.jsonl`).
184pub fn default_trail_path() -> Option<PathBuf> {
185    trail_path()
186}
187
188pub fn load_recent(limit: usize) -> Vec<AuditEntry> {
189    let Some(path) = trail_path() else {
190        return Vec::new();
191    };
192    let entries = load_all_at(&path);
193    let skip = entries.len().saturating_sub(limit);
194    entries.into_iter().skip(skip).collect()
195}
196
197/// Every parseable entry of the trail at `path`.
198pub fn load_all_at(path: &Path) -> Vec<AuditEntry> {
199    let Ok(file) = fs::File::open(path) else {
200        return Vec::new();
201    };
202    std::io::BufReader::new(file)
203        .lines()
204        .map_while(Result::ok)
205        .filter_map(|line| serde_json::from_str(&line).ok())
206        .collect()
207}
208
209pub fn verify_chain() -> ChainVerifyResult {
210    let Some(path) = trail_path() else {
211        return ChainVerifyResult {
212            total_entries: 0,
213            valid: true,
214            first_invalid_at: None,
215        };
216    };
217    verify_chain_at(&path)
218}
219
220/// Re-walks the trail at `path` from genesis, recomputing every hash.
221pub fn verify_chain_at(path: &Path) -> ChainVerifyResult {
222    let Ok(file) = fs::File::open(path) else {
223        return ChainVerifyResult {
224            total_entries: 0,
225            valid: true,
226            first_invalid_at: None,
227        };
228    };
229    let reader = std::io::BufReader::new(file);
230    let mut prev_hash = "genesis".to_string();
231    let mut total = 0usize;
232
233    for line in reader.lines().map_while(Result::ok) {
234        let entry: AuditEntry = match serde_json::from_str(&line) {
235            Ok(e) => e,
236            Err(_) => {
237                return ChainVerifyResult {
238                    total_entries: total,
239                    valid: false,
240                    first_invalid_at: Some(total),
241                };
242            }
243        };
244
245        if entry.prev_hash != prev_hash {
246            return ChainVerifyResult {
247                total_entries: total,
248                valid: false,
249                first_invalid_at: Some(total),
250            };
251        }
252
253        let partial = serde_json::json!({
254            "agent_id": entry.agent_id,
255            "tool": entry.tool,
256            "action": entry.action,
257            "input_hash": entry.input_hash,
258            "output_tokens": entry.output_tokens,
259            "role": entry.role,
260            "event_type": entry.event_type,
261        });
262        let data_json = serde_json::to_string(&partial).unwrap_or_default();
263        let expected = compute_entry_hash(&prev_hash, &data_json);
264
265        if entry.entry_hash != expected {
266            return ChainVerifyResult {
267                total_entries: total,
268                valid: false,
269                first_invalid_at: Some(total),
270            };
271        }
272
273        prev_hash = entry.entry_hash;
274        total += 1;
275    }
276
277    ChainVerifyResult {
278        total_entries: total,
279        valid: true,
280        first_invalid_at: None,
281    }
282}
283
284pub fn hash_input(args: &serde_json::Map<String, serde_json::Value>) -> String {
285    let serialized = serde_json::to_string(args).unwrap_or_default();
286    let mut hasher = Sha256::new();
287    hasher.update(serialized.as_bytes());
288    crate::core::agent_identity::hex_encode(&hasher.finalize())
289}