auths-cli 0.1.3

Command-line interface for Auths decentralized identity system
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
use anyhow::{Context, Result, anyhow};
use serde::Serialize;
use std::fs;
use std::path::{Path, PathBuf};

use auths_keri::witness::SignedReceipt;
use auths_verifier::core::Attestation;
use auths_verifier::witness::{WitnessQuorum, WitnessVerifyConfig};
use auths_verifier::{
    CanonicalDid, IdentityBundle, VerificationReport, verify_chain, verify_chain_with_witnesses,
};

use super::core::{ArtifactMetadata, ArtifactSource};
use super::file::FileArtifact;
use crate::commands::verify_helpers::parse_witness_keys;
use crate::ux::format::is_json_mode;

/// JSON output for `artifact verify --json`.
#[derive(Serialize)]
struct VerifyArtifactResult {
    file: String,
    valid: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    digest_match: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    chain_valid: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    chain_report: Option<VerificationReport>,
    #[serde(skip_serializing_if = "Option::is_none")]
    witness_quorum: Option<WitnessQuorum>,
    #[serde(skip_serializing_if = "Option::is_none")]
    issuer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    commit_sha: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    commit_verified: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

/// Execute the `artifact verify` command.
///
/// Exit codes: 0=valid, 1=invalid, 2=error.
pub async fn handle_verify(
    file: &Path,
    signature: Option<PathBuf>,
    identity_bundle: Option<PathBuf>,
    witness_receipts: Option<PathBuf>,
    witness_keys: &[String],
    witness_threshold: usize,
    verify_commit: bool,
) -> Result<()> {
    let file_str = file.to_string_lossy().to_string();

    // 1. Locate and load signature file
    let sig_path = signature.unwrap_or_else(|| {
        let mut p = file.to_path_buf();
        let new_name = format!(
            "{}.auths.json",
            p.file_name().unwrap_or_default().to_string_lossy()
        );
        p.set_file_name(new_name);
        p
    });

    let sig_content = match fs::read_to_string(&sig_path) {
        Ok(c) => c,
        Err(e) => {
            return output_error(
                &file_str,
                2,
                &format!("Failed to read signature file {:?}: {}", sig_path, e),
            );
        }
    };

    // 2. Parse attestation
    let attestation: Attestation = match serde_json::from_str(&sig_content) {
        Ok(a) => a,
        Err(e) => {
            return output_error(&file_str, 2, &format!("Failed to parse attestation: {}", e));
        }
    };

    // 3. Extract artifact metadata from payload
    let artifact_meta: ArtifactMetadata = match &attestation.payload {
        Some(payload) => match serde_json::from_value(payload.clone()) {
            Ok(m) => m,
            Err(e) => {
                return output_error(
                    &file_str,
                    2,
                    &format!("Failed to parse artifact metadata from payload: {}", e),
                );
            }
        },
        None => {
            return output_error(
                &file_str,
                2,
                "Attestation has no payload (expected artifact metadata)",
            );
        }
    };

    // 4. Compute file digest and compare
    let file_artifact = FileArtifact::new(file);
    let file_digest = match file_artifact.digest() {
        Ok(d) => d,
        Err(e) => {
            return output_error(
                &file_str,
                2,
                &format!("Failed to compute file digest: {}", e),
            );
        }
    };

    if file_digest != artifact_meta.digest {
        return output_result(
            1,
            VerifyArtifactResult {
                file: file_str.clone(),
                valid: false,
                digest_match: Some(false),
                chain_valid: None,
                chain_report: None,
                witness_quorum: None,
                issuer: Some(attestation.issuer.to_string()),
                commit_sha: attestation.commit_sha.clone(),
                commit_verified: None,
                error: Some(format!(
                    "Digest mismatch: file={}, attestation={}",
                    file_digest.hex, artifact_meta.digest.hex
                )),
            },
        );
    }

    // 5. Resolve identity public key
    // Exit-code contract: 0 = verified, 1 = verification failed (a trust or
    // signature verdict — an unresolvable/untrusted issuer is a verdict), 2 =
    // could not attempt (I/O, malformed input).
    let (root_pk, identity_did) = match resolve_identity_key(&identity_bundle, &attestation) {
        Ok(v) => v,
        Err(e) => {
            return output_error(&file_str, 1, &format!("{e:#}"));
        }
    };

    // 6. Verify attestation chain authenticity (signatures, linkage, expiry).
    //    Capability authority is no longer gated here: an artifact-signer capability
    //    grant must come from a holder-verified ACDC credential, not the attestation.
    let chain = vec![attestation.clone()];
    let chain_result = verify_chain(&chain, &root_pk).await;

    let (chain_valid, chain_report) = match chain_result {
        Ok(mut report) => {
            if let Ok(home) = auths_sdk::paths::auths_home() {
                let storage = auths_sdk::storage::RegistryAttestationStorage::new(&home);
                if let Ok(enriched) = storage.load_all_enriched() {
                    let anchor_set: std::collections::HashSet<auths_keri::Said> = enriched
                        .iter()
                        .filter(|e| e.anchor == auths_keri::AnchorStatus::Anchored)
                        .map(|e| e.said.clone())
                        .collect();
                    let all_anchored = chain.iter().all(|att| {
                        auths_sdk::attestation::canonical_said(att)
                            .is_some_and(|s| anchor_set.contains(&s))
                    });
                    report.anchored = Some(if all_anchored {
                        auths_keri::AnchorStatus::Anchored
                    } else {
                        auths_keri::AnchorStatus::NotAnchored
                    });
                }
            }
            let is_valid = report.is_valid();
            (Some(is_valid), Some(report))
        }
        Err(e) => {
            return output_error(&file_str, 1, &format!("Chain verification failed: {}", e));
        }
    };

    // 7. Optional witness verification
    let witness_quorum = match verify_witnesses(
        &chain,
        &root_pk,
        &witness_receipts,
        witness_keys,
        witness_threshold,
    )
    .await
    {
        Ok(q) => q,
        Err(e) => {
            return output_error(&file_str, 2, &format!("Witness verification error: {}", e));
        }
    };

    // 8. Compute overall verdict
    let mut valid = chain_valid.unwrap_or(false);

    if let Some(ref q) = witness_quorum
        && q.verified < q.required
    {
        valid = false;
    }

    // 8a. Ephemeral attestation: verify commit signature transitively
    let is_ephemeral = attestation.issuer.as_str().starts_with("did:key:");
    if is_ephemeral && valid {
        match &attestation.commit_sha {
            None => {
                if !is_json_mode() {
                    eprintln!(
                        "Error: ephemeral attestation (did:key issuer) requires commit_sha. \
                         This attestation is unsigned provenance without a commit anchor."
                    );
                }
                valid = false;
            }
            Some(sha) => {
                // Verify the commit is signed by a trusted key.
                // Uses in-process verification via auths-verifier (no git shell-out).
                let commit_sig_ok = verify_commit_in_process(sha).await;

                if !commit_sig_ok {
                    valid = false;
                }

                if !is_json_mode() {
                    if commit_sig_ok {
                        eprintln!(
                            "  Trust chain: artifact <- ephemeral key <- commit {} <- maintainer",
                            &sha[..8.min(sha.len())]
                        );
                    } else {
                        eprintln!(
                            "  Commit {} is not signed by a trusted maintainer.",
                            &sha[..8.min(sha.len())]
                        );
                    }
                }
            }
        }
    }

    // 8b. Display commit linkage info (always, when present)
    let commit_sha_val = attestation.commit_sha.clone();
    if let Some(ref sha) = commit_sha_val
        && !is_json_mode()
        && !is_ephemeral
    {
        eprintln!("  Commit: {}", sha);
    }

    // 8c. Optional commit attestation verification
    let commit_verified = if verify_commit {
        match &commit_sha_val {
            None => {
                if !is_json_mode() {
                    eprintln!(
                        "warning: artifact attestation has no commit_sha field; \
                         re-sign with: auths artifact sign --commit <SHA>"
                    );
                }
                None
            }
            Some(sha) => {
                // Look up commit attestation via git ref
                let commit_ref = format!("refs/auths/commits/{}", sha);
                let lookup = crate::subprocess::git_command(&[
                    "show",
                    &format!("{}:attestation.json", commit_ref),
                ])
                .output();
                match lookup {
                    Ok(output) if output.status.success() => {
                        if !is_json_mode() {
                            eprintln!("  Commit {}: signing attestation found", &sha[..12]);
                        }
                        Some(true)
                    }
                    _ => {
                        if !is_json_mode() {
                            eprintln!(
                                "warning: no signing attestation found for commit {}",
                                &sha[..std::cmp::min(sha.len(), 12)]
                            );
                        }
                        Some(false)
                    }
                }
            }
        }
    } else {
        None
    };

    let exit_code = if valid { 0 } else { 1 };

    output_result(
        exit_code,
        VerifyArtifactResult {
            file: file_str,
            valid,
            digest_match: Some(true),
            chain_valid,
            chain_report,
            witness_quorum,
            issuer: Some(identity_did.to_string()),
            commit_sha: commit_sha_val,
            commit_verified,
            error: None,
        },
    )
}

/// Resolve identity public key from bundle or from the attestation's issuer DID.
fn resolve_identity_key(
    identity_bundle: &Option<PathBuf>,
    attestation: &Attestation,
) -> Result<(auths_verifier::DevicePublicKey, CanonicalDid)> {
    if let Some(bundle_path) = identity_bundle {
        let bundle_content = fs::read_to_string(bundle_path)
            .with_context(|| format!("Failed to read identity bundle: {:?}", bundle_path))?;
        let bundle: IdentityBundle = serde_json::from_str(&bundle_content)
            .with_context(|| format!("Failed to parse identity bundle: {:?}", bundle_path))?;
        let pk_bytes = hex::decode(bundle.public_key_hex.as_str())
            .context("Invalid public key hex in bundle")?;
        let pk = auths_verifier::DevicePublicKey::try_new(bundle.curve, &pk_bytes)
            .map_err(|e| anyhow!("Invalid bundle public key: {e}"))?;
        Ok((pk, bundle.identity_did.into()))
    } else {
        // Resolve public key from the issuer DID
        let issuer = &attestation.issuer;
        let (pk_bytes, curve) = resolve_pk_from_did(issuer)
            .with_context(|| format!("Failed to resolve public key from issuer DID '{}'. Use --identity-bundle for stateless verification.", issuer))?;
        let pk = auths_verifier::DevicePublicKey::try_new(curve, &pk_bytes)
            .map_err(|e| anyhow!("Invalid issuer public key resolved from DID: {e}"))?;
        Ok((pk, issuer.clone()))
    }
}

/// Resolve a DID's current public key bytes.
///
/// `did:keri:` resolves by replaying the issuer's KEL from the local registry —
/// a KERI prefix is a digest of its inception event, never raw key bytes, and
/// only KEL replay yields the post-rotation *current* key. This is what makes
/// self-verification work: the signer's own KEL is always in the local registry.
/// `did:key:` decodes in-band (the key IS the identifier).
fn resolve_pk_from_did(did: &str) -> Result<(Vec<u8>, auths_crypto::CurveType)> {
    if did.starts_with("did:keri:") {
        let auths_home = auths_sdk::paths::auths_home()
            .map_err(|e| anyhow!("Could not locate ~/.auths: {e}"))?;
        let registry = auths_sdk::storage::GitRegistryBackend::from_config_unchecked(
            auths_sdk::storage::RegistryConfig::single_tenant(&auths_home),
        );
        let (pk, curve) = auths_sdk::keri::resolve_current_public_key(&registry, did)?;
        Ok((pk, curve))
    } else if did.starts_with("did:key:z") {
        match auths_crypto::did_key_decode(did) {
            Ok(auths_crypto::DecodedDidKey::Ed25519(pk)) => {
                Ok((pk.to_vec(), auths_crypto::CurveType::Ed25519))
            }
            Ok(auths_crypto::DecodedDidKey::P256(pk)) => Ok((pk, auths_crypto::CurveType::P256)),
            Err(e) => Err(anyhow!("Failed to resolve did:key: {}", e)),
        }
    } else {
        Err(anyhow!(
            "Unsupported DID method: {}. Use --identity-bundle instead.",
            did
        ))
    }
}

/// Verify witness receipts if provided.
async fn verify_witnesses(
    chain: &[Attestation],
    root_pk: &auths_verifier::DevicePublicKey,
    receipts_path: &Option<PathBuf>,
    witness_keys_raw: &[String],
    threshold: usize,
) -> Result<Option<WitnessQuorum>> {
    let receipts_path = match receipts_path {
        Some(p) => p,
        None => return Ok(None),
    };

    let receipts_bytes = fs::read(receipts_path)
        .with_context(|| format!("Failed to read witness receipts: {:?}", receipts_path))?;
    let receipts: Vec<SignedReceipt> =
        serde_json::from_slice(&receipts_bytes).context("Failed to parse witness receipts JSON")?;

    let witness_keys = parse_witness_keys(witness_keys_raw)?;

    let config = WitnessVerifyConfig {
        receipts: &receipts,
        witness_keys: &witness_keys,
        threshold,
    };

    let report = verify_chain_with_witnesses(chain, root_pk, &config)
        .await
        .context("Witness chain verification failed")?;

    Ok(report.witness_quorum)
}

fn output_error(file: &str, exit_code: i32, message: &str) -> Result<()> {
    if is_json_mode() {
        let result = VerifyArtifactResult {
            file: file.to_string(),
            valid: false,
            digest_match: None,
            chain_valid: None,
            chain_report: None,
            witness_quorum: None,
            issuer: None,
            commit_sha: None,
            commit_verified: None,
            error: Some(message.to_string()),
        };
        println!("{}", serde_json::to_string(&result)?);
    } else {
        eprintln!("Error: {}", message);
    }
    std::process::exit(exit_code);
}

/// Output the verification result.
fn output_result(exit_code: i32, result: VerifyArtifactResult) -> Result<()> {
    if is_json_mode() {
        println!("{}", serde_json::to_string(&result)?);
    } else if result.valid {
        print!("Artifact verified");
        if let Some(ref issuer) = result.issuer {
            print!(": signed by {}", issuer);
        }
        if let Some(ref q) = result.witness_quorum {
            print!(" (witnesses: {}/{})", q.verified, q.required);
        }
        println!();
    } else {
        eprint!("Verification failed");
        if let Some(ref error) = result.error {
            eprint!(": {}", error);
        }
        eprintln!();
    }

    if exit_code != 0 {
        std::process::exit(exit_code);
    }
    Ok(())
}

/// Verify the commit an ephemeral attestation is bound to, KEL-natively.
///
/// Reads the raw commit via git2, then delegates trust to the SDK commit-trust
/// resolver: the signer must be a device delegated under a root pinned in
/// `.auths/roots`. No `.auths/allowed_signers`, no `ssh-keygen` allowlist, no
/// `git verify-commit --raw` shell-out.
async fn verify_commit_in_process(sha: &str) -> bool {
    // Open the repository
    let repo = match git2::Repository::discover(".") {
        Ok(r) => r,
        Err(e) => {
            if !is_json_mode() {
                eprintln!("Failed to open git repository: {e}");
            }
            return false;
        }
    };

    // Parse the commit SHA
    let oid = match git2::Oid::from_str(sha) {
        Ok(o) => o,
        Err(e) => {
            if !is_json_mode() {
                eprintln!("Invalid commit SHA '{}': {e}", &sha[..8.min(sha.len())]);
            }
            return false;
        }
    };

    // The SSH signature is computed over the commit object's EXACT bytes
    // (what `git cat-file commit <sha>` prints). Read them from the object
    // database — never reconstruct them by joining header/message strings;
    // a single byte of drift makes a valid signature unverifiable.
    let commit_content = match raw_commit_bytes(&repo, oid) {
        Ok(bytes) => String::from_utf8_lossy(&bytes).to_string(),
        Err(e) => {
            if !is_json_mode() {
                eprintln!("Commit {} not found: {e}", &sha[..8.min(sha.len())]);
            }
            return false;
        }
    };

    // KEL-native trust: the commit's signer must be a device delegated under a root
    // pinned in `.auths/roots`. The verdict logic lives in the SDK commit-trust resolver.
    let provider = auths_crypto::RingCryptoProvider;
    let auths_home = match auths_sdk::paths::auths_home() {
        Ok(h) => h,
        Err(e) => {
            if !is_json_mode() {
                eprintln!("Could not locate ~/.auths: {e}");
            }
            return false;
        }
    };
    let registry = auths_sdk::storage::GitRegistryBackend::from_config_unchecked(
        auths_sdk::storage::RegistryConfig::single_tenant(&auths_home),
    );
    let pinned_roots = crate::commands::verify_helpers::load_project_pinned_roots();

    let short = &sha[..8.min(sha.len())];
    match auths_sdk::workflows::commit_trust::verify_commit_local(
        &registry,
        &pinned_roots,
        commit_content.as_bytes(),
        &provider,
    )
    .await
    {
        Ok(verdict) if verdict.is_valid() => true,
        Ok(verdict) => {
            if !is_json_mode() {
                eprintln!("Commit {short} is not authorized by a pinned trusted root: {verdict:?}");
            }
            false
        }
        Err(e) => {
            if !is_json_mode() {
                eprintln!("Commit {short} trust could not be resolved: {e}");
            }
            false
        }
    }
}

/// Verify an air-gapped org bundle entirely offline (zero network), fail-closed.
///
/// Reads the fn-154.5 bundle, loads the verifier's pinned roots (from `roots` or the
/// default `.auths/roots`, falling back to the bundle's declared roots if neither
/// exists), and classifies the optional `member` at `signed_at` purely from the
/// bundle's KEL contents. Exits non-zero on any non-authorized verdict so it can gate
/// CI.
///
/// Args:
/// * `file`: Path to the air-gapped bundle (`auths org bundle` output).
/// * `roots`: Optional pinned-roots file (default `.auths/roots`).
/// * `member`: Optional member `did:keri` to classify authority for.
/// * `signed_at`: Optional in-band signing KEL position for the member's artifact.
/// * `json`: Emit the typed report as JSON.
///
/// Usage:
/// ```ignore
/// handle_offline_verify(Path::new("acme.auths-offline"), None, None, None, false)?;
/// ```
pub fn handle_offline_verify(
    file: &Path,
    roots: Option<&Path>,
    member: Option<&str>,
    signed_at: Option<u128>,
    json: bool,
) -> Result<()> {
    use auths_sdk::workflows::org::{AirGappedOrgBundle, AuthorityAtSigning, verify_org_bundle};
    use auths_sdk::workflows::roots::parse_roots_typed;
    use auths_verifier::Prefix;
    use auths_verifier::types::IdentityDID;

    let bundle_json =
        fs::read_to_string(file).with_context(|| format!("Failed to read bundle file {file:?}"))?;
    let bundle = AirGappedOrgBundle::from_json(&bundle_json)
        .context("Failed to parse air-gapped org bundle")?;

    let roots_path = roots
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from(".auths/roots"));
    let pinned_roots: Vec<IdentityDID> = if roots_path.exists() {
        let content = fs::read_to_string(&roots_path)
            .with_context(|| format!("Failed to read roots file {roots_path:?}"))?;
        parse_roots_typed(&content).context("Failed to parse pinned roots")?
    } else {
        // No verifier-side roots configured — trust the bundle's declared roots
        // (trust-on-first-use). Supply --roots to pin explicitly.
        bundle.pinned_roots.clone()
    };

