auths-verifier 0.1.16

Minimal-dependency attestation verification library for Auths - supports FFI and WASM
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Offline verification of a compliance evidence pack — zero network, pure
//! function of the pack's bytes.
//!
//! An evidence pack is the org's append-only history rendered as a
//! deterministic, offline-verifiable document: one row per release, each
//! answering "who signed this artifact, and were they authorized **at
//! release time**?" by KEL position, never wall-clock. An **offline** pack
//! embeds the org's KEL material as an
//! [`AirGappedOrgBundle`](crate::org_bundle::AirGappedOrgBundle) plus, per
//! row, the transparency-log inclusion (and consistency) proof.
//!
//! This module owns the pack's wire types and [`verify_evidence_pack_offline`]
//! — the verification half. The *build* half (which classifies releases
//! against a live registry) lives in `auths-sdk` and re-exports these types,
//! so a CI gate, audit tool, or **browser** (via the WASM exports) replays
//! the same verdict from the pack file alone.

use auths_keri::Prefix;
use auths_keri::witness::independence::HonestyCeiling;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::core::Ed25519PublicKey;
use crate::org_bundle::{
    AirGappedOrgBundle, AuthorityAtSigning, classify_authority_in_bundle, verify_org_bundle,
};
use crate::tlog::{ConsistencyProof, InclusionProof, MerkleHash, SignedCheckpoint, hash_leaf};
use crate::types::IdentityDID;

/// The current evidence-pack schema version.
pub const EVIDENCE_PACK_SCHEMA_VERSION: u32 = 1;

/// Maximum accepted JSON input for the JSON/WASM surface (16 MiB) — a pack
/// embeds whole KELs and Merkle proofs, so the ceiling matches the org-bundle
/// contract's.
pub const MAX_PACK_JSON_BYTES: usize = 16 * 1024 * 1024;

/// A typed failure parsing or verifying a compliance evidence pack.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum EvidencePackError {
    /// Canonical serialization (`json-canon`) failed.
    #[error("canonicalization failed: {0}")]
    Canonicalize(String),
    /// The pack (or a JSON input) could not be decoded.
    #[error("decode failed: {0}")]
    Decode(String),
    /// Offline pack verification failed (tampered KEL, unpinned root, or a
    /// transparency proof that did not check out).
    #[error("offline verification failed: {0}")]
    OfflineVerification(String),
}

impl auths_crypto::AuthsErrorInfo for EvidencePackError {
    fn error_code(&self) -> &'static str {
        match self {
            Self::Canonicalize(_) => "AUTHS-E2301",
            Self::Decode(_) => "AUTHS-E2302",
            Self::OfflineVerification(_) => "AUTHS-E2303",
        }
    }

    fn suggestion(&self) -> Option<&'static str> {
        match self {
            Self::Canonicalize(_) | Self::Decode(_) => Some(
                "The file is not a valid evidence pack; re-export it with `auths compliance report`",
            ),
            Self::OfflineVerification(_) => Some(
                "The pack failed offline verification; obtain a fresh, untampered pack from the org",
            ),
        }
    }
}

/// The compliance framework a report targets. Each variant selects the
/// predicate the report builder renders (SLSA provenance + VSA / SPDX SBOM /
/// CRA→SSDF / SOC 2 TSC / ISO 27001 Annex-A); here it only tags the pack.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ComplianceFramework {
    /// SLSA provenance.
    Slsa,
    /// SPDX software bill of materials.
    Sbom,
    /// EU Cyber Resilience Act obligation mapping.
    Cra,
    /// SOC 2 Trust Services Criteria (TSC) control mapping.
    Soc2,
    /// ISO/IEC 27001:2022 Annex-A control mapping.
    Iso27001,
}

