1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19#[non_exhaustive]
20pub enum VerifyFailureKind {
21 Malformed,
23 SequenceBroken,
25 LeafHashMismatch,
27 NotCanonical,
29 ChainBroken,
31 LogIdMismatch,
33 UnsupportedVersion,
35 UntrustedCheckpoint,
37 RootMismatch,
39 Truncated,
41 Fork,
43 OriginMismatch,
45 RotationNotDualSigned,
47 Unanchored,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "camelCase")]
54pub struct VerifyFailure {
55 pub kind: VerifyFailureKind,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub seq: Option<u64>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub checkpoint_size: Option<u64>,
63 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "camelCase")]
84pub struct VerifyReport {
85 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub log_id: Option<String>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub origin: Option<String>,
91 pub records: u64,
93 pub pruned: u64,
95 pub checkpoints_verified: u64,
97 pub verified_size: u64,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub verified_root: Option<AuditHash>,
102 pub unsigned_tail: u64,
105 pub learned_keys: Vec<String>,
107 pub failures: Vec<VerifyFailure>,
109}
110
111impl VerifyReport {
112 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
160pub 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(¬e.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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
432#[serde(tag = "type", rename_all = "camelCase")]
433pub enum ExportLine {
434 Entry(AuditLogEntry),
436 Checkpoint(AuditCheckpoint),
438}
439
440#[derive(Debug, Clone, Default, PartialEq, Eq)]
442pub struct AuditExport {
443 pub entries: Vec<AuditLogEntry>,
445 pub checkpoints: Vec<AuditCheckpoint>,
447}
448
449impl AuditExport {
450 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 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 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 pub fn verify(&self, trusted_keys: &[NoteVerifier]) -> VerifyReport {
500 verify(&self.entries, &self.checkpoints, trusted_keys)
501 }
502}