libro 0.92.0

Cryptographic audit chain — tamper-proof event logging with hash-linked entries and verification
Documentation
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! The audit chain — append-only, hash-linked sequence of entries.

use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};

use crate::LibroError;
use crate::entry::{AuditEntry, EventSeverity};
use crate::query::QueryFilter;
use crate::retention::RetentionPolicy;
use crate::verify::verify_chain;

/// An append-only audit chain with hash-linked entries.
///
/// Optionally enforces a maximum capacity. When set, appending beyond the
/// limit triggers automatic rotation — excess entries are drained into a
/// [`ChainArchive`] before the new entry is appended. Use
/// [`with_capacity`](AuditChain::with_capacity) to enable this.
#[derive(Debug, Default)]
pub struct AuditChain {
    pub(crate) entries: Vec<AuditEntry>,
    /// After rotation, holds the head hash of the previous chain for continuity.
    pub(crate) prev_chain_hash: Option<String>,
    /// Optional maximum number of entries before auto-rotation.
    max_capacity: Option<usize>,
    /// Accumulates archives produced by auto-rotation.
    overflow_archives: Vec<ChainArchive>,
}

/// Archived entries from a chain rotation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ChainArchive {
    /// The drained entries.
    pub entries: Vec<AuditEntry>,
    /// The head hash of the archived chain (used to link the next chain).
    pub head_hash: String,
}

impl AuditChain {
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a chain with a maximum entry capacity.
    ///
    /// When the chain reaches `max_entries`, the next append triggers an
    /// automatic rotation. Archived entries are accessible via
    /// [`take_overflow`](AuditChain::take_overflow).
    ///
    /// A capacity of `0` is treated as unlimited (no auto-rotation).
    pub fn with_capacity(max_entries: usize) -> Self {
        Self {
            max_capacity: if max_entries == 0 {
                None
            } else {
                Some(max_entries)
            },
            ..Self::default()
        }
    }

    /// Returns the configured maximum capacity, if any.
    #[inline]
    #[must_use]
    pub fn max_capacity(&self) -> Option<usize> {
        self.max_capacity
    }

    /// Drain and return all archives produced by auto-rotation.
    ///
    /// After calling this, the internal overflow buffer is empty until the
    /// next auto-rotation occurs.
    pub fn take_overflow(&mut self) -> Vec<ChainArchive> {
        std::mem::take(&mut self.overflow_archives)
    }

    /// Auto-rotate if at capacity. Called before each append.
    fn auto_rotate_if_full(&mut self) {
        if let Some(max) = self.max_capacity
            && self.entries.len() >= max
        {
            info!(
                max_capacity = max,
                entries = self.entries.len(),
                "auto-rotating chain at capacity"
            );
            let archive = self.rotate();
            self.overflow_archives.push(archive);
        }
    }

    /// Append an event to the chain. Automatically links to the previous entry's hash.
    ///
    /// If the chain has a configured [`max_capacity`](AuditChain::with_capacity)
    /// and is at the limit, the current entries are auto-rotated into an archive
    /// before appending. Retrieve archives with [`take_overflow`](AuditChain::take_overflow).
    pub fn append(
        &mut self,
        severity: EventSeverity,
        source: impl Into<String>,
        action: impl Into<String>,
        details: serde_json::Value,
    ) -> &AuditEntry {
        self.auto_rotate_if_full();
        let prev_hash = self
            .entries
            .last()
            .map(|e| e.hash().to_owned())
            .or_else(|| self.prev_chain_hash.clone())
            .unwrap_or_default();
        let entry = AuditEntry::new(severity, source, action, details, prev_hash);
        debug!(
            hash = entry.hash(),
            source = entry.source(),
            action = entry.action(),
            severity = entry.severity().as_str(),
            index = self.entries.len(),
            "chain entry appended"
        );
        self.entries.push(entry);
        self.entries.last().unwrap()
    }