/// The transparency-log evidence that proves an artifact's entry is in the log,
/// bundled so a row verifies offline.
///
/// `inclusion_proof` proves the `leaf_hash` is in the tree at size N (root
/// `inclusion_proof.root`). When the inclusion was taken at a tree size **older**
/// than the embedded `signed_checkpoint`, a `consistency_proof` (N→M) proves the
/// older root is a prefix of the checkpoint root. With no consistency proof the
/// inclusion must be **against** the checkpoint (same root and size).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TransparencyInclusion {
    /// The artifact's transparency-log leaf hash (the value `inclusion_proof`
    /// proves). For a release row the leaf data is the canonical artifact
    /// digest string (`sha256:<hex>`), so `leaf_hash =
    /// hash_leaf(artifact_digest)` — row verification re-derives and compares
    /// it, binding the proof to *this* artifact rather than to whatever leaf
    /// the prover chose to embed.
    pub leaf_hash: MerkleHash,
    /// Inclusion proof for `leaf_hash` at tree size `inclusion_proof.size`.
    pub inclusion_proof: InclusionProof,
    /// The signed checkpoint the inclusion is anchored to (directly, or via the
    /// consistency proof). Its signature is verified against the verifier's
    /// **pinned log key** when one is supplied to
    /// [`verify_evidence_pack_offline`] — upgrading "in the log" from bare
    /// Merkle membership to operator-attested non-repudiation.
    pub signed_checkpoint: SignedCheckpoint,
    /// Consistency proof from the inclusion's tree size to the checkpoint's, present
    /// only when the inclusion was taken at an earlier size than the checkpoint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub consistency_proof: Option<ConsistencyProof>,
}

/// One row of compliance evidence: the signer's authority **at release**.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EvidenceRow {
    /// The artifact content digest.
    pub artifact_digest: String,
    /// The signing member's self-certifying identity.
    pub signer: IdentityDID,
    /// The signer's authority at the signing position, by KEL order.
    pub authority_at_release: AuthorityAtSigning,
    /// The artifact's in-band signing position, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signed_at: Option<u128>,
    /// Transparency-log inclusion evidence, when supplied — lets the row prove the
    /// artifact's log membership offline.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transparency: Option<TransparencyInclusion>,
}

/// A deterministic, offline-verifiable compliance evidence pack.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvidencePack {
    /// Schema version.
    pub schema_version: u32,
    /// The org whose history this pack covers.
    pub org: IdentityDID,
    /// The reporting period (free-form, e.g. `2026-Q3`).
    pub period: String,
    /// The framework this pack targets.
    pub framework: ComplianceFramework,
    /// The honest witness-diversity verdict — NEVER a bare `non_equivocation`
    /// flag. With only self-run/placeholder witnesses this is `policy_met ==
    /// false` ("single-operator — not yet independent").
    pub equivocation_visibility: HonestyCeiling,
    /// When the pack was generated (injected clock; never `Utc::now()` in domain
    /// code). Two runs with the same inputs and timestamp are byte-identical.
    pub generated_at: DateTime<Utc>,
    /// One row per classified release.
    pub rows: Vec<EvidenceRow>,
    /// The embedded, URL-free KEL material (org + member KELs + off-boarding
    /// records + pinned root) that makes authority re-derivable offline. `None`
    /// for a non-offline pack.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub org_bundle: Option<AirGappedOrgBundle>,
}

impl EvidencePack {
    /// Canonicalize with `json-canon` — the byte-exact, reproducible form an
    /// auditor re-derives and the org signs.
    pub fn canonicalize(&self) -> Result<String, EvidencePackError> {
        json_canon::to_string(self).map_err(|e| EvidencePackError::Canonicalize(e.to_string()))
    }

    /// Parse a pack back from its canonical JSON form. Typed identifiers fail
    /// closed on malformed input.
    pub fn from_json(json: &str) -> Result<Self, EvidencePackError> {
        serde_json::from_str(json).map_err(|e| EvidencePackError::Decode(e.to_string()))
    }

