1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Audit logger — logs every tool call verdict.
//!
//! Dual-writes to an in-memory ring buffer (fast operational queries) and a
//! libro audit chain (tamper-proof cryptographic hash chain).

use crate::gate::{ToolCall, Verdict, VerdictKind};
use libro::{AuditChain, EventSeverity};
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::sync::Mutex;
use tokio::sync::RwLock;

/// Maximum audit events kept in the operational ring buffer.
const MAX_EVENTS: usize = 10_000;

/// A logged security event (operational view).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityEvent {
    pub id: uuid::Uuid,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub agent_id: String,
    pub tool_name: String,
    pub verdict: VerdictKind,
    pub reason: Option<String>,
}

pub struct AuditLogger {
    /// Fast ring buffer for operational queries (risk scoring, recent events).
    events: RwLock<VecDeque<SecurityEvent>>,
    /// Cryptographic hash chain for tamper-proof audit trail.
    chain: Mutex<AuditChain>,
}

impl Default for AuditLogger {
    fn default() -> Self {
        Self::new()
    }
}

impl AuditLogger {
    #[must_use]
    pub fn new() -> Self {
        Self {
            events: RwLock::new(VecDeque::new()),
            chain: Mutex::new(AuditChain::new()),
        }
    }

    /// Log a tool call verdict to both the ring buffer and the libro chain.
    pub async fn log(&self, call: &ToolCall, verdict: &Verdict) {
        let reason = match verdict {
            Verdict::Allow => None,
            Verdict::Deny { reason, .. } => Some(reason.clone()),
            Verdict::Flag { reason } => Some(reason.clone()),
        };

        let event = SecurityEvent {
            id: uuid::Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            agent_id: call.agent_id.clone(),
            tool_name: call.tool_name.clone(),
            verdict: verdict.kind(),
            reason: reason.clone(),
        };

        // Write to libro chain (sync lock, fast — no await points)
        {
            let severity = match verdict.kind() {
                VerdictKind::Allow => EventSeverity::Info,
                VerdictKind::Flag => EventSeverity::Warning,
                VerdictKind::Deny => EventSeverity::Security,
            };
            let action = match verdict.kind() {
                VerdictKind::Allow => "tool_call.allow",
                VerdictKind::Flag => "tool_call.flag",
                VerdictKind::Deny => "tool_call.deny",
            };
            let mut details = serde_json::json!({
                "tool_name": call.tool_name,
            });
            if let Some(ref r) = reason {
                details["reason"] = serde_json::Value::String(r.clone());
            }
            if let Verdict::Deny { code, .. } = verdict {
                details["deny_code"] = serde_json::Value::String(code.as_str().to_owned());
            }
            let mut chain = self
                .chain
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            chain.append_with_agent(severity, "t-ron", action, details, &call.agent_id);
        }

        // Write to operational ring buffer
        let mut events = self.events.write().await;
        events.push_back(event);
        if events.len() > MAX_EVENTS {
            events.pop_front();
        }
    }

    /// Get recent events.
    pub async fn recent(&self, limit: usize) -> Vec<SecurityEvent> {
        let events = self.events.read().await;
        events.iter().rev().take(limit).cloned().collect()
    }

    /// Get events for a specific agent.
    pub async fn agent_events(&self, agent_id: &str, limit: usize) -> Vec<SecurityEvent> {
        let events = self.events.read().await;
        events
            .iter()
            .rev()
            .filter(|e| e.agent_id == agent_id)
            .take(limit)
            .cloned()
            .collect()
    }

    /// Count denied calls.
    pub async fn deny_count(&self) -> usize {
        self.events
            .read()
            .await
            .iter()
            .filter(|e| e.verdict == VerdictKind::Deny)
            .count()
    }

    /// Total event count.
    pub async fn total_count(&self) -> usize {
        self.events.read().await.len()
    }

    /// Verify the libro audit chain integrity.
    pub fn verify_chain(&self) -> libro::Result<()> {
        let chain = self
            .chain
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        chain.verify()
    }

    /// Get a structured review/summary of the audit chain.
    #[must_use]
    pub fn chain_review(&self) -> libro::ChainReview {
        let chain = self
            .chain
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        chain.review()
    }

    /// Number of entries in the libro chain (may differ from ring buffer
    /// if ring buffer has evicted old entries).
    #[must_use]
    pub fn chain_len(&self) -> usize {
        self.chain
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .len()
    }

    /// Export the libro chain entries as JSON bytes.
    pub fn export_json(&self) -> Result<Vec<u8>, crate::TRonError> {
        let chain = self
            .chain
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        serde_json::to_vec(chain.entries())
            .map_err(|e| crate::TRonError::Export(format!("JSON serialization failed: {e}")))
    }