    let member_prefix =
        member.map(|m| Prefix::new_unchecked(m.strip_prefix("did:keri:").unwrap_or(m).to_string()));
    let query = member_prefix.as_ref().map(|p| (p, signed_at));

    let report =
        verify_org_bundle(&bundle, &pinned_roots, query).context("Offline verification failed")?;

    if json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        println!("Air-gapped verification of {file:?}");
        println!("  Org:            {}", report.org_did.as_str());
        println!(
            "  Verified as-of: KEL seq {} (by position, not wall-clock)",
            report.as_of_org_seq
        );
        let root = if report.root_pinned {
            "✅ yes"
        } else {
            "🛑 NO (untrusted root)"
        };
        println!("  Root pinned:    {root}");
        let dup = if report.duplicity_detected {
            "🛑 DETECTED"
        } else {
            "✅ none"
        };
        println!("  Duplicity:      {dup}");
        if let Some(authority) = &report.authority {
            match authority {
                AuthorityAtSigning::AuthorizedBeforeRevocation => {
                    println!("  Authority:      ✅ AuthorizedBeforeRevocation")
                }
                AuthorityAtSigning::RejectedAfterRevocation { revoked_at } => {
                    println!(
                        "  Authority:      🛑 RejectedAfterRevocation {{ revoked_at: {revoked_at} }}"
                    )
                }
                AuthorityAtSigning::RejectedRevokedPositionUnknown { revoked_at } => {
                    println!(
                        "  Authority:      🛑 RejectedRevokedPositionUnknown {{ revoked_at: {revoked_at} }}"
                    )
                }
                AuthorityAtSigning::NeverDelegated => {
                    println!("  Authority:      ❌ NeverDelegated")
                }
            }
        }
    }

    // Fail-closed exit: anything short of a trusted, non-duplicitous, authorized
    // verdict is a hard failure (so CI gates reject it).
    if !report.root_pinned {
        return Err(anyhow!(
            "unauthorized: the bundle's org is not in the pinned trust roots"
        ));
    }
    if report.duplicity_detected {
        return Err(anyhow!(
            "org KEL duplicity detected — divergent history; resolve before trusting"
        ));
    }
    match report.authority {
        None | Some(AuthorityAtSigning::AuthorizedBeforeRevocation) => Ok(()),
        Some(AuthorityAtSigning::RejectedAfterRevocation { revoked_at }) => Err(anyhow!(
            "unauthorized: signed at/after revocation (KEL seq {revoked_at})"
        )),
        Some(AuthorityAtSigning::RejectedRevokedPositionUnknown { revoked_at }) => Err(anyhow!(
            "unauthorized: member revoked at KEL seq {revoked_at}; artifact has no in-band signing position"
        )),
        Some(AuthorityAtSigning::NeverDelegated) => {
            Err(anyhow!("unauthorized: the org never delegated this member"))
        }
    }
}