    /// Render as a canonical in-toto Statement: `subject` = the artifact digests,
    /// `predicate` = this pack. The org DSSE signature over these bytes lives in
    /// the SDK's compliance DSSE module.
    pub fn to_intoto_statement(&self) -> Result<String, EvidencePackError> {
        let subject: Vec<serde_json::Value> = self
            .rows
            .iter()
            .map(|r| {
                let digest = r
                    .artifact_digest
                    .strip_prefix("sha256:")
                    .unwrap_or(&r.artifact_digest);
                serde_json::json!({
                    "name": r.artifact_digest,
                    "digest": { "sha256": digest },
                })
            })
            .collect();

        let statement = serde_json::json!({
            "_type": "https://in-toto.io/Statement/v1",
            "subject": subject,
            "predicateType": "https://auths.dev/compliance/evidence/v1",
            "predicate": self,
        });

        json_canon::to_string(&statement)
            .map_err(|e| EvidencePackError::Canonicalize(e.to_string()))
    }
}

/// The offline-verification verdict for one evidence row.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RowVerdict {
    /// The artifact this row covers.
    pub artifact_digest: String,
    /// The row's signer.
    pub signer: IdentityDID,
    /// The authority recorded in the row.
    pub authority_at_release: AuthorityAtSigning,
    /// Whether re-deriving authority from the embedded KEL matches the row's
    /// recorded verdict (a tampered row flips this to `false`).
    pub authority_consistent: bool,
    /// Whether the row's transparency evidence verified: the leaf hash
    /// re-derives from the row's artifact digest AND the inclusion/consistency
    /// proof checks out. `None` when the row carries no transparency evidence.
    pub transparency_verified: Option<bool>,
    /// Whether the row's signed checkpoint is **attested by the pinned log
    /// operator**: `Some(true)` when the checkpoint signature verified under
    /// the caller's pinned log key, `Some(false)` when it did not (a forged
    /// checkpoint, or one signed by a different operator). `None` when the
    /// caller pinned no log key or the row carries no transparency evidence —
    /// the verdict is then Merkle membership only, and says so.
    pub checkpoint_attested: Option<bool>,
}

/// Verify the transparency inclusion (and consistency) of one row, offline.
pub fn verify_transparency_inclusion(t: &TransparencyInclusion) -> Result<(), EvidencePackError> {
    t.inclusion_proof.verify(&t.leaf_hash).map_err(|e| {
        EvidencePackError::OfflineVerification(format!("inclusion proof did not verify: {e}"))
    })?;

    let checkpoint_root = t.signed_checkpoint.checkpoint.root;
    let checkpoint_size = t.signed_checkpoint.checkpoint.size;

    match &t.consistency_proof {
        Some(c) => {
            if c.old_root != t.inclusion_proof.root || c.old_size != t.inclusion_proof.size {
                return Err(EvidencePackError::OfflineVerification(
                    "consistency proof old root/size does not match the inclusion proof".into(),
                ));
            }
            if c.new_root != checkpoint_root || c.new_size != checkpoint_size {
                return Err(EvidencePackError::OfflineVerification(
                    "consistency proof new root/size does not match the signed checkpoint".into(),
                ));
            }
            c.verify().map_err(|e| {
                EvidencePackError::OfflineVerification(format!(
                    "consistency proof did not verify: {e}"
                ))
            })?;
        }
        None => {
            if t.inclusion_proof.root != checkpoint_root
                || t.inclusion_proof.size != checkpoint_size
            {
                return Err(EvidencePackError::OfflineVerification(
                    "inclusion proof is not against the signed checkpoint and no consistency proof was provided".into(),
                ));
            }
        }
    }
    Ok(())
}

/// Binding + inclusion: the evidence is FOR this artifact (its leaf hash
/// re-derives from the canonical `sha256:<hex>` digest string) AND the
/// Merkle inclusion/consistency proof checks out. Operator attestation of
/// the checkpoint is a separate axis — see [`verify_artifact_log_inclusion`].
fn verify_inclusion_binds_artifact(
    artifact_digest: &str,
    t: &TransparencyInclusion,
) -> Result<(), EvidencePackError> {
    if t.leaf_hash != hash_leaf(artifact_digest.as_bytes()) {
        return Err(EvidencePackError::OfflineVerification(format!(
            "transparency evidence is not for this artifact: leaf hash does not re-derive from {artifact_digest}"
        )));
    }
    verify_transparency_inclusion(t)
}