    /// Export the libro chain as encrypted JSON using ChaCha20-Poly1305 AEAD.
    ///
    /// The key must be exactly 32 bytes. Returns `nonce (12 bytes) || ciphertext`.
    #[cfg(feature = "export")]
    pub fn export_encrypted(&self, key: &[u8; 32]) -> Result<Vec<u8>, crate::TRonError> {
        use chacha20poly1305::{
            ChaCha20Poly1305, KeyInit,
            aead::{Aead, AeadCore, OsRng},
        };

        let json = self.export_json()?;
        let cipher = ChaCha20Poly1305::new(key.into());
        let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
        let ciphertext = cipher
            .encrypt(&nonce, json.as_ref())
            .map_err(|e| crate::TRonError::Export(format!("encryption failed: {e}")))?;

        let mut output = Vec::with_capacity(12 + ciphertext.len());
        output.extend_from_slice(&nonce);
        output.extend_from_slice(&ciphertext);

        tracing::info!(
            entries = self.chain_len(),
            encrypted_bytes = output.len(),
            "audit chain exported (encrypted)"
        );
        Ok(output)
    }

    /// Decrypt an encrypted audit export. Returns the raw JSON bytes.
    #[cfg(feature = "export")]
    pub fn decrypt_export(key: &[u8; 32], data: &[u8]) -> Result<Vec<u8>, crate::TRonError> {
        use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce, aead::Aead};

        if data.len() < 12 {
            return Err(crate::TRonError::Export(
                "encrypted data too short (need at least 12 bytes for nonce)".into(),
            ));
        }
        let (nonce_bytes, ciphertext) = data.split_at(12);
        let nonce = Nonce::from_slice(nonce_bytes);
        let cipher = ChaCha20Poly1305::new(key.into());
        cipher
            .decrypt(nonce, ciphertext)
            .map_err(|e| crate::TRonError::Export(format!("decryption failed: {e}")))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gate::DenyCode;