/// The raw commit object bytes, exactly as `git cat-file commit <oid>` prints
/// them — the payload an SSH commit signature is computed over.
///
/// Args:
/// * `repo`: An open git repository.
/// * `oid`: The commit's object id.
///
/// Usage:
/// ```ignore
/// let bytes = raw_commit_bytes(&repo, oid)?;
/// ```
pub(crate) fn raw_commit_bytes(repo: &git2::Repository, oid: git2::Oid) -> Result<Vec<u8>> {
    let odb = repo.odb().context("open git object database")?;
    let obj = odb.read(oid).context("read commit object")?;
    Ok(obj.data().to_vec())
}

#[cfg(test)]
mod tests {
    use super::raw_commit_bytes;
    use std::process::Command;

    /// Regression: the bytes the verifier checks the SSH signature over must
    /// be byte-identical to `git cat-file commit`. A prior implementation
    /// reconstructed them from raw_header + "\n\n" + message, drifting by one
    /// newline and making every valid signature report SshSignatureInvalid.
    #[test]
    fn raw_commit_bytes_matches_git_cat_file() {
        let (dir, repo) = auths_test_utils::git::init_test_repo();
        let sig = git2::Signature::now("t", "t@example.com").expect("sig");
        let tree_id = {
            let mut index = repo.index().expect("index");
            index.write_tree().expect("tree")
        };
        let tree = repo.find_tree(tree_id).expect("find tree");
        let oid = repo
            .commit(
                Some("HEAD"),
                &sig,
                &sig,
                "subject line\n\nbody with trailing newline drift potential\n",
                &tree,
                &[],
            )
            .expect("commit");

        let via_helper = raw_commit_bytes(&repo, oid).expect("helper");
        let via_git = Command::new("git")
            .args(["cat-file", "commit", &oid.to_string()])
            .current_dir(dir.path())
            .output()
            .expect("git cat-file");
        assert!(via_git.status.success());
        assert_eq!(
            via_helper, via_git.stdout,
            "verifier payload must be byte-identical to git cat-file commit"
        );
    }
}