/// Verify, fully offline, that an artifact's digest is anchored in a
/// transparency log operated by the **pinned** key — the all-or-nothing
/// verdict an artifact verifier needs (vs. the per-axis row verdicts of
/// [`verify_evidence_pack_offline`]).
///
/// Three checks, each fail-closed:
/// 1. the evidence binds to *this* artifact (`leaf_hash =
///    hash_leaf(artifact_digest)`);
/// 2. the Merkle inclusion (and any consistency) proof verifies against the
///    embedded signed checkpoint;
/// 3. the checkpoint signature verifies under the caller's pinned log key —
///    never under the key the evidence itself carries.
///
/// Args:
/// * `artifact_digest`: The canonical `sha256:<64 hex>` digest string — the
///   exact leaf data the log appended.
/// * `t`: The inclusion evidence (what `LogWriter::prove` mints).
/// * `pinned_log_key`: The log operator's Ed25519 key, pinned out of band.
///
/// Usage:
/// ```ignore
/// verify_artifact_log_inclusion("sha256:ab…", &evidence, &pinned_key)?;
/// ```
pub fn verify_artifact_log_inclusion(
    artifact_digest: &str,
    t: &TransparencyInclusion,
    pinned_log_key: &Ed25519PublicKey,
) -> Result<(), EvidencePackError> {
    verify_inclusion_binds_artifact(artifact_digest, t)?;
    t.signed_checkpoint
        .verify_log_signature(pinned_log_key)
        .map_err(|e| {
            EvidencePackError::OfflineVerification(format!(
                "checkpoint is not attested by the pinned log key: {e}"
            ))
        })
}

/// Verify an offline evidence pack with **zero network**.
///
/// Checks the embedded [`AirGappedOrgBundle`] integrity (every event
/// self-addresses AND is signed by the controlling key-state), confirms the org
/// is a pinned root, flags KEL duplicity, then for each row re-derives
/// authority-at-release from the embedded KEL (tamper check) and verifies any
/// transparency inclusion/consistency proof. With a `pinned_log_key`, each
/// row's [`SignedCheckpoint`] signature is also verified against that pinned
/// operator key ([`SignedCheckpoint::verify_log_signature`]) — "in the log"
/// becomes operator-attested non-repudiation, and a forged or backdated
/// checkpoint surfaces as `checkpoint_attested == Some(false)`. With no pinned
/// log key the verdict is Merkle membership only, reported honestly as
/// `checkpoint_attested == None`.
///
/// Args:
/// * `pack`: The pack to verify (must embed an org bundle).
/// * `pinned_roots`: The verifier's pinned trust roots.
/// * `pinned_log_key`: The log operator's Ed25519 key, pinned out of band;
///   `None` skips the checkpoint-signature axis (and the verdict says so).
///
/// Usage:
/// ```ignore
/// let verdicts = verify_evidence_pack_offline(&pack, &roots, Some(&log_key))?;
/// assert!(verdicts.iter().all(|v| v.authority_consistent));
/// ```
pub fn verify_evidence_pack_offline(
    pack: &EvidencePack,
    pinned_roots: &[IdentityDID],
    pinned_log_key: Option<&Ed25519PublicKey>,
) -> Result<Vec<RowVerdict>, EvidencePackError> {
    let bundle = pack.org_bundle.as_ref().ok_or_else(|| {
        EvidencePackError::OfflineVerification(
            "pack carries no embedded org bundle — not an offline-verifiable pack".into(),
        )
    })?;

    let report = verify_org_bundle(bundle, pinned_roots, None)
        .map_err(|e| EvidencePackError::OfflineVerification(e.to_string()))?;
    if !report.root_pinned {
        return Err(EvidencePackError::OfflineVerification(format!(
            "org {} is not in the pinned trust roots",
            bundle.org_did.as_str()
        )));
    }
    if report.duplicity_detected {
        return Err(EvidencePackError::OfflineVerification(
            "org KEL shows duplicity (same-seq divergent SAIDs)".into(),
        ));
    }

    let mut verdicts = Vec::with_capacity(pack.rows.len());
    for row in &pack.rows {
        let signer_prefix = Prefix::new_unchecked(
            row.signer
                .as_str()
                .strip_prefix("did:keri:")
                .unwrap_or(row.signer.as_str())
                .to_string(),
        );
        let rederived = classify_authority_in_bundle(bundle, &signer_prefix, row.signed_at);
        let authority_consistent = rederived == row.authority_at_release;

        // The proof must be FOR this row's artifact: the leaf is the canonical
        // digest string, so a valid proof over some other leaf is a mismatch,
        // not evidence.
        let transparency_verified = row
            .transparency
            .as_ref()
            .map(|t| verify_inclusion_binds_artifact(&row.artifact_digest, t).is_ok());

        // The operator axis: only decidable when the verifier pinned a log key
        // AND the row anchors to a checkpoint — anything else is honestly None.
        let checkpoint_attested = match (row.transparency.as_ref(), pinned_log_key) {
            (Some(t), Some(key)) => Some(t.signed_checkpoint.verify_log_signature(key).is_ok()),
            _ => None,
        };

        verdicts.push(RowVerdict {
            artifact_digest: row.artifact_digest.clone(),
            signer: row.signer.clone(),
            authority_at_release: row.authority_at_release.clone(),
            authority_consistent,
            transparency_verified,
            checkpoint_attested,
        });
    }
    Ok(verdicts)
}