    #[tokio::test]
    async fn log_and_retrieve() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };

        logger.log(&call, &Verdict::Allow).await;
        logger
            .log(
                &call,
                &Verdict::Deny {
                    reason: "nope".into(),
                    code: crate::gate::DenyCode::Unauthorized,
                },
            )
            .await;

        assert_eq!(logger.total_count().await, 2);
        assert_eq!(logger.deny_count().await, 1);

        let recent = logger.recent(10).await;
        assert_eq!(recent.len(), 2);
        assert_eq!(recent[0].verdict, VerdictKind::Deny); // Most recent first
    }

    #[tokio::test]
    async fn log_flag_verdict() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "test_tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        logger
            .log(
                &call,
                &Verdict::Flag {
                    reason: "suspicious".into(),
                },
            )
            .await;

        let events = logger.recent(1).await;
        assert_eq!(events[0].verdict, VerdictKind::Flag);
        assert_eq!(events[0].reason.as_deref(), Some("suspicious"));
        // Flags are not denials
        assert_eq!(logger.deny_count().await, 0);
    }

    #[tokio::test]
    async fn agent_events_filtering() {
        let logger = AuditLogger::new();
        let call_a = ToolCall {
            agent_id: "agent-a".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        let call_b = ToolCall {
            agent_id: "agent-b".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };

        for _ in 0..5 {
            logger.log(&call_a, &Verdict::Allow).await;
        }
        for _ in 0..3 {
            logger.log(&call_b, &Verdict::Allow).await;
        }

        assert_eq!(logger.agent_events("agent-a", 100).await.len(), 5);
        assert_eq!(logger.agent_events("agent-b", 100).await.len(), 3);
        assert_eq!(logger.agent_events("nobody", 100).await.len(), 0);
    }

    #[tokio::test]
    async fn agent_events_respects_limit() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        for _ in 0..10 {
            logger.log(&call, &Verdict::Allow).await;
        }
        assert_eq!(logger.agent_events("agent-1", 3).await.len(), 3);
    }

    #[tokio::test]
    async fn recent_limit_larger_than_count() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        logger.log(&call, &Verdict::Allow).await;
        // Ask for 100 but only 1 exists
        assert_eq!(logger.recent(100).await.len(), 1);
    }

    #[tokio::test]
    async fn empty_log_queries() {
        let logger = AuditLogger::new();
        assert_eq!(logger.total_count().await, 0);
        assert_eq!(logger.deny_count().await, 0);
        assert!(logger.recent(10).await.is_empty());
        assert!(logger.agent_events("nobody", 10).await.is_empty());
    }

    #[tokio::test]
    async fn max_events_eviction() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };

        // Log MAX_EVENTS + 100 events
        for _ in 0..(MAX_EVENTS + 100) {
            logger.log(&call, &Verdict::Allow).await;
        }
        assert_eq!(logger.total_count().await, MAX_EVENTS);
    }

    #[tokio::test]
    async fn event_has_unique_id() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        logger.log(&call, &Verdict::Allow).await;
        logger.log(&call, &Verdict::Allow).await;

        let events = logger.recent(2).await;
        assert_ne!(events[0].id, events[1].id);
    }

    #[tokio::test]
    async fn chain_written_on_log() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "tarang_probe".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        logger.log(&call, &Verdict::Allow).await;
        logger
            .log(
                &call,
                &Verdict::Deny {
                    reason: "blocked".into(),
                    code: DenyCode::Unauthorized,
                },
            )
            .await;

        assert_eq!(logger.chain_len(), 2);
        assert!(logger.verify_chain().is_ok());
    }

    #[tokio::test]
    async fn chain_integrity_after_many_writes() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        for _ in 0..100 {
            logger.log(&call, &Verdict::Allow).await;
        }
        assert_eq!(logger.chain_len(), 100);
        assert!(logger.verify_chain().is_ok());
    }

    #[tokio::test]
    async fn chain_has_agent_id() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "web-agent".to_string(),
            tool_name: "tarang_probe".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        logger.log(&call, &Verdict::Allow).await;

        let chain = logger.chain.lock().unwrap();
        let entry = &chain.entries()[0];
        assert_eq!(entry.agent_id(), Some("web-agent"));
        assert_eq!(entry.source(), "t-ron");
        assert_eq!(entry.action(), "tool_call.allow");
    }

    #[tokio::test]
    async fn chain_deny_has_details() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "bad-agent".to_string(),
            tool_name: "aegis_scan".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        logger
            .log(
                &call,
                &Verdict::Deny {
                    reason: "rate limit exceeded".into(),
                    code: DenyCode::RateLimited,
                },
            )
            .await;

        let chain = logger.chain.lock().unwrap();
        let entry = &chain.entries()[0];
        assert_eq!(entry.action(), "tool_call.deny");
        assert_eq!(entry.severity(), EventSeverity::Security);
        let details = entry.details();
        assert_eq!(details["tool_name"], "aegis_scan");
        assert_eq!(details["reason"], "rate limit exceeded");
        assert_eq!(details["deny_code"], "rate_limited");
    }

    #[tokio::test]
    async fn chain_review_works() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        logger.log(&call, &Verdict::Allow).await;

        let review = logger.chain_review();
        assert_eq!(review.entry_count, 1);
    }

    #[tokio::test]
    async fn export_json_empty_chain() {
        let logger = AuditLogger::new();
        let json = logger.export_json().unwrap();
        let parsed: Vec<serde_json::Value> = serde_json::from_slice(&json).unwrap();
        assert!(parsed.is_empty());
    }

    #[tokio::test]
    async fn export_json_with_entries() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        for _ in 0..5 {
            logger.log(&call, &Verdict::Allow).await;
        }
        let json = logger.export_json().unwrap();
        let parsed: Vec<serde_json::Value> = serde_json::from_slice(&json).unwrap();
        assert_eq!(parsed.len(), 5);
    }

    #[cfg(feature = "export")]
    #[tokio::test]
    async fn export_encrypted_roundtrip() {
        let logger = AuditLogger::new();
        let call = ToolCall {
            agent_id: "agent-1".to_string(),
            tool_name: "tool".to_string(),
            params: serde_json::json!({}),
            timestamp: chrono::Utc::now(),
        };
        logger.log(&call, &Verdict::Allow).await;
        logger
            .log(
                &call,
                &Verdict::Deny {
                    reason: "test".into(),
                    code: DenyCode::Unauthorized,
                },
            )
            .await;

        let key = [42u8; 32];
        let encrypted = logger.export_encrypted(&key).unwrap();
        assert!(encrypted.len() > 12); // nonce + ciphertext

        let decrypted = AuditLogger::decrypt_export(&key, &encrypted).unwrap();
        let original_json = logger.export_json().unwrap();
        assert_eq!(decrypted, original_json);
    }

    #[cfg(feature = "export")]
    #[test]
    fn decrypt_wrong_key_fails() {
        // Manually construct some data that was "encrypted" with key A
        // then try to decrypt with key B
        let logger = AuditLogger::new();
        let key_a = [1u8; 32];
        let key_b = [2u8; 32];

        let encrypted = logger.export_encrypted(&key_a).unwrap();
        assert!(AuditLogger::decrypt_export(&key_b, &encrypted).is_err());
    }

    #[cfg(feature = "export")]
    #[test]
    fn decrypt_truncated_data_fails() {
        let key = [0u8; 32];
        // Less than 12 bytes (nonce size)
        assert!(AuditLogger::decrypt_export(&key, &[0u8; 5]).is_err());
    }
}