Skip to main content

ash_log/
hmac_chain.rs

1//! Tamper-evident audit logging via an HMAC hash chain.
2//!
3//! Unlike [`ChecksumIntegrity`](crate::ChecksumIntegrity), which uses an
4//! unkeyed hash that anyone can recompute, this module keys every entry with a
5//! secret and links each entry to its predecessor. An attacker who can rewrite
6//! the log file cannot produce a chain that verifies without the key, and
7//! cannot delete, reorder, or truncate entries without breaking the link.
8
9use super::{AuditEvent, AuditIntegrity};
10use hmac::{Hmac, KeyInit, Mac};
11use sha2::Sha256;
12use std::sync::Mutex;
13
14type HmacSha256 = Hmac<Sha256>;
15
16/// Metadata key holding the chained HMAC of an event.
17pub const MAC_FIELD: &str = "mac";
18
19/// Metadata key holding the event's position in the chain.
20pub const CHAIN_INDEX_FIELD: &str = "chain_index";
21
22/// Genesis value for the chain, used as the "previous MAC" of the first entry.
23const GENESIS: &str = "ash-log:genesis:v1";
24
25/// Metadata field naming the key an entry was signed with.
26///
27/// Present only when the chain was built with an identified key. Its absence
28/// means a single unidentified key, which is how every chain written before
29/// rotation support looked — so those chains canonicalize unchanged.
30pub const KEY_ID_FIELD: &str = "key_id";
31
32/// Metadata field naming the writer that produced an entry.
33///
34/// Present only when the chain was given a writer identity. See
35/// [`HmacChainIntegrity::writer`].
36pub const WRITER_FIELD: &str = "writer";
37
38/// Render bytes as lowercase hex.
39fn to_hex(bytes: &[u8]) -> String {
40    use std::fmt::Write as _;
41    bytes.iter().fold(String::new(), |mut acc, b| {
42        // Writing to a String is infallible.
43        let _ = write!(acc, "{b:02x}");
44        acc
45    })
46}
47
48/// Serialize an event to a canonical, deterministic byte string.
49///
50/// Round-tripping through [`serde_json::Value`] sorts object keys (`serde_json`'s
51/// map is a `BTreeMap` unless the `preserve_order` feature is on), so two events
52/// with equal content always produce identical bytes. The MAC and chain-index
53/// fields are removed first so a stamped event re-canonicalizes to the value
54/// that was originally signed.
55///
56/// Returns `None` only if the event contains values that cannot be serialized
57/// (for example a map with non-string keys inside `metadata` or `params`).
58fn canonicalize(event: &AuditEvent) -> Option<Vec<u8>> {
59    let mut value = serde_json::to_value(event).ok()?;
60    if let Some(metadata) = value
61        .get_mut("metadata")
62        .and_then(serde_json::Value::as_object_mut)
63    {
64        metadata.remove(MAC_FIELD);
65        metadata.remove(CHAIN_INDEX_FIELD);
66    }
67    serde_json::to_vec(&value).ok()
68}
69
70/// Compute the chained MAC for one event given the previous entry's MAC.
71///
72/// The previous MAC is bound with an explicit length prefix so that a value
73/// ending in the canonical bytes of another cannot be confused with it.
74fn compute_mac(key: &[u8], previous_mac: &str, canonical: &[u8]) -> String {
75    let mut mac =
76        <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts keys of any length");
77    mac.update(
78        &u64::try_from(previous_mac.len())
79            .unwrap_or(u64::MAX)
80            .to_be_bytes(),
81    );
82    mac.update(previous_mac.as_bytes());
83    mac.update(canonical);
84    to_hex(&mac.finalize().into_bytes())
85}
86
87/// Why a key rotation was refused.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub enum RotationError {
90    /// The chain has no key identifier, so entries could not say which key
91    /// signed them and rotation would make earlier ones unverifiable.
92    NoKeyId,
93    /// The replacement key is empty, which provides no security.
94    EmptyKey,
95    /// The identifier is already in use by the current or a retired key.
96    /// Reusing one for different key material would make entries signed with
97    /// the earlier key impossible to verify.
98    DuplicateKeyId(String),
99}
100
101impl std::fmt::Display for RotationError {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        match self {
104            Self::NoKeyId => write!(
105                f,
106                "cannot rotate a chain with no key id; call `with_key_id` before signing"
107            ),
108            Self::EmptyKey => write!(f, "the replacement key is empty and provides no security"),
109            Self::DuplicateKeyId(id) => {
110                write!(f, "key id `{id}` is already in use by this chain")
111            }
112        }
113    }
114}
115
116impl std::error::Error for RotationError {}
117
118/// Why a chain failed to verify.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum ChainError {
121    /// The event carries no `mac` metadata field, or it is not a string.
122    MissingMac {
123        /// Position of the offending entry within the verified stream.
124        index: usize,
125    },
126    /// The event could not be canonicalized for hashing.
127    NotCanonicalizable {
128        /// Position of the offending entry within the verified stream.
129        index: usize,
130    },
131    /// The stored MAC does not match the recomputed one: the entry was
132    /// modified, or an earlier entry was altered, removed, or reordered.
133    MacMismatch {
134        /// Position of the offending entry within the verified stream.
135        index: usize,
136    },
137    /// The event carries no `chain_index`, so its position cannot be
138    /// established. Only returned by
139    /// [`verify_unordered`](HmacChainIntegrity::verify_unordered).
140    MissingChainIndex {
141        /// Position of the offending entry within the verified stream.
142        index: usize,
143    },
144    /// The entry names a key this verifier does not hold, so it cannot be
145    /// checked. Supply the key, or verify with the instance that rotated.
146    UnknownKeyId {
147        /// Position of the offending entry within the verified stream.
148        index: usize,
149        /// The key identifier the entry carries.
150        key_id: String,
151    },
152    /// Entries from two different writers are interleaved in one chain.
153    ///
154    /// Each writer keeps its own index and previous-MAC state, so their output
155    /// cannot form a single valid chain. This is a configuration mistake, not
156    /// an attack, and is reported separately so it is not mistaken for one.
157    MixedWriters {
158        /// Position of the entry whose writer differs from the first.
159        index: usize,
160        /// The writer the chain started with.
161        expected: String,
162        /// The writer this entry names.
163        found: String,
164    },
165    /// The event's recorded chain index disagrees with its actual position,
166    /// which indicates entries were removed or reordered.
167    IndexMismatch {
168        /// Position of the offending entry within the verified stream.
169        index: usize,
170        /// The chain index recorded in the entry.
171        found: u64,
172    },
173}
174
175impl std::fmt::Display for ChainError {
176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177        match self {
178            Self::MissingMac { index } => {
179                write!(f, "entry {index}: missing or malformed `{MAC_FIELD}` field")
180            }
181            Self::NotCanonicalizable { index } => {
182                write!(f, "entry {index}: could not be canonicalized for hashing")
183            }
184            Self::MissingChainIndex { index } => write!(
185                f,
186                "entry {index}: missing `{CHAIN_INDEX_FIELD}` field, so its position \
187                 in the chain cannot be established"
188            ),
189            Self::UnknownKeyId { index, key_id } => write!(
190                f,
191                "entry {index}: signed with key `{key_id}`, which this verifier does not hold"
192            ),
193            Self::MixedWriters {
194                index,
195                expected,
196                found,
197            } => write!(
198                f,
199                "entry {index}: written by `{found}` but the chain began with `{expected}` — \
200                 two processes cannot share one chain; give each its own chain or key"
201            ),
202            Self::MacMismatch { index } => write!(
203                f,
204                "entry {index}: MAC mismatch — this entry or an earlier one was altered, \
205                 removed, or reordered"
206            ),
207            Self::IndexMismatch { index, found } => write!(
208                f,
209                "entry {index}: recorded chain index {found} does not match its position — \
210                 entries were removed or reordered"
211            ),
212        }
213    }
214}
215
216impl std::error::Error for ChainError {}
217
218/// Tamper-evident integrity using a keyed HMAC-SHA256 hash chain.
219///
220/// Each event is stamped with `mac = HMAC(key, prev_mac || canonical(event))`
221/// and a `chain_index`. Because the MAC covers the *entire* canonical event and
222/// is keyed with a secret, an attacker cannot silently modify a field, and
223/// because it also covers the previous MAC, they cannot delete, reorder, or
224/// truncate entries without breaking every subsequent link.
225///
226/// # Key management
227///
228/// The key must be secret and must never be written to the log it protects.
229/// Load it from a KMS, a secrets manager, or an environment variable at
230/// startup. Use at least 32 bytes of random data.
231///
232/// # Limitations
233///
234/// This makes tampering *detectable*, not impossible. An attacker who obtains
235/// the key can rewrite the whole chain. To protect against that, ship entries
236/// off-box (or to WORM storage) promptly, so the attacker never controls the
237/// only copy.
238///
239/// # Examples
240///
241/// ```rust
242/// use ash_log::*;
243///
244/// let integrity = HmacChainIntegrity::new(b"a-32-byte-or-longer-secret-key!!");
245///
246/// let mut first = AuditEvent::builder()
247///     .event_type(AuditEventType::AuthenticationAttempt)
248///     .principal("alice@example.com")
249///     .result(AuditResult::Success)
250///     .build();
251/// integrity.add_integrity(&mut first);
252///
253/// let mut second = AuditEvent::builder()
254///     .event_type(AuditEventType::MethodInvocation)
255///     .result(AuditResult::Success)
256///     .build();
257/// integrity.add_integrity(&mut second);
258///
259/// // A verifier holding the same key can confirm the whole stream.
260/// let verifier = HmacChainIntegrity::new(b"a-32-byte-or-longer-secret-key!!");
261/// assert!(verifier.verify_chain(&[first, second]).is_ok());
262/// ```
263pub struct HmacChainIntegrity {
264    key: Vec<u8>,
265    key_id: Option<String>,
266    writer: Option<String>,
267    /// Keys retired by rotation, kept so earlier entries still verify.
268    previous_keys: Vec<(String, Vec<u8>)>,
269    state: Mutex<ChainState>,
270}
271
272/// Mutable position in the chain.
273#[derive(Debug, Clone)]
274struct ChainState {
275    previous_mac: String,
276    index: u64,
277}
278
279impl HmacChainIntegrity {
280    /// Create a chain starting from the genesis value.
281    ///
282    /// Use a secret of at least 32 random bytes.
283    ///
284    /// # Panics
285    ///
286    /// Panics if `key` is empty. An empty key provides no security whatsoever,
287    /// and silently accepting one would produce a log that looks protected but
288    /// is not; failing loudly at construction is the safer behaviour.
289    #[must_use]
290    pub fn new(key: &[u8]) -> Self {
291        assert!(
292            !key.is_empty(),
293            "HmacChainIntegrity requires a non-empty key; an empty key provides no security"
294        );
295        Self {
296            key: key.to_vec(),
297            key_id: None,
298            writer: None,
299            previous_keys: Vec::new(),
300            state: Mutex::new(ChainState {
301                previous_mac: GENESIS.to_string(),
302                index: 0,
303            }),
304        }
305    }
306
307    /// Resume an existing chain from the last known MAC and index.
308    ///
309    /// Use this when a process restarts and must continue an existing log
310    /// rather than begin a new chain. Pass the `mac` and `chain_index` of the
311    /// last entry already written, so the next entry links to it.
312    ///
313    /// # Panics
314    ///
315    /// Panics if `key` is empty, for the same reason as [`new`](Self::new).
316    #[must_use]
317    pub fn resume(key: &[u8], last_mac: impl Into<String>, last_index: u64) -> Self {
318        assert!(
319            !key.is_empty(),
320            "HmacChainIntegrity requires a non-empty key; an empty key provides no security"
321        );
322        Self {
323            key: key.to_vec(),
324            key_id: None,
325            writer: None,
326            previous_keys: Vec::new(),
327            state: Mutex::new(ChainState {
328                previous_mac: last_mac.into(),
329                index: last_index.saturating_add(1),
330            }),
331        }
332    }
333
334    /// Name the key this chain signs with.
335    ///
336    /// The identifier is stamped on every entry and covered by the MAC, so a
337    /// verifier can tell which key to use without guessing, and an attacker
338    /// cannot relabel an entry to point at a key they do control.
339    ///
340    /// Required before [`rotate_to`](Self::rotate_to): rotation is meaningless
341    /// if entries do not say which key signed them.
342    #[must_use]
343    pub fn with_key_id<S: Into<String>>(mut self, key_id: S) -> Self {
344        self.key_id = Some(key_id.into());
345        self
346    }
347
348    /// Name the writer producing this chain.
349    ///
350    /// Two processes must never share one chain: each keeps its own index and
351    /// previous-MAC state, so their entries interleave into a stream that
352    /// verifies as tampered. Giving each writer a distinct identity makes that
353    /// mistake diagnosable — [`verify_chain`](Self::verify_chain) reports
354    /// [`ChainError::MixedWriters`] instead of a bare MAC mismatch, which would
355    /// otherwise look exactly like an attack.
356    ///
357    /// Give each process its own chain, its own key, or serialize writes
358    /// through one process.
359    #[must_use]
360    pub fn writer<S: Into<String>>(mut self, writer: S) -> Self {
361        self.writer = Some(writer.into());
362        self
363    }
364
365    /// Begin signing with a new key, keeping the old one for verification.
366    ///
367    /// The chain is *not* restarted: the next entry links to the previous MAC
368    /// as usual, so continuity is preserved across the rotation. Entries signed
369    /// before this call keep their original `key_id` and still verify, because
370    /// the retired key is retained.
371    ///
372    /// # Errors
373    ///
374    /// Returns [`RotationError`] if this chain has no key id, if `new_key` is
375    /// empty, or if `new_key_id` is already in use — reusing an identifier for
376    /// a different key would make earlier entries unverifiable.
377    pub fn rotate_to(
378        &mut self,
379        new_key: &[u8],
380        new_key_id: impl Into<String>,
381    ) -> Result<(), RotationError> {
382        if new_key.is_empty() {
383            return Err(RotationError::EmptyKey);
384        }
385        let Some(current_id) = self.key_id.clone() else {
386            return Err(RotationError::NoKeyId);
387        };
388        let new_key_id = new_key_id.into();
389        if new_key_id == current_id || self.previous_keys.iter().any(|(id, _)| *id == new_key_id) {
390            return Err(RotationError::DuplicateKeyId(new_key_id));
391        }
392
393        self.previous_keys.push((
394            current_id,
395            std::mem::replace(&mut self.key, new_key.to_vec()),
396        ));
397        self.key_id = Some(new_key_id);
398        Ok(())
399    }
400
401    /// The key identifier currently in use, if one was set.
402    #[must_use]
403    pub fn key_id(&self) -> Option<&str> {
404        self.key_id.as_deref()
405    }
406
407    /// Identifiers of keys retired by rotation, oldest first.
408    #[must_use]
409    pub fn retired_key_ids(&self) -> Vec<&str> {
410        self.previous_keys
411            .iter()
412            .map(|(id, _)| id.as_str())
413            .collect()
414    }
415
416    /// The key to verify an entry stamped with `key_id`.
417    ///
418    /// An entry with no identifier is verified with the current key, which is
419    /// how every chain written before rotation support behaves.
420    fn key_for(&self, key_id: Option<&str>) -> Option<&[u8]> {
421        match key_id {
422            None => Some(&self.key),
423            Some(id) if Some(id) == self.key_id.as_deref() => Some(&self.key),
424            Some(id) => self
425                .previous_keys
426                .iter()
427                .find(|(known, _)| known == id)
428                .map(|(_, key)| key.as_slice()),
429        }
430    }
431
432    /// Lock the chain state, recovering it if another thread panicked while
433    /// holding the lock. The state remains valid, and refusing to log would be
434    /// a worse outcome than continuing.
435    fn lock(&self) -> std::sync::MutexGuard<'_, ChainState> {
436        self.state
437            .lock()
438            .unwrap_or_else(std::sync::PoisonError::into_inner)
439    }
440
441    /// The MAC most recently produced, or the genesis value if none yet.
442    ///
443    /// Persist this alongside the index to later [`resume`](Self::resume).
444    #[must_use]
445    pub fn current_mac(&self) -> String {
446        self.lock().previous_mac.clone()
447    }
448
449    /// The index the next stamped event will receive.
450    #[must_use]
451    pub fn next_index(&self) -> u64 {
452        self.lock().index
453    }
454
455    /// Verify a complete chain of events in order.
456    ///
457    /// Returns the number of entries verified, or the first
458    /// [`ChainError`] encountered. Verification starts from genesis, so pass
459    /// the stream from its beginning; a mid-stream segment will report a
460    /// mismatch at entry 0.
461    ///
462    /// # Errors
463    ///
464    /// Returns [`ChainError`] identifying the first entry that fails to verify.
465    pub fn verify_chain(&self, events: &[AuditEvent]) -> Result<usize, ChainError> {
466        let mut previous_mac = GENESIS.to_string();
467        let mut chain_writer: Option<&str> = None;
468
469        for (index, event) in events.iter().enumerate() {
470            let stored_mac = event
471                .metadata
472                .get(MAC_FIELD)
473                .and_then(serde_json::Value::as_str)
474                .ok_or(ChainError::MissingMac { index })?;
475
476            // A writer change means two processes wrote one chain. Reporting it
477            // as its own error keeps a configuration mistake from being read as
478            // an attack.
479            let writer = event
480                .metadata
481                .get(WRITER_FIELD)
482                .and_then(serde_json::Value::as_str);
483            match (chain_writer, writer) {
484                (None, Some(found)) => chain_writer = Some(found),
485                (Some(expected), Some(found)) if expected != found => {
486                    return Err(ChainError::MixedWriters {
487                        index,
488                        expected: expected.to_string(),
489                        found: found.to_string(),
490                    });
491                }
492                _ => {}
493            }
494
495            // Each entry is verified with the key it names, so a chain that
496            // rotated keys mid-stream still verifies end to end.
497            let key_id = event
498                .metadata
499                .get(KEY_ID_FIELD)
500                .and_then(serde_json::Value::as_str);
501            let key = self
502                .key_for(key_id)
503                .ok_or_else(|| ChainError::UnknownKeyId {
504                    index,
505                    key_id: key_id.unwrap_or_default().to_string(),
506                })?;
507
508            if let Some(found) = event
509                .metadata
510                .get(CHAIN_INDEX_FIELD)
511                .and_then(serde_json::Value::as_u64)
512                && found != index as u64
513            {
514                return Err(ChainError::IndexMismatch { index, found });
515            }
516
517            let canonical = canonicalize(event).ok_or(ChainError::NotCanonicalizable { index })?;
518            let expected = compute_mac(key, &previous_mac, &canonical);
519
520            // `expected` is derived from the secret key; comparing it against
521            // attacker-supplied bytes is not a secret-dependent branch, but use
522            // the constant-time path anyway to avoid leaking a comparison
523            // oracle on the recomputed value.
524            if !constant_time_eq(expected.as_bytes(), stored_mac.as_bytes()) {
525                return Err(ChainError::MacMismatch { index });
526            }
527
528            previous_mac = expected;
529        }
530
531        Ok(events.len())
532    }
533
534    /// Verify a chain whose entries may not be in chain order.
535    ///
536    /// Concurrent producers stamp events under a lock but write them to the
537    /// backend afterwards, so a log written by multiple threads can contain
538    /// entries in a different order than they were stamped. Such a log is
539    /// perfectly valid, but [`verify_chain`](Self::verify_chain) rejects it
540    /// because it checks position. This method sorts by the recorded
541    /// `chain_index` first, then verifies.
542    ///
543    /// Prefer this whenever more than one thread logs to the same chain. It
544    /// requires every entry to carry a `chain_index`, and rejects duplicates,
545    /// so it detects tampering just as strictly as `verify_chain` does.
546    ///
547    /// # Errors
548    ///
549    /// Returns [`ChainError`] identifying the first entry that fails to verify.
550    /// Indices in the returned error refer to positions in chain order, not to
551    /// positions in the slice that was passed in.
552    pub fn verify_unordered(&self, events: &[AuditEvent]) -> Result<usize, ChainError> {
553        let mut ordered: Vec<AuditEvent> = events.to_vec();
554
555        // Every entry must carry an index, or sorting is meaningless.
556        for (index, event) in ordered.iter().enumerate() {
557            if event
558                .metadata
559                .get(CHAIN_INDEX_FIELD)
560                .and_then(serde_json::Value::as_u64)
561                .is_none()
562            {
563                return Err(ChainError::MissingChainIndex { index });
564            }
565        }
566
567        ordered.sort_by_key(|event| {
568            event
569                .metadata
570                .get(CHAIN_INDEX_FIELD)
571                .and_then(serde_json::Value::as_u64)
572                .unwrap_or(u64::MAX)
573        });
574
575        self.verify_chain(&ordered)
576    }
577}
578
579/// Compare two byte strings without short-circuiting on the first difference.
580fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
581    if a.len() != b.len() {
582        return false;
583    }
584    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
585}
586
587impl AuditIntegrity for HmacChainIntegrity {
588    fn add_integrity(&self, event: &mut AuditEvent) {
589        let mut state = self.lock();
590
591        // Stamp everything identifying before hashing, so all of it is covered
592        // by the MAC. A key id an attacker could rewrite would let them point
593        // an entry at a key they control.
594        event.add_metadata(CHAIN_INDEX_FIELD, state.index);
595        if let Some(key_id) = &self.key_id {
596            event.add_metadata(KEY_ID_FIELD, key_id.clone());
597        }
598        if let Some(writer) = &self.writer {
599            event.add_metadata(WRITER_FIELD, writer.clone());
600        }
601
602        let Some(canonical) = canonicalize(event) else {
603            eprintln!("[AUDIT ERROR] Failed to canonicalize event for HMAC chaining");
604            return;
605        };
606
607        let mac = compute_mac(&self.key, &state.previous_mac, &canonical);
608        event.add_metadata(MAC_FIELD, mac.clone());
609
610        state.previous_mac = mac;
611        state.index = state.index.saturating_add(1);
612    }
613
614    /// Verify a single event in isolation.
615    ///
616    /// This only confirms that a MAC field is present and well-formed; a single
617    /// event carries no proof of its position. Use
618    /// [`verify_chain`](Self::verify_chain) to actually detect tampering.
619    fn verify(&self, event: &AuditEvent) -> bool {
620        event
621            .metadata
622            .get(MAC_FIELD)
623            .and_then(serde_json::Value::as_str)
624            .is_some_and(|mac| mac.len() == 64 && mac.bytes().all(|b| b.is_ascii_hexdigit()))
625    }
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631    use crate::{AuditEventType, AuditResult};
632
633    const KEY: &[u8] = b"test-key-at-least-32-bytes-long!!";
634
635    fn event(principal: &str) -> AuditEvent {
636        AuditEvent::builder()
637            .event_type(AuditEventType::AuthenticationAttempt)
638            .principal(principal)
639            .method("login")
640            .result(AuditResult::Success)
641            .build()
642    }
643
644    fn chain_of(n: usize) -> Vec<AuditEvent> {
645        let integrity = HmacChainIntegrity::new(KEY);
646        (0..n)
647            .map(|i| {
648                let mut e = event(&format!("user{i}@example.com"));
649                integrity.add_integrity(&mut e);
650                e
651            })
652            .collect()
653    }
654
655    #[test]
656    fn test_valid_chain_verifies() {
657        let events = chain_of(5);
658        let verifier = HmacChainIntegrity::new(KEY);
659        assert_eq!(verifier.verify_chain(&events), Ok(5));
660    }
661
662    #[test]
663    fn test_empty_chain_verifies() {
664        let verifier = HmacChainIntegrity::new(KEY);
665        assert_eq!(verifier.verify_chain(&[]), Ok(0));
666    }
667
668    #[test]
669    fn test_wrong_key_fails() {
670        let events = chain_of(3);
671        let verifier = HmacChainIntegrity::new(b"a-completely-different-secret-key");
672        assert_eq!(
673            verifier.verify_chain(&events),
674            Err(ChainError::MacMismatch { index: 0 })
675        );
676    }
677
678    /// The attack that defeats `ChecksumIntegrity`: edit a field, strip the
679    /// integrity metadata, and re-stamp with the same public algorithm.
680    #[test]
681    fn test_restamp_forgery_is_detected() {
682        let mut events = chain_of(3);
683
684        events[1].principal = Some("innocent@example.com".to_string());
685        events[1].result = AuditResult::Success;
686        events[1].metadata.remove(MAC_FIELD);
687        events[1].metadata.remove(CHAIN_INDEX_FIELD);
688
689        // Attacker re-stamps using the library, but without the secret key.
690        let attacker = HmacChainIntegrity::new(b"attacker-guessed-key-not-the-real");
691        attacker.add_integrity(&mut events[1]);
692
693        // The attacker's fresh chain restarts at index 0, so the recorded
694        // index betrays the forgery before the MAC is even compared. Either
695        // way the entry is rejected.
696        let verifier = HmacChainIntegrity::new(KEY);
697        assert_eq!(
698            verifier.verify_chain(&events),
699            Err(ChainError::IndexMismatch { index: 1, found: 0 })
700        );
701
702        // With the index forged to match, the keyed MAC still catches it.
703        events[1].add_metadata(CHAIN_INDEX_FIELD, 1u64);
704        assert_eq!(
705            verifier.verify_chain(&events),
706            Err(ChainError::MacMismatch { index: 1 })
707        );
708    }
709
710    #[test]
711    fn test_field_edit_is_detected() {
712        let mut events = chain_of(3);
713        events[2].principal = Some("attacker@evil.com".to_string());
714
715        let verifier = HmacChainIntegrity::new(KEY);
716        assert_eq!(
717            verifier.verify_chain(&events),
718            Err(ChainError::MacMismatch { index: 2 })
719        );
720    }
721
722    /// Fields that `ChecksumIntegrity` ignored entirely must be covered here.
723    #[test]
724    fn test_previously_uncovered_fields_are_detected() {
725        for (name, mutate) in [
726            (
727                "severity",
728                (|e: &mut AuditEvent| {
729                    // Events are built with `Success`, which defaults to `Info`;
730                    // move to a different level so the field genuinely changes.
731                    e.severity = crate::AuditSeverity::Critical;
732                }) as fn(&mut AuditEvent),
733            ),
734            ("error", |e: &mut AuditEvent| {
735                e.error = Some("rewritten".to_string());
736            }),
737            ("metadata", |e: &mut AuditEvent| {
738                e.add_metadata("amount", 1);
739            }),
740            ("params", |e: &mut AuditEvent| {
741                e.params = Some(serde_json::json!({"forged": true}));
742            }),
743        ] {
744            let mut events = chain_of(2);
745            mutate(&mut events[1]);
746
747            let verifier = HmacChainIntegrity::new(KEY);
748            assert_eq!(
749                verifier.verify_chain(&events),
750                Err(ChainError::MacMismatch { index: 1 }),
751                "tampering with `{name}` went undetected"
752            );
753        }
754    }
755
756    #[test]
757    fn test_deletion_is_detected() {
758        let mut events = chain_of(5);
759        events.remove(2);
760
761        let verifier = HmacChainIntegrity::new(KEY);
762        // The removed entry shifts later indices, caught by the recorded index.
763        assert_eq!(
764            verifier.verify_chain(&events),
765            Err(ChainError::IndexMismatch { index: 2, found: 3 })
766        );
767    }
768
769    #[test]
770    fn test_reorder_is_detected() {
771        let mut events = chain_of(4);
772        events.swap(1, 2);
773
774        let verifier = HmacChainIntegrity::new(KEY);
775        assert!(verifier.verify_chain(&events).is_err());
776    }
777
778    #[test]
779    fn test_truncation_is_detected_via_index() {
780        // Truncating the tail leaves a valid prefix; detection requires knowing
781        // the expected length, so callers compare the final index. Verify that
782        // a truncated stream still reports its true length.
783        let events = chain_of(5);
784        let truncated = &events[..3];
785
786        let verifier = HmacChainIntegrity::new(KEY);
787        assert_eq!(verifier.verify_chain(truncated), Ok(3));
788
789        let last_index = truncated[2]
790            .metadata
791            .get(CHAIN_INDEX_FIELD)
792            .and_then(serde_json::Value::as_u64);
793        assert_eq!(last_index, Some(2), "index reveals the stream length");
794    }
795
796    #[test]
797    fn test_missing_mac_is_detected() {
798        let mut events = chain_of(2);
799        events[1].metadata.remove(MAC_FIELD);
800
801        let verifier = HmacChainIntegrity::new(KEY);
802        assert_eq!(
803            verifier.verify_chain(&events),
804            Err(ChainError::MissingMac { index: 1 })
805        );
806    }
807
808    #[test]
809    fn test_resume_continues_chain() {
810        let integrity = HmacChainIntegrity::new(KEY);
811        let mut first = event("alice@example.com");
812        integrity.add_integrity(&mut first);
813
814        // Simulate a restart: resume from the persisted MAC and index.
815        let resumed = HmacChainIntegrity::resume(KEY, integrity.current_mac(), 0);
816        let mut second = event("bob@example.com");
817        resumed.add_integrity(&mut second);
818
819        let verifier = HmacChainIntegrity::new(KEY);
820        assert_eq!(verifier.verify_chain(&[first, second]), Ok(2));
821    }
822
823    #[test]
824    fn test_canonicalization_is_order_independent() {
825        // Metadata insertion order must not change the MAC.
826        let integrity = HmacChainIntegrity::new(KEY);
827        let mut a = event("alice@example.com");
828        a.add_metadata("zebra", 1);
829        a.add_metadata("apple", 2);
830        integrity.add_integrity(&mut a);
831
832        let integrity2 = HmacChainIntegrity::new(KEY);
833        let mut b = event("alice@example.com");
834        b.add_metadata("apple", 2);
835        b.add_metadata("zebra", 1);
836        // Match timestamps so only ordering differs.
837        b.timestamp = a.timestamp;
838        integrity2.add_integrity(&mut b);
839
840        assert_eq!(
841            a.metadata.get(MAC_FIELD),
842            b.metadata.get(MAC_FIELD),
843            "metadata ordering must not affect the MAC"
844        );
845    }
846
847    #[test]
848    fn test_serialization_round_trip_preserves_verification() {
849        // The CLI verifies events that have been through JSON; make sure the
850        // round trip does not perturb the canonical form.
851        let events = chain_of(3);
852        let lines: Vec<String> = events
853            .iter()
854            .map(|e| serde_json::to_string(e).unwrap())
855            .collect();
856        let parsed: Vec<AuditEvent> = lines
857            .iter()
858            .map(|l| serde_json::from_str(l).unwrap())
859            .collect();
860
861        let verifier = HmacChainIntegrity::new(KEY);
862        assert_eq!(verifier.verify_chain(&parsed), Ok(3));
863    }
864
865    #[test]
866    fn test_constant_time_eq() {
867        assert!(constant_time_eq(b"abc", b"abc"));
868        assert!(!constant_time_eq(b"abc", b"abd"));
869        assert!(!constant_time_eq(b"abc", b"ab"));
870        assert!(constant_time_eq(b"", b""));
871    }
872
873    #[cfg(feature = "hlc")]
874    mod hlc_canonical_form {
875        use super::*;
876        use crate::{EventClock, HlcClock, Logger, NoopAuditBackend};
877        use std::sync::Arc;
878
879        /// A chain produced before this feature existed, captured as the JSON
880        /// lines it was written as. Enabling `hlc` must not change how these
881        /// verify: the field is skipped when absent, so their canonical bytes
882        /// are byte-identical to what was signed.
883        const KEY: &[u8] = b"test-key-at-least-32-bytes-long!!";
884
885        #[test]
886        fn test_events_without_a_timestamp_canonicalize_unchanged() {
887            // Built and signed exactly as a pre-`hlc` build would: no clock,
888            // so no field, so the same bytes reach the MAC.
889            let integrity = HmacChainIntegrity::new(KEY);
890            let mut events: Vec<AuditEvent> = (0..4)
891                .map(|n| {
892                    let mut event = AuditEvent::builder()
893                        .event_type(AuditEventType::AuthenticationAttempt)
894                        .principal(format!("user{n}"))
895                        .result(AuditResult::Success)
896                        .build();
897                    integrity.add_integrity(&mut event);
898                    event
899                })
900                .collect();
901
902            assert!(
903                events.iter().all(|e| e.hlc.is_none()),
904                "no clock was configured, so no event carries a timestamp"
905            );
906            assert_eq!(
907                HmacChainIntegrity::new(KEY).verify_chain(&events),
908                Ok(4),
909                "a chain with no timestamps verifies under an hlc-enabled build"
910            );
911
912            // The serialized form carries no `hlc` key at all, so a consumer
913            // reading these lines sees exactly the pre-feature schema.
914            let json = serde_json::to_value(&events[0]).unwrap();
915            assert!(json.get("hlc").is_none());
916
917            // And the round trip still verifies, which is what a log file is.
918            let line = serde_json::to_string(&events[0]).unwrap();
919            events[0] = serde_json::from_str(&line).unwrap();
920            assert_eq!(HmacChainIntegrity::new(KEY).verify_chain(&events), Ok(4));
921        }
922
923        #[test]
924        fn test_a_stamped_chain_verifies() {
925            let backend = Arc::new(NoopAuditBackend);
926            let logger = Logger::builder(backend)
927                .integrity(Arc::new(HmacChainIntegrity::new(KEY)))
928                .clock(Arc::new(HlcClock::new()))
929                .build();
930
931            // Collect what the logger produces by stamping directly, since the
932            // noop backend discards.
933            let integrity = HmacChainIntegrity::new(KEY);
934            let clock = HlcClock::new();
935            let mut events: Vec<AuditEvent> = (0..4)
936                .map(|n| {
937                    let mut event = AuditEvent::builder()
938                        .event_type(AuditEventType::AdminAction)
939                        .result(AuditResult::Success)
940                        .method(format!("action{n}"))
941                        .hlc(EventClock::from(clock.now().unwrap()))
942                        .build();
943                    integrity.add_integrity(&mut event);
944                    event
945                })
946                .collect();
947
948            assert_eq!(
949                HmacChainIntegrity::new(KEY).verify_chain(&events),
950                Ok(4),
951                "a chain of stamped events verifies"
952            );
953
954            // Round-tripping through JSON preserves the timestamp exactly, or
955            // the chain would break on reload.
956            let line = serde_json::to_string(&events[2]).unwrap();
957            let reloaded: AuditEvent = serde_json::from_str(&line).unwrap();
958            assert_eq!(reloaded.hlc, events[2].hlc);
959            events[2] = reloaded;
960            assert_eq!(HmacChainIntegrity::new(KEY).verify_chain(&events), Ok(4));
961
962            let _ = logger;
963        }
964
965        #[test]
966        fn test_rewriting_the_causal_order_is_detected() {
967            // The reason the timestamp is inside the canonical form: an
968            // attacker who edits it must forge the MAC to match.
969            let integrity = HmacChainIntegrity::new(KEY);
970            let clock = HlcClock::new();
971            let mut events: Vec<AuditEvent> = (0..3)
972                .map(|_| {
973                    let mut event = AuditEvent::builder()
974                        .event_type(AuditEventType::SecurityViolation)
975                        .result(AuditResult::Violation)
976                        .hlc(EventClock::from(clock.now().unwrap()))
977                        .build();
978                    integrity.add_integrity(&mut event);
979                    event
980                })
981                .collect();
982
983            assert_eq!(HmacChainIntegrity::new(KEY).verify_chain(&events), Ok(3));
984
985            // Backdate one entry so it appears to have happened first.
986            events[2].hlc = Some(EventClock {
987                physical: 1,
988                logical: 0,
989            });
990
991            assert_eq!(
992                HmacChainIntegrity::new(KEY).verify_chain(&events),
993                Err(ChainError::MacMismatch { index: 2 }),
994                "altering the causal timestamp breaks the MAC"
995            );
996        }
997
998        #[test]
999        fn test_adding_a_timestamp_to_a_signed_event_is_detected() {
1000            // The inverse: an event signed without a timestamp cannot have one
1001            // grafted on afterwards.
1002            let integrity = HmacChainIntegrity::new(KEY);
1003            let mut event = AuditEvent::builder()
1004                .event_type(AuditEventType::AdminAction)
1005                .result(AuditResult::Success)
1006                .build();
1007            integrity.add_integrity(&mut event);
1008
1009            assert_eq!(
1010                HmacChainIntegrity::new(KEY).verify_chain(&[event.clone()]),
1011                Ok(1)
1012            );
1013
1014            event.hlc = Some(EventClock {
1015                physical: 99,
1016                logical: 0,
1017            });
1018            assert_eq!(
1019                HmacChainIntegrity::new(KEY).verify_chain(&[event]),
1020                Err(ChainError::MacMismatch { index: 0 }),
1021                "a timestamp cannot be added to an already-signed event"
1022            );
1023        }
1024    }
1025}