// ── JSON contract (the WASM/FFI-facing form) ───────────────────────────────

/// The tagged verdict envelope for [`verify_evidence_pack_offline_json`].
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
enum PackVerdictJson {
    /// Verification ran to completion; one verdict per evidence row.
    #[serde(rename = "verdicts")]
    Verdicts {
        /// Per-row offline verdicts, in pack order.
        rows: Vec<RowVerdict>,
    },
    /// Verification failed closed (tampered pack, unpinned root, bad input).
    #[serde(rename = "error")]
    Error {
        /// The stable `AUTHS-Exxxx` code.
        code: String,
        /// Human-readable detail.
        message: String,
    },
}

/// A last-resort verdict used only if envelope serialization itself fails.
const SERIALIZE_FALLBACK: &str =
    r#"{"kind":"error","code":"AUTHS-E2301","message":"verdict serialization failed"}"#;

/// Verify an offline evidence pack from its JSON wire forms — the
/// string-in/string-out contract the WASM surface exposes.
///
/// Panic-free and synchronous: malformed or oversize input returns a tagged
/// `error` envelope, never an exception. The verdict is a discriminated union
/// (`kind`: `"verdicts"` | `"error"`), never a bare bool.
///
/// Args:
/// * `pack_json`: The [`EvidencePack`] JSON (the `.evidence` file).
/// * `pinned_roots_json`: JSON array of the verifier's pinned `did:keri:` roots.
/// * `pinned_log_key_hex`: The pinned log operator key (64 hex chars, Ed25519),
///   or `None` for a membership-only verdict.
///
/// Usage:
/// ```ignore
/// let verdict = verify_evidence_pack_offline_json(&pack, r#"["did:keri:EOrg"]"#, None);
/// ```
pub fn verify_evidence_pack_offline_json(
    pack_json: &str,
    pinned_roots_json: &str,
    pinned_log_key_hex: Option<&str>,
) -> String {
    use auths_crypto::AuthsErrorInfo;
    let envelope = match verify_pack_json_inner(pack_json, pinned_roots_json, pinned_log_key_hex) {
        Ok(rows) => PackVerdictJson::Verdicts { rows },
        Err(e) => PackVerdictJson::Error {
            code: e.error_code().to_string(),
            message: e.to_string(),
        },
    };
    serde_json::to_string(&envelope).unwrap_or_else(|_| SERIALIZE_FALLBACK.to_string())
}