    /// Append an event with an agent ID to the chain.
    pub fn append_with_agent(
        &mut self,
        severity: EventSeverity,
        source: impl Into<String>,
        action: impl Into<String>,
        details: serde_json::Value,
        agent_id: impl Into<String>,
    ) -> &AuditEntry {
        self.auto_rotate_if_full();
        let prev_hash = self
            .entries
            .last()
            .map(|e| e.hash().to_owned())
            .or_else(|| self.prev_chain_hash.clone())
            .unwrap_or_default();
        let entry =
            AuditEntry::new(severity, source, action, details, prev_hash).with_agent(agent_id);
        debug!(
            hash = entry.hash(),
            source = entry.source(),
            action = entry.action(),
            severity = entry.severity().as_str(),
            agent = entry.agent_id().unwrap_or(""),
            index = self.entries.len(),
            "chain entry appended"
        );
        self.entries.push(entry);
        self.entries.last().unwrap()
    }

    /// Number of entries in the chain.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Get all entries.
    #[inline]
    #[must_use]
    pub fn entries(&self) -> &[AuditEntry] {
        &self.entries
    }

    /// Get the last entry's hash (chain head).
    #[inline]
    #[must_use]
    pub fn head_hash(&self) -> Option<&str> {
        self.entries.last().map(|e| e.hash())
    }

    /// Verify the entire chain's integrity.
    ///
    /// Checks the genesis entry links to the expected previous chain hash
    /// (empty string for a fresh chain, or the archived head after rotation),
    /// then delegates entry-level hash and linkage verification to [`verify_chain`].
    pub fn verify(&self) -> crate::Result<()> {
        if self.entries.is_empty() {
            return Ok(());
        }

        // Verify genesis entry links correctly (accounts for rotation)
        let expected_genesis_prev = self.prev_chain_hash.as_deref().unwrap_or("");
        if self.entries[0].prev_hash() != expected_genesis_prev {
            return Err(LibroError::IntegrityViolation {
                index: 0,
                expected: expected_genesis_prev.to_owned(),
                actual: self.entries[0].prev_hash().to_owned(),
            });
        }

        let result = verify_chain(&self.entries);
        match &result {
            Ok(()) => info!(entries = self.entries.len(), "chain verification passed"),
            Err(e) => warn!(error = %e, "chain verification failed"),
        }
        result
    }

    /// Append multiple events in one call. Each entry is chained to the previous.
    /// Returns a slice of the newly appended entries.
    pub fn append_batch(
        &mut self,
        events: impl IntoIterator<Item = (EventSeverity, String, String, serde_json::Value)>,
    ) -> &[AuditEntry] {
        let start = self.entries.len();
        for (severity, source, action, details) in events {
            self.append(severity, source, action, details);
        }
        &self.entries[start..]
    }

    /// Query entries by source.
    pub fn by_source(&self, source: &str) -> Vec<&AuditEntry> {
        self.entries
            .iter()
            .filter(|e| e.source() == source)
            .collect()
    }

    /// Query entries by severity.
    pub fn by_severity(&self, severity: EventSeverity) -> Vec<&AuditEntry> {
        self.entries
            .iter()
            .filter(|e| e.severity() == severity)
            .collect()
    }

    /// Query entries by agent ID.
    pub fn by_agent(&self, agent_id: &str) -> Vec<&AuditEntry> {
        self.entries
            .iter()
            .filter(|e| e.agent_id() == Some(agent_id))
            .collect()
    }

    /// Return a page of entries: `offset` entries skipped, up to `limit` returned.
    pub fn page(&self, offset: usize, limit: usize) -> &[AuditEntry] {
        let start = offset.min(self.entries.len());
        let end = (start + limit).min(self.entries.len());
        &self.entries[start..end]
    }

    /// Query entries using a composable [`QueryFilter`].
    pub fn query(&self, filter: &QueryFilter) -> Vec<&AuditEntry> {
        filter.apply(&self.entries)
    }

    /// Rotate the chain: drain all current entries and return them as an archive.
    /// The next entry appended will link to the previous chain's head hash,
    /// preserving continuity across rotations.
    pub fn rotate(&mut self) -> ChainArchive {
        let head_hash = self.head_hash().unwrap_or("").to_owned();
        let entries = std::mem::take(&mut self.entries);
        if !head_hash.is_empty() {
            self.prev_chain_hash = Some(head_hash.clone());
        }
        info!(
            archived = entries.len(),
            head_hash = %head_hash,
            "chain rotated"
        );
        ChainArchive { entries, head_hash }
    }

