Skip to main content

adk_auth/signed_audit/
verify.rs

1//! Offline verification of an exported audit log.
2
3use std::collections::{BTreeMap, HashSet};
4use std::fmt;
5
6use adk_core::audit_log::{
7    AUDIT_RECORD_VERSION, AuditCheckpoint, AuditHash, AuditLogEntry, AuditLogStore, AuditRecord,
8    AuditRecordKind,
9};
10use serde::{Deserialize, Serialize};
11
12use super::jcs::canonicalize;
13use super::merkle::{leaf_hash, root};
14use super::note::{CheckpointBody, Note, NoteVerifier};
15
16/// Why a log failed verification.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19#[non_exhaustive]
20pub enum VerifyFailureKind {
21    /// An entry or checkpoint could not be parsed.
22    Malformed,
23    /// Entries are missing, duplicated, or out of order.
24    SequenceBroken,
25    /// A record's text does not hash to its stored leaf hash.
26    LeafHashMismatch,
27    /// A record is not in RFC 8785 canonical form.
28    NotCanonical,
29    /// A record's `prev_hash` does not match the previous record's leaf hash.
30    ChainBroken,
31    /// Records name different logs.
32    LogIdMismatch,
33    /// A record uses a schema version this verifier does not know.
34    UnsupportedVersion,
35    /// A checkpoint carries no valid signature from a trusted key.
36    UntrustedCheckpoint,
37    /// A checkpoint's root does not match the records.
38    RootMismatch,
39    /// A checkpoint covers more records than were supplied.
40    Truncated,
41    /// Two checkpoints of the same size have different roots.
42    Fork,
43    /// Checkpoints carry different origins.
44    OriginMismatch,
45    /// The checkpoint after a key rotation is not signed by both keys.
46    RotationNotDualSigned,
47    /// Records exist but no checkpoint signs them.
48    Unanchored,
49}
50
51/// One verification failure.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "camelCase")]
54pub struct VerifyFailure {
55    /// The failure kind.
56    pub kind: VerifyFailureKind,
57    /// The record position, when the failure concerns one record.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub seq: Option<u64>,
60    /// The checkpoint size, when the failure concerns one checkpoint.
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub checkpoint_size: Option<u64>,
63    /// What was found.
64    pub message: String,
65}
66
67impl fmt::Display for VerifyFailure {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        let kind = serde_json::to_value(self.kind).ok().and_then(|v| v.as_str().map(String::from));
70        write!(f, "[{}]", kind.unwrap_or_default())?;
71        if let Some(seq) = self.seq {
72            write!(f, " record {seq}:")?;
73        }
74        if let Some(size) = self.checkpoint_size {
75            write!(f, " checkpoint {size}:")?;
76        }
77        write!(f, " {}", self.message)
78    }
79}
80
81/// The result of [`verify`].
82#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "camelCase")]
84pub struct VerifyReport {
85    /// The log id the records carry.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub log_id: Option<String>,
88    /// The checkpoint origin.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub origin: Option<String>,
91    /// Number of entries supplied.
92    pub records: u64,
93    /// Entries whose body was pruned; only their hashes were checked.
94    pub pruned: u64,
95    /// Checkpoints whose signature and root verified.
96    pub checkpoints_verified: u64,
97    /// Largest verified checkpoint size; records up to it are signed.
98    pub verified_size: u64,
99    /// Root hash at `verified_size`.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub verified_root: Option<AuditHash>,
102    /// Records after the last verified checkpoint. Removing them is not detectable
103    /// until a later checkpoint or an anchor covers them.
104    pub unsigned_tail: u64,
105    /// Verifier keys learned from dual-signed rotation checkpoints.
106    pub learned_keys: Vec<String>,
107    /// Every failure found.
108    pub failures: Vec<VerifyFailure>,
109}
110
111impl VerifyReport {
112    /// Whether the log verified with no failures.
113    pub fn is_valid(&self) -> bool {
114        self.failures.is_empty()
115    }
116
117    fn fail(
118        &mut self,
119        kind: VerifyFailureKind,
120        seq: Option<u64>,
121        size: Option<u64>,
122        message: String,
123    ) {
124        self.failures.push(VerifyFailure { kind, seq, checkpoint_size: size, message });
125    }
126}
127
128impl fmt::Display for VerifyReport {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        writeln!(f, "log:                  {}", self.log_id.as_deref().unwrap_or("-"))?;
131        writeln!(f, "origin:               {}", self.origin.as_deref().unwrap_or("-"))?;
132        writeln!(f, "records:              {} ({} pruned)", self.records, self.pruned)?;
133        writeln!(f, "checkpoints verified: {}", self.checkpoints_verified)?;
134        writeln!(f, "signed through:       {}", self.verified_size)?;
135        if let Some(root) = &self.verified_root {
136            writeln!(f, "root:                 {root}")?;
137        }
138        writeln!(f, "unsigned tail:        {}", self.unsigned_tail)?;
139        for key in &self.learned_keys {
140            writeln!(f, "learned key:          {key}")?;
141        }
142        if self.is_valid() {
143            write!(f, "result:               VALID")
144        } else {
145            writeln!(f, "result:               INVALID ({} failures)", self.failures.len())?;
146            for failure in &self.failures {
147                writeln!(f, "  {failure}")?;
148            }
149            Ok(())
150        }
151    }
152}
153
154struct Rotation {
155    seq: u64,
156    previous: Option<NoteVerifier>,
157    next: Option<NoteVerifier>,
158}
159
160/// Verifies an audit log against its signed checkpoints and the keys you trust.
161///
162/// Checks, in order:
163///
164/// 1. Entries run from seq 0 with no gaps, each record hashes to its leaf hash, is in
165///    canonical form, names one log, and links to the previous leaf through `prev_hash`.
166/// 2. Each checkpoint is signed by a trusted key, its root equals the tree over the
167///    first `size` records, it covers no more records than were supplied, and no two
168///    checkpoints of one size disagree.
169/// 3. A `key_rotated` record is followed by a checkpoint signed by both keys; the next
170///    key is then trusted and the previous one retired.
171///
172/// Flipping a byte, deleting, reordering, or truncating covered records, and forking the
173/// log under one key, each produce a failure. Records after the last checkpoint are
174/// reported as `unsigned_tail`.
175///
176/// # Example
177///
178/// ```rust
179/// use adk_auth::signed_audit::verify;
180///
181/// let report = verify(&[], &[], &[]);
182/// assert!(report.is_valid());
183/// ```
184pub fn verify(
185    entries: &[AuditLogEntry],
186    checkpoints: &[AuditCheckpoint],
187    trusted_keys: &[NoteVerifier],
188) -> VerifyReport {
189    use VerifyFailureKind as Kind;
190    let mut report = VerifyReport { records: entries.len() as u64, ..VerifyReport::default() };
191    let mut leaves = Vec::with_capacity(entries.len());
192    let mut previous_leaf: Option<AuditHash> = None;
193    let mut rotations = Vec::new();
194
195    for (position, entry) in entries.iter().enumerate() {
196        let position = position as u64;
197        if entry.seq != position {
198            report.fail(
199                Kind::SequenceBroken,
200                Some(position),
201                None,
202                format!("entry at position {position} has seq {}", entry.seq),
203            );
204        }
205        let Some(text) = &entry.record else {
206            report.pruned += 1;
207            leaves.push(entry.leaf_hash);
208            previous_leaf = Some(entry.leaf_hash);
209            continue;
210        };
211        let leaf = leaf_hash(text.as_bytes());
212        if leaf != entry.leaf_hash {
213            report.fail(
214                Kind::LeafHashMismatch,
215                Some(position),
216                None,
217                "record text does not hash to its stored leaf hash".into(),
218            );
219        }
220        leaves.push(leaf);
221        let value: serde_json::Value = match serde_json::from_str(text) {
222            Ok(value) => value,
223            Err(error) => {
224                report.fail(Kind::Malformed, Some(position), None, format!("not JSON: {error}"));
225                previous_leaf = Some(leaf);
226                continue;
227            }
228        };
229        if canonicalize(&value).ok().as_deref() != Some(text.as_str()) {
230            report.fail(
231                Kind::NotCanonical,
232                Some(position),
233                None,
234                "record is not RFC 8785 canonical".into(),
235            );
236        }
237        let record: AuditRecord = match serde_json::from_value(value) {
238            Ok(record) => record,
239            Err(error) => {
240                report.fail(
241                    Kind::Malformed,
242                    Some(position),
243                    None,
244                    format!("not an audit record: {error}"),
245                );
246                previous_leaf = Some(leaf);
247                continue;
248            }
249        };
250        if record.v != AUDIT_RECORD_VERSION {
251            report.fail(
252                Kind::UnsupportedVersion,
253                Some(position),
254                None,
255                format!("record version {} is not {AUDIT_RECORD_VERSION}", record.v),
256            );
257        }
258        if record.seq != position {
259            report.fail(
260                Kind::SequenceBroken,
261                Some(position),
262                None,
263                format!("record at position {position} claims seq {}", record.seq),
264            );
265        }
266        match &report.log_id {
267            None => report.log_id = Some(record.log_id.clone()),
268            Some(log_id) if *log_id != record.log_id => report.fail(
269                Kind::LogIdMismatch,
270                Some(position),
271                None,
272                format!("record names log '{}', expected '{log_id}'", record.log_id),
273            ),
274            Some(_) => {}
275        }
276        if record.prev_hash != previous_leaf {
277            report.fail(
278                Kind::ChainBroken,
279                Some(position),
280                None,
281                "prev_hash does not match the previous record's leaf hash".into(),
282            );
283        }
284        if record.kind == AuditRecordKind::KeyRotated {
285            let key = |name: &str| {
286                record
287                    .ext
288                    .get(name)
289                    .and_then(serde_json::Value::as_str)
290                    .and_then(|k| k.parse().ok())
291            };
292            rotations.push(Rotation {
293                seq: position,
294                previous: key("previousKey"),
295                next: key("nextKey"),
296            });
297        }
298        previous_leaf = Some(leaf);
299    }
300
301    let mut trusted: Vec<NoteVerifier> = trusted_keys.to_vec();
302    let mut retired: HashSet<NoteVerifier> = HashSet::new();
303    let mut ordered: Vec<&AuditCheckpoint> = checkpoints.iter().collect();
304    ordered.sort_by_key(|checkpoint| checkpoint.size);
305    let mut roots_by_size: BTreeMap<u64, AuditHash> = BTreeMap::new();
306    let mut rotations = rotations.into_iter().peekable();
307
308    for checkpoint in ordered {
309        let size = Some(checkpoint.size);
310        let note = match Note::parse(&checkpoint.note) {
311            Ok(note) => note,
312            Err(error) => {
313                report.fail(Kind::Malformed, None, size, error.to_string());
314                continue;
315            }
316        };
317        let body = match CheckpointBody::parse(&note.text) {
318            Ok(body) => body,
319            Err(error) => {
320                report.fail(Kind::Malformed, None, size, error.to_string());
321                continue;
322            }
323        };
324        if body.size != checkpoint.size || body.root_hash != checkpoint.root_hash {
325            report.fail(
326                Kind::Malformed,
327                None,
328                size,
329                "stored size or root differs from the signed note".into(),
330            );
331            continue;
332        }
333        match &report.origin {
334            None => report.origin = Some(body.origin.clone()),
335            Some(origin) if *origin != body.origin => {
336                report.fail(
337                    Kind::OriginMismatch,
338                    None,
339                    size,
340                    format!("origin '{}' differs", body.origin),
341                );
342                continue;
343            }
344            Some(_) => {}
345        }
346        if let Some(previous_root) = roots_by_size.insert(body.size, body.root_hash)
347            && previous_root != body.root_hash
348        {
349            report.fail(
350                Kind::Fork,
351                None,
352                size,
353                "two signed checkpoints of this size disagree".into(),
354            );
355        }
356        let active: Vec<NoteVerifier> =
357            trusted.iter().filter(|key| !retired.contains(*key)).cloned().collect();
358        if note.verified_by(&active).is_empty() {
359            report.fail(
360                Kind::UntrustedCheckpoint,
361                None,
362                size,
363                "no valid signature from a trusted key".into(),
364            );
365            continue;
366        }
367        while let Some(rotation) = rotations.next_if(|rotation| rotation.seq < body.size) {
368            let (Some(previous), Some(next)) = (rotation.previous, rotation.next) else {
369                report.fail(
370                    Kind::Malformed,
371                    Some(rotation.seq),
372                    None,
373                    "key_rotated record lacks valid previousKey and nextKey".into(),
374                );
375                continue;
376            };
377            let both = [previous.clone(), next.clone()];
378            if note.verified_by(&both).len() == 2 && active.contains(&previous) {
379                if !trusted.contains(&next) {
380                    report.learned_keys.push(next.to_string());
381                    trusted.push(next);
382                }
383                retired.insert(previous);
384            } else {
385                report.fail(
386                    Kind::RotationNotDualSigned,
387                    Some(rotation.seq),
388                    size,
389                    "the first checkpoint after the rotation is not signed by the trusted previous key and the next key"
390                        .into(),
391                );
392            }
393        }
394        if body.size > leaves.len() as u64 {
395            report.fail(
396                Kind::Truncated,
397                None,
398                size,
399                format!(
400                    "checkpoint covers {} records but {} were supplied",
401                    body.size,
402                    leaves.len()
403                ),
404            );
405            continue;
406        }
407        if root(&leaves[..body.size as usize]) != body.root_hash {
408            report.fail(
409                Kind::RootMismatch,
410                None,
411                size,
412                "root hash does not match the records".into(),
413            );
414            continue;
415        }
416        report.checkpoints_verified += 1;
417        if body.size >= report.verified_size {
418            report.verified_size = body.size;
419            report.verified_root = Some(body.root_hash);
420        }
421    }
422
423    if !entries.is_empty() && report.checkpoints_verified == 0 && report.failures.is_empty() {
424        report.fail(Kind::Unanchored, None, None, "no checkpoint signs these records".into());
425    }
426    report.unsigned_tail = (leaves.len() as u64).saturating_sub(report.verified_size);
427    report
428}
429
430/// One line of an audit export: an entry or a checkpoint.
431#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
432#[serde(tag = "type", rename_all = "camelCase")]
433pub enum ExportLine {
434    /// A log entry.
435    Entry(AuditLogEntry),
436    /// A signed checkpoint.
437    Checkpoint(AuditCheckpoint),
438}
439
440/// A log's entries and checkpoints, as read from a store or an export file.
441#[derive(Debug, Clone, Default, PartialEq, Eq)]
442pub struct AuditExport {
443    /// Entries in file order.
444    pub entries: Vec<AuditLogEntry>,
445    /// Checkpoints in file order.
446    pub checkpoints: Vec<AuditCheckpoint>,
447}
448
449impl AuditExport {
450    /// Reads every entry and checkpoint of `log_id` from `store`.
451    ///
452    /// # Errors
453    ///
454    /// Store errors.
455    pub async fn from_store(store: &dyn AuditLogStore, log_id: &str) -> adk_core::Result<Self> {
456        let size = store.size(log_id).await?;
457        Ok(Self {
458            entries: store.read(log_id, 0..size).await?,
459            checkpoints: store.checkpoints(log_id).await?,
460        })
461    }
462
463    /// Writes the export as JSON lines: entries first, then checkpoints.
464    pub fn to_jsonl(&self) -> String {
465        let mut out = String::new();
466        let lines = self
467            .entries
468            .iter()
469            .cloned()
470            .map(ExportLine::Entry)
471            .chain(self.checkpoints.iter().cloned().map(ExportLine::Checkpoint));
472        for line in lines {
473            out.push_str(&serde_json::to_string(&line).expect("export lines serialize"));
474            out.push('\n');
475        }
476        out
477    }
478
479    /// Parses an export written by [`to_jsonl`](Self::to_jsonl).
480    ///
481    /// # Errors
482    ///
483    /// Returns the 1-based line number and the parse error of the first bad line.
484    pub fn from_jsonl(text: &str) -> Result<Self, (usize, serde_json::Error)> {
485        let mut export = Self::default();
486        for (index, line) in text.lines().enumerate() {
487            if line.trim().is_empty() {
488                continue;
489            }
490            match serde_json::from_str(line).map_err(|e| (index + 1, e))? {
491                ExportLine::Entry(entry) => export.entries.push(entry),
492                ExportLine::Checkpoint(checkpoint) => export.checkpoints.push(checkpoint),
493            }
494        }
495        Ok(export)
496    }
497
498    /// Verifies the export with [`verify`].
499    pub fn verify(&self, trusted_keys: &[NoteVerifier]) -> VerifyReport {
500        verify(&self.entries, &self.checkpoints, trusted_keys)
501    }
502}