/// Parse a pinned log key from its hex wire form (fail-closed on malformed input).
pub fn parse_log_key_hex(hex_key: &str) -> Result<Ed25519PublicKey, EvidencePackError> {
    let bytes = hex::decode(hex_key.trim())
        .map_err(|e| EvidencePackError::Decode(format!("pinned log key: invalid hex: {e}")))?;
    Ed25519PublicKey::try_from_slice(&bytes)
        .map_err(|e| EvidencePackError::Decode(format!("pinned log key: {e}")))
}

fn verify_pack_json_inner(
    pack_json: &str,
    pinned_roots_json: &str,
    pinned_log_key_hex: Option<&str>,
) -> Result<Vec<RowVerdict>, EvidencePackError> {
    if pack_json.len() > MAX_PACK_JSON_BYTES {
        return Err(EvidencePackError::Decode(format!(
            "pack JSON too large: {} bytes, max {}",
            pack_json.len(),
            MAX_PACK_JSON_BYTES
        )));
    }
    let pack = EvidencePack::from_json(pack_json)?;
    let pinned_roots: Vec<IdentityDID> = serde_json::from_str(pinned_roots_json)
        .map_err(|e| EvidencePackError::Decode(format!("pinned roots: {e}")))?;
    let pinned_log_key = pinned_log_key_hex.map(parse_log_key_hex).transpose()?;
    verify_evidence_pack_offline(&pack, &pinned_roots, pinned_log_key.as_ref())
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::core::{Ed25519PublicKey, Ed25519Signature};
    use crate::tlog::merkle::{hash_children, hash_leaf};
    use crate::tlog::{Checkpoint, LogOrigin};
    use auths_keri::witness::independence::EquivocationDetection;

    fn fixed_now() -> DateTime<Utc> {
        DateTime::parse_from_rfc3339("2026-06-08T00:00:00Z")
            .unwrap()
            .with_timezone(&Utc)
    }

    fn single_operator_ceiling() -> HonestyCeiling {
        // The reality today: no independent commons → not policy_met.
        HonestyCeiling {
            distinct_operators: 1,
            distinct_organizations: 1,
            distinct_jurisdictions: 1,
            distinct_infra_zones: 1,
            policy_met: false,
            equivocation: EquivocationDetection::Sampled,
            shortfalls: vec!["no independent witness commons".into()],
            label: "single-operator — not yet independent".into(),
        }
    }

    fn sample_pack() -> EvidencePack {
        EvidencePack {
            schema_version: EVIDENCE_PACK_SCHEMA_VERSION,
            org: IdentityDID::new_unchecked("did:keri:EOrg"),
            period: "2026-Q3".into(),
            framework: ComplianceFramework::Slsa,
            equivocation_visibility: single_operator_ceiling(),
            generated_at: fixed_now(),
            rows: vec![
                EvidenceRow {
                    artifact_digest: "sha256:aa".into(),
                    signer: IdentityDID::new_unchecked("did:keri:EAlice"),
                    authority_at_release: AuthorityAtSigning::AuthorizedBeforeRevocation,
                    signed_at: Some(7),
                    transparency: None,
                },
                EvidenceRow {
                    artifact_digest: "sha256:bb".into(),
                    signer: IdentityDID::new_unchecked("did:keri:EBob"),
                    authority_at_release: AuthorityAtSigning::RejectedRevokedPositionUnknown {
                        revoked_at: 12,
                    },
                    signed_at: None,
                    transparency: None,
                },
            ],
            org_bundle: None,
        }
    }

    #[test]
    fn canonicalize_is_deterministic() {
        let a = sample_pack().canonicalize().unwrap();
        let b = sample_pack().canonicalize().unwrap();
        assert_eq!(
            a, b,
            "same inputs must produce byte-identical canonical bytes"
        );
    }

    #[test]
    fn pack_round_trips_through_json() {
        let pack = sample_pack();
        let json = pack.canonicalize().unwrap();
        let back = EvidencePack::from_json(&json).unwrap();
        assert_eq!(
            json,
            back.canonicalize().unwrap(),
            "canonical JSON must round-trip byte-identically"
        );
    }

    #[test]
    fn position_unknown_is_represented_honestly_not_authorized() {
        let json = sample_pack().canonicalize().unwrap();
        assert!(json.contains("rejected_revoked_position_unknown"));
        // The unclassifiable row must NOT be silently rendered as authorized.
        let bob_authorized = json.matches("authorized_before_revocation").count();
        assert_eq!(
            bob_authorized, 1,
            "only Alice is authorized-before-revocation"
        );
    }

    #[test]
    fn intoto_statement_carries_subjects_and_predicate_type() {
        let stmt = sample_pack().to_intoto_statement().unwrap();
        assert!(stmt.contains("https://in-toto.io/Statement/v1"));
        assert!(stmt.contains("https://auths.dev/compliance/evidence/v1"));
        assert!(stmt.contains("\"sha256\":\"aa\""));
        // The predicate carries the authority verdicts.
        assert!(stmt.contains("authority_at_signing"));
    }

    #[test]
    fn pack_without_bundle_fails_offline_verification_closed() {
        let pack = sample_pack();
        let roots = vec![IdentityDID::new_unchecked("did:keri:EOrg")];
        let err = verify_evidence_pack_offline(&pack, &roots, None).unwrap_err();
        assert!(err.to_string().contains("no embedded org bundle"));
    }

    #[test]
    fn pack_json_contract_reports_errors_as_tagged_envelopes() {
        let verdict = verify_evidence_pack_offline_json("not json", "[]", None);
        let v: serde_json::Value = serde_json::from_str(&verdict).unwrap();
        assert_eq!(v["kind"], "error");
        assert_eq!(v["code"], "AUTHS-E2302");
    }

    #[test]
    fn pack_json_contract_rejects_a_malformed_pinned_log_key() {
        let pack_json = sample_pack().canonicalize().unwrap();
        for bad in ["not hex", "abcd"] {
            let verdict = verify_evidence_pack_offline_json(&pack_json, "[]", Some(bad));
            let v: serde_json::Value = serde_json::from_str(&verdict).unwrap();
            assert_eq!(
                v["kind"], "error",
                "malformed log key '{bad}' must fail closed"
            );
            assert_eq!(v["code"], "AUTHS-E2302");
        }
    }

    fn signed_checkpoint_at(size: u64, root: MerkleHash) -> SignedCheckpoint {
        SignedCheckpoint {
            checkpoint: Checkpoint {
                origin: LogOrigin::new("auths.dev/log").unwrap(),
                size,
                root,
                timestamp: fixed_now(),
            },
            log_signature: Ed25519Signature::from_bytes([0u8; 64]),
            log_public_key: Ed25519PublicKey::from_bytes([0u8; 32]),
            witnesses: vec![],
            ecdsa_checkpoint_signature: None,
            ecdsa_checkpoint_key: None,
        }
    }

    #[test]
    fn transparency_inclusion_against_checkpoint_verifies() {
        let a = hash_leaf(b"artifact-a");
        let b = hash_leaf(b"artifact-b");
        let root = hash_children(&a, &b);

        let t = TransparencyInclusion {
            leaf_hash: a,
            inclusion_proof: InclusionProof {
                index: 0,
                size: 2,
                root,
                hashes: vec![b],
            },
            signed_checkpoint: signed_checkpoint_at(2, root),
            consistency_proof: None,
        };
        verify_transparency_inclusion(&t).expect("inclusion against the checkpoint verifies");
    }

    #[test]
    fn transparency_inclusion_mismatched_checkpoint_fails() {
        let a = hash_leaf(b"artifact-a");
        let b = hash_leaf(b"artifact-b");
        let root = hash_children(&a, &b);

        let t = TransparencyInclusion {
            leaf_hash: a,
            inclusion_proof: InclusionProof {
                index: 0,
                size: 2,
                root,
                hashes: vec![b],
            },
            // A checkpoint over a DIFFERENT root with no consistency proof must fail.
            signed_checkpoint: signed_checkpoint_at(2, MerkleHash::from_bytes([0x99; 32])),
            consistency_proof: None,
        };
        assert!(
            verify_transparency_inclusion(&t).is_err(),
            "inclusion not anchored to the checkpoint must fail closed"
        );
    }

    /// A checkpoint genuinely signed by `signing_key` over its note body.
    fn operator_signed_checkpoint(
        size: u64,
        root: MerkleHash,
        signing_key: &ed25519_dalek::SigningKey,
    ) -> SignedCheckpoint {
        use ed25519_dalek::Signer;
        let checkpoint = Checkpoint {
            origin: LogOrigin::new("auths.dev/log").unwrap(),
            size,
            root,
            timestamp: fixed_now(),
        };
        let sig = signing_key.sign(checkpoint.to_note_body().as_bytes());
        SignedCheckpoint {
            checkpoint,
            log_signature: Ed25519Signature::from_bytes(sig.to_bytes()),
            log_public_key: Ed25519PublicKey::from_bytes(signing_key.verifying_key().to_bytes()),
            witnesses: vec![],
            ecdsa_checkpoint_signature: None,
            ecdsa_checkpoint_key: None,
        }
    }

    /// Evidence for `digest` in a two-leaf log signed by `signing_key`.
    fn artifact_evidence(
        digest: &str,
        signing_key: &ed25519_dalek::SigningKey,
    ) -> TransparencyInclusion {
        let leaf = hash_leaf(digest.as_bytes());
        let sibling = hash_leaf(b"sha256:other");
        let root = hash_children(&leaf, &sibling);
        TransparencyInclusion {
            leaf_hash: leaf,
            inclusion_proof: InclusionProof {
                index: 0,
                size: 2,
                root,
                hashes: vec![sibling],
            },
            signed_checkpoint: operator_signed_checkpoint(2, root, signing_key),
            consistency_proof: None,
        }
    }

    #[test]
    fn artifact_log_inclusion_verifies_under_the_pinned_operator() {
        let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
        let digest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let evidence = artifact_evidence(digest, &key);
        let pinned = Ed25519PublicKey::from_bytes(key.verifying_key().to_bytes());
        verify_artifact_log_inclusion(digest, &evidence, &pinned)
            .expect("bound, included, operator-attested evidence verifies");
    }

    #[test]
    fn artifact_log_inclusion_rejects_evidence_for_a_different_artifact() {
        let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
        let digest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let evidence = artifact_evidence(digest, &key);
        let pinned = Ed25519PublicKey::from_bytes(key.verifying_key().to_bytes());
        let other = "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
        let err = verify_artifact_log_inclusion(other, &evidence, &pinned)
            .expect_err("a valid proof for some OTHER leaf is a mismatch, not evidence");
        assert!(
            err.to_string().contains("not for this artifact"),
            "rejection must name the binding failure, got: {err}"
        );
    }

    #[test]
    fn artifact_log_inclusion_rejects_a_different_pinned_operator() {
        let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
        let digest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        let evidence = artifact_evidence(digest, &key);
        let other_operator = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32]);
        let pinned = Ed25519PublicKey::from_bytes(other_operator.verifying_key().to_bytes());
        let err = verify_artifact_log_inclusion(digest, &evidence, &pinned)
            .expect_err("a checkpoint from a different operator must fail the pinned-key check");
        assert!(
            err.to_string().contains("pinned log key"),
            "rejection must name the operator failure, got: {err}"
        );
    }
}