    /// Restore a chain from an archive (e.g. for verification of historical data).
    pub fn from_entries(entries: Vec<AuditEntry>) -> Self {
        Self {
            entries,
            prev_chain_hash: None,
            max_capacity: None,
            overflow_archives: Vec::new(),
        }
    }

    /// Apply a retention policy, archiving entries that fall outside the
    /// retention window. Returns the archived entries (if any).
    ///
    /// The chain maintains integrity: the first retained entry links to
    /// the last archived entry's hash via `prev_chain_hash`.
    ///
    /// Returns `None` if no entries need archiving.
    pub fn apply_retention(&mut self, policy: &RetentionPolicy) -> Option<ChainArchive> {
        let split = policy.split_index(self.entries());
        if split == 0 {
            return None;
        }

        let mut all_entries = std::mem::take(&mut self.entries);
        let retained = all_entries.split_off(split);

        let head_hash = all_entries
            .last()
            .map(|e| e.hash().to_owned())
            .unwrap_or_default();

        self.entries = retained;
        self.prev_chain_hash = Some(head_hash.clone());

        info!(
            archived = all_entries.len(),
            retained = self.entries.len(),
            "retention policy applied"
        );

        Some(ChainArchive {
            entries: all_entries,
            head_hash,
        })
    }
}

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

    #[test]
    fn chain_append_and_verify() {
        let mut chain = AuditChain::new();
        chain.append(
            EventSeverity::Info,
            "daimon",
            "agent.start",
            serde_json::json!({}),
        );
        chain.append(
            EventSeverity::Info,
            "daimon",
            "agent.stop",
            serde_json::json!({}),
        );
        assert_eq!(chain.len(), 2);
        assert!(chain.verify().is_ok());
    }

    #[test]
    fn chain_detects_tamper() {
        let mut chain = AuditChain::new();
        chain.append(EventSeverity::Info, "src", "act", serde_json::json!({}));
        chain.append(EventSeverity::Info, "src", "act2", serde_json::json!({}));

        // Tamper with first entry
        chain.entries[0].corrupt_action("hacked");
        assert!(chain.verify().is_err());
    }

    #[test]
    fn chain_query() {
        let mut chain = AuditChain::new();
        chain.append(
            EventSeverity::Info,
            "daimon",
            "start",
            serde_json::json!({}),
        );
        chain.append(
            EventSeverity::Security,
            "aegis",
            "alert",
            serde_json::json!({}),
        );
        chain.append(EventSeverity::Info, "daimon", "stop", serde_json::json!({}));

        assert_eq!(chain.by_source("daimon").len(), 2);
        assert_eq!(chain.by_severity(EventSeverity::Security).len(), 1);
    }

    #[test]
    fn empty_chain_valid() {
        let chain = AuditChain::new();
        assert!(chain.verify().is_ok());
        assert!(chain.is_empty());
    }

    #[test]
    fn head_hash() {
        let mut chain = AuditChain::new();
        assert!(chain.head_hash().is_none());
        chain.append(EventSeverity::Info, "src", "act", serde_json::json!({}));
        assert!(chain.head_hash().is_some());
    }

    #[test]
    fn rotate_archives_and_continues() {
        let mut chain = AuditChain::new();
        chain.append(EventSeverity::Info, "src", "first", serde_json::json!({}));
        chain.append(EventSeverity::Info, "src", "second", serde_json::json!({}));
        let head_before = chain.head_hash().unwrap().to_owned();

        let archive = chain.rotate();
        assert_eq!(archive.entries.len(), 2);
        assert_eq!(archive.head_hash, head_before);
        assert!(chain.is_empty());

        // New entry links to the archived chain's head
        let entry = chain.append(EventSeverity::Info, "src", "third", serde_json::json!({}));
        assert_eq!(entry.prev_hash(), head_before);
        assert!(chain.verify().is_ok());
    }

    #[test]
    fn rotate_empty_chain() {
        let mut chain = AuditChain::new();
        let archive = chain.rotate();
        assert!(archive.entries.is_empty());
        assert_eq!(archive.head_hash, "");
        // Empty rotation should NOT set prev_chain_hash
        assert!(chain.prev_chain_hash.is_none());
    }

    #[test]
    fn from_entries_verifies() {
        let mut chain = AuditChain::new();
        chain.append(EventSeverity::Info, "s", "a", serde_json::json!({}));
        chain.append(EventSeverity::Info, "s", "b", serde_json::json!({}));
        let entries = chain.entries().to_vec();

        let restored = AuditChain::from_entries(entries);
        assert_eq!(restored.len(), 2);
        assert!(restored.verify().is_ok());
    }

    #[test]
    fn multiple_rotations() {
        let mut chain = AuditChain::new();
        chain.append(EventSeverity::Info, "src", "gen1", serde_json::json!({}));
        let archive1 = chain.rotate();

        chain.append(EventSeverity::Info, "src", "gen2", serde_json::json!({}));
        assert!(chain.verify().is_ok());
        assert_eq!(chain.entries()[0].prev_hash(), archive1.head_hash);

        let archive2 = chain.rotate();
        chain.append(EventSeverity::Info, "src", "gen3", serde_json::json!({}));
        assert!(chain.verify().is_ok());
        assert_eq!(chain.entries()[0].prev_hash(), archive2.head_hash);
    }

    #[test]
    fn by_agent() {
        let mut chain = AuditChain::new();
        chain.append(
            EventSeverity::Info,
            "daimon",
            "start",
            serde_json::json!({}),
        );
        chain.append_with_agent(
            EventSeverity::Info,
            "daimon",
            "task",
            serde_json::json!({}),
            "agent-01",
        );

        assert_eq!(chain.by_agent("agent-01").len(), 1);
        assert_eq!(chain.by_agent("nonexistent").len(), 0);
    }

    #[test]
    fn query_with_filter() {
        let mut chain = AuditChain::new();
        chain.append(
            EventSeverity::Info,
            "daimon",
            "start",
            serde_json::json!({}),
        );
        chain.append(
            EventSeverity::Security,
            "aegis",
            "alert",
            serde_json::json!({}),
        );
        chain.append(EventSeverity::Info, "daimon", "stop", serde_json::json!({}));

        let results = chain.query(
            &QueryFilter::new()
                .source("daimon")
                .severity(EventSeverity::Info),
        );
        assert_eq!(results.len(), 2);

        let results = chain.query(&QueryFilter::new().action("alert"));
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn append_batch_chains_correctly() {
        let mut chain = AuditChain::new();
        let events = vec![
            (
                EventSeverity::Info,
                "daimon".to_owned(),
                "start".to_owned(),
                serde_json::json!({}),
            ),
            (
                EventSeverity::Security,
                "aegis".to_owned(),
                "alert".to_owned(),
                serde_json::json!({}),
            ),
            (
                EventSeverity::Info,
                "daimon".to_owned(),
                "stop".to_owned(),
                serde_json::json!({}),
            ),
        ];
        let appended = chain.append_batch(events);
        assert_eq!(appended.len(), 3);
        assert_eq!(chain.len(), 3);
        assert!(chain.verify().is_ok());
    }

    #[test]
    fn page_returns_slice() {
        let mut chain = AuditChain::new();
        for i in 0..10 {
            chain.append(
                EventSeverity::Info,
                "s",
                format!("e{i}"),
                serde_json::json!({}),
            );
        }
        assert_eq!(chain.page(0, 3).len(), 3);
        assert_eq!(chain.page(0, 3)[0].action(), "e0");
        assert_eq!(chain.page(3, 3).len(), 3);
        assert_eq!(chain.page(3, 3)[0].action(), "e3");
        assert_eq!(chain.page(8, 5).len(), 2); // only 2 left
        assert_eq!(chain.page(20, 5).len(), 0); // past end
    }

    #[test]
    fn verify_detects_bad_genesis_prev_hash() {
        // Manually construct a chain where genesis has wrong prev_hash
        let entry = AuditEntry::new(
            EventSeverity::Info,
            "s",
            "a",
            serde_json::json!({}),
            "bogus",
        );
        let chain = AuditChain::from_entries(vec![entry]);
        // from_entries sets prev_chain_hash to None, so expected genesis prev is ""
        let err = chain.verify().unwrap_err();
        assert!(err.to_string().contains("entry 0"));
    }

    #[test]
    fn verify_detects_broken_linkage() {
        let e1 = AuditEntry::new(EventSeverity::Info, "s", "a", serde_json::json!({}), "");
        let e2 = AuditEntry::new(
            EventSeverity::Info,
            "s",
            "b",
            serde_json::json!({}),
            "wrong-hash",
        );
        let chain = AuditChain::from_entries(vec![e1, e2]);
        let err = chain.verify().unwrap_err();
        assert!(err.to_string().contains("entry 1"));
    }

    #[test]
    fn verify_detects_tampered_self_hash() {
        let mut chain = AuditChain::new();
        chain.append(EventSeverity::Info, "s", "a", serde_json::json!({}));
        chain.append(EventSeverity::Info, "s", "b", serde_json::json!({}));
        // Tamper with the hash directly (not the content)
        chain.entries[1].corrupt_hash("tampered");
        let err = chain.verify().unwrap_err();
        assert!(err.to_string().contains("entry 1"));
    }

    #[test]
    fn append_with_agent_on_chain() {
        let mut chain = AuditChain::new();
        chain.append(
            EventSeverity::Info,
            "daimon",
            "start",
            serde_json::json!({}),
        );
        let head = chain.head_hash().unwrap().to_owned();
        let entry = chain.append_with_agent(
            EventSeverity::Info,
            "daimon",
            "task",
            serde_json::json!({}),
            "agent-007",
        );
        assert_eq!(entry.agent_id(), Some("agent-007"));
        assert_eq!(entry.prev_hash(), head);
        assert!(entry.verify());
        assert!(chain.verify().is_ok());
    }

    #[test]
    fn capacity_auto_rotates() {
        let mut chain = AuditChain::with_capacity(3);
        for i in 0..3 {
            chain.append(
                EventSeverity::Info,
                "s",
                format!("e{i}"),
                serde_json::json!({}),
            );
        }
        assert_eq!(chain.len(), 3);
        assert!(chain.take_overflow().is_empty());

        // 4th append triggers auto-rotation
        chain.append(EventSeverity::Info, "s", "e3", serde_json::json!({}));
        assert_eq!(chain.len(), 1);
        assert_eq!(chain.entries()[0].action(), "e3");

        let archives = chain.take_overflow();
        assert_eq!(archives.len(), 1);
        assert_eq!(archives[0].entries.len(), 3);

        // Chain still verifies
        assert!(chain.verify().is_ok());

        // New entry links to the archived chain's head
        assert_eq!(chain.entries()[0].prev_hash(), archives[0].head_hash);
    }

    #[test]
    fn capacity_zero_means_unlimited() {
        let mut chain = AuditChain::with_capacity(0);
        assert!(chain.max_capacity().is_none());
        for i in 0..100 {
            chain.append(
                EventSeverity::Info,
                "s",
                format!("e{i}"),
                serde_json::json!({}),
            );
        }
        assert_eq!(chain.len(), 100);
        assert!(chain.take_overflow().is_empty());
    }

    #[test]
    fn capacity_multiple_auto_rotations() {
        let mut chain = AuditChain::with_capacity(2);
        for i in 0..7 {
            chain.append(
                EventSeverity::Info,
                "s",
                format!("e{i}"),
                serde_json::json!({}),
            );
        }
        // 7 entries with capacity 2: rotations at 3rd, 5th, 7th append
        let archives = chain.take_overflow();
        assert_eq!(archives.len(), 3);
        assert!(chain.verify().is_ok());
    }

    #[test]
    fn capacity_with_agent_auto_rotates() {
        let mut chain = AuditChain::with_capacity(1);
        chain.append(EventSeverity::Info, "s", "e0", serde_json::json!({}));
        chain.append_with_agent(
            EventSeverity::Info,
            "s",
            "e1",
            serde_json::json!({}),
            "agent-01",
        );
        assert_eq!(chain.len(), 1);
        assert_eq!(chain.entries()[0].agent_id(), Some("agent-01"));
        assert_eq!(chain.take_overflow().len(), 1);
    }
}