crtx-ledger 0.1.1

Append-only event log, hash chain, trace assembly, and audit records.
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! Sigstore Rekor live adapter (ADR 0013 Mechanism C, slice 2 of Gate 4).
//!
//! Authorized by `docs/decisions/COUNCIL_TIEBREAKS_2026_05_14.md`
//! (commit `1eb93b6`) Decision #2 (immediate slice) and Decision #4 (dep
//! set). Implements the **adapter-boundary** ECDSA P-256 verification of
//! Rekor `SignedEntryTimestamp` proofs and SHA-256 Merkle inclusion-proof
//! verification. **Does not** rewrite the per-witness-class
//! [`cortex_verifier::IndependentWitness`] surface — that is explicitly
//! deferred to an ADR 0041 amendment.
//!
//! Rekor entry kind: [`REKOR_KIND_HASHEDREKORD_V0_0_1`]. The adapter
//! intentionally does not parse the inner Rekor entry body fields — the
//! body is opaque from the SET-signature perspective, and the only thing
//! that must be verified is that the body the Rekor server signed is the
//! same body Cortex submitted. Cortex re-derives the canonical
//! SET-signing buffer from `(logId, logIndex, integratedTime, body)` and
//! checks the ECDSA signature against the trusted root's Rekor
//! verifying key.
//!
//! Live submission uses [`ureq`] for a small, sync HTTP client surface.
//! Offline tests do not exercise [`submit`] — they call
//! [`verify_receipt`] with a checked-in fixture and synthesized
//! `TrustedRoot`.

use std::time::Duration as StdDuration;

use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use chrono::Utc;
use p256::ecdsa::signature::Verifier as _;
use p256::ecdsa::{DerSignature, Signature, VerifyingKey};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{debug, warn};

use crate::anchor::LedgerAnchor;
use crate::external_sink::trusted_root::{TrustedRoot, TrustedRootKeyError};
use crate::external_sink::{anchor_text_sha256, ExternalReceipt, ExternalSink};
use crate::sha256::sha256;

/// Rekor entry kind for this adapter.
pub const REKOR_KIND_HASHEDREKORD_V0_0_1: &str = "hashedrekord:0.0.1";

/// Default Rekor public endpoint.
pub const REKOR_DEFAULT_ENDPOINT: &str = "https://rekor.sigstore.dev";

/// Rekor REST API path for entry submission.
const REKOR_ENTRIES_PATH: &str = "/api/v1/log/entries";

/// Default sync HTTP timeout for Rekor submission.
const REKOR_HTTP_TIMEOUT: StdDuration = StdDuration::from_secs(20);

// =============================================================================
// Stable invariant identifiers — keyed off by the CLI and external scripts.
// =============================================================================

/// Stable invariant emitted when the HTTP submission to Rekor failed.
pub const REKOR_SUBMIT_FAILED_INVARIANT: &str = "audit.anchor.rekor.submit_failed";
/// Stable invariant emitted when the Rekor receipt failed offline verification.
pub const REKOR_VERIFY_FAILED_INVARIANT: &str = "audit.anchor.rekor.verify_failed";
/// Stable invariant emitted when the Merkle inclusion proof did not reconstruct
/// the declared root hash.
pub const REKOR_INCLUSION_PROOF_INVALID_INVARIANT: &str =
    "audit.anchor.rekor.inclusion_proof_invalid";
/// Stable invariant emitted when the ECDSA P-256 verification of the
/// `SignedEntryTimestamp` failed.
pub const REKOR_SET_SIGNATURE_INVALID_INVARIANT: &str = "audit.anchor.rekor.set_signature_invalid";
/// Stable invariant emitted when the local trusted-root cache is stale beyond
/// the Decision #1 30-day window.
pub const REKOR_TRUSTED_ROOT_STALE_INVARIANT: &str = "audit.anchor.rekor.trusted_root_stale";
/// Stable invariant emitted when `cortex audit verify --against-external` runs
/// the live Rekor receipt verifier and the signature does not match.
pub const REKOR_VERIFY_SIGNATURE_MISMATCH_INVARIANT: &str = "audit.verify.rekor.signature_mismatch";

/// Stable status string emitted by `cortex audit anchor --sink rekor`
/// after a successful submit + verify pass.
pub const REKOR_EXTERNAL_AUTHORITY_STATUS: &str = "external_authority_rekor";

// =============================================================================
// Receipt body shape
// =============================================================================

/// Inclusion proof body that the Rekor REST API returns inside
/// `verification.inclusionProof`. Hash list is in leaf-to-root sibling order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InclusionProof {
    /// Index of the witnessed leaf in the log.
    #[serde(rename = "logIndex")]
    pub log_index: u64,
    /// Size of the log tree at the time the proof was produced.
    #[serde(rename = "treeSize")]
    pub tree_size: u64,
    /// Lowercase hex SHA-256 of the tree root that the proof reconstructs.
    #[serde(rename = "rootHash")]
    pub root_hash: String,
    /// Sibling hashes leaf-to-root, each lowercase hex SHA-256.
    pub hashes: Vec<String>,
}

/// Typed Rekor receipt body the adapter consumes. Mirrors the subset of the
/// Rekor REST API response that ADR 0013 cares about; unknown fields
/// outside this struct are ignored at the [`ExternalReceipt::receipt`]
/// JSON-value boundary.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RekorReceiptBody {
    /// Rekor-assigned UUID for this entry.
    pub uuid: String,
    /// Stable log identifier the Rekor server uses to scope its signing key.
    #[serde(rename = "logID")]
    pub log_id: String,
    /// Index of this entry in the Rekor log.
    #[serde(rename = "logIndex")]
    pub log_index: u64,
    /// Server-recorded integration time (epoch seconds).
    #[serde(rename = "integratedTime")]
    pub integrated_time: i64,
    /// Base64-encoded ECDSA P-256 signature in DER form over the canonical
    /// SET-signing buffer.
    #[serde(rename = "signedEntryTimestamp")]
    pub signed_entry_timestamp: String,
    /// Base64-encoded JSON body the Rekor server stored for this entry.
    #[serde(rename = "body")]
    pub body_base64: String,
    /// Merkle inclusion proof.
    #[serde(rename = "inclusionProof")]
    pub inclusion_proof: InclusionProof,
}

// =============================================================================
// Submit
// =============================================================================

/// HTTP request body Cortex POSTs to the Rekor REST API. Mirrors the
/// Rekor `proposedEntries` schema for `hashedrekord:0.0.1`.
#[derive(Debug, Serialize)]
struct RekorSubmitRequest<'a> {
    #[serde(rename = "apiVersion")]
    api_version: &'a str,
    kind: &'a str,
    spec: RekorSubmitSpec<'a>,
}

#[derive(Debug, Serialize)]
struct RekorSubmitSpec<'a> {
    data: RekorSubmitData<'a>,
}

#[derive(Debug, Serialize)]
struct RekorSubmitData<'a> {
    hash: RekorSubmitHash<'a>,
}

#[derive(Debug, Serialize)]
struct RekorSubmitHash<'a> {
    algorithm: &'a str,
    value: &'a str,
}

/// Submit a Cortex anchor to a live Rekor instance and return the parsed
/// external receipt envelope.
///
/// This call performs **one** sync HTTP POST against `<endpoint>{REKOR_ENTRIES_PATH}`,
/// parses the response body as the Rekor entry JSON, and assembles the
/// canonical [`ExternalReceipt`] envelope. It does not verify the SET
/// signature — call [`verify_receipt`] for that.
///
/// Network and JSON-parse errors fail closed with [`RekorError::SubmitHttp`]
/// or [`RekorError::SubmitBody`]; both surface the
/// [`REKOR_SUBMIT_FAILED_INVARIANT`] token to scripts.
pub fn submit(anchor: &LedgerAnchor, endpoint: &str) -> Result<ExternalReceipt, RekorError> {
    let anchor_text = anchor.to_anchor_text();
    let anchor_hash = sha256(anchor_text.as_bytes());
    let anchor_hash_hex = lowercase_hex(&anchor_hash);
    let request = RekorSubmitRequest {
        api_version: "0.0.1",
        kind: REKOR_KIND_HASHEDREKORD_V0_0_1,
        spec: RekorSubmitSpec {
            data: RekorSubmitData {
                hash: RekorSubmitHash {
                    algorithm: "sha256",
                    value: &anchor_hash_hex,
                },
            },
        },
    };

    let url = format!("{}{REKOR_ENTRIES_PATH}", endpoint.trim_end_matches('/'));
    debug!(target: "cortex.audit.anchor.rekor", endpoint = %url, "submitting Rekor entry");

    let agent = ureq::AgentBuilder::new()
        .timeout(REKOR_HTTP_TIMEOUT)
        .build();
    let response = agent
        .post(&url)
        .set("Content-Type", "application/json")
        .send_json(serde_json::to_value(&request).expect("submit request serializes"))
        .map_err(|source| {
            warn!(
                target: "cortex.audit.anchor.rekor",
                invariant = REKOR_SUBMIT_FAILED_INVARIANT,
                error = %source,
                "Rekor submission failed"
            );
            RekorError::SubmitHttp {
                invariant: REKOR_SUBMIT_FAILED_INVARIANT,
                reason: source.to_string(),
            }
        })?;

    let response_text = response
        .into_string()
        .map_err(|source| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: format!("failed to read Rekor response body: {source}"),
        })?;
    let receipt = parse_rekor_submit_response(&response_text)?;

    let anchor_text_sha256_hex = anchor_text_sha256(anchor);
    let envelope = ExternalReceipt {
        sink: ExternalSink::Rekor,
        anchor_text_sha256: anchor_text_sha256_hex,
        anchor_event_count: anchor.event_count,
        anchor_chain_head_hash: anchor.chain_head_hash.clone(),
        submitted_at: Utc::now(),
        sink_endpoint: endpoint.to_string(),
        receipt: serde_json::to_value(&receipt).map_err(|source| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: format!("failed to re-encode Rekor receipt body: {source}"),
        })?,
    };
    Ok(envelope)
}

/// Parse the Rekor `POST /api/v1/log/entries` response body. The Rekor
/// REST API wraps the entry in a one-element map keyed by UUID — extract
/// it and emit the typed [`RekorReceiptBody`].
fn parse_rekor_submit_response(text: &str) -> Result<RekorReceiptBody, RekorError> {
    let parsed: serde_json::Value =
        serde_json::from_str(text).map_err(|source| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: format!("Rekor response is not valid JSON: {source}"),
        })?;
    let entry_map = parsed.as_object().ok_or_else(|| RekorError::SubmitBody {
        invariant: REKOR_SUBMIT_FAILED_INVARIANT,
        reason: "Rekor response is not a JSON object".to_string(),
    })?;
    let (uuid, entry) = entry_map
        .iter()
        .next()
        .ok_or_else(|| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: "Rekor response did not contain any entry".to_string(),
        })?;

    let body_base64 = entry
        .get("body")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: "Rekor response entry missing string body".to_string(),
        })?
        .to_string();
    let log_id = entry
        .get("logID")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: "Rekor response entry missing logID".to_string(),
        })?
        .to_string();
    let log_index = entry
        .get("logIndex")
        .and_then(serde_json::Value::as_u64)
        .ok_or_else(|| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: "Rekor response entry missing logIndex".to_string(),
        })?;
    let integrated_time = entry
        .get("integratedTime")
        .and_then(serde_json::Value::as_i64)
        .ok_or_else(|| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: "Rekor response entry missing integratedTime".to_string(),
        })?;
    let signed_entry_timestamp = entry
        .pointer("/verification/signedEntryTimestamp")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: "Rekor response entry missing verification.signedEntryTimestamp".to_string(),
        })?
        .to_string();
    let inclusion_value = entry
        .pointer("/verification/inclusionProof")
        .ok_or_else(|| RekorError::SubmitBody {
            invariant: REKOR_SUBMIT_FAILED_INVARIANT,
            reason: "Rekor response entry missing verification.inclusionProof".to_string(),
        })?;
    let inclusion_proof: InclusionProof =
        serde_json::from_value(inclusion_value.clone()).map_err(|source| {
            RekorError::SubmitBody {
                invariant: REKOR_SUBMIT_FAILED_INVARIANT,
                reason: format!("Rekor response inclusionProof did not parse: {source}"),
            }
        })?;

    Ok(RekorReceiptBody {
        uuid: uuid.clone(),
        log_id,
        log_index,
        integrated_time,
        signed_entry_timestamp,
        body_base64,
        inclusion_proof,
    })
}

// =============================================================================
// Verify
// =============================================================================

/// Offline verification result for a Rekor receipt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RekorVerification {
    /// Log index of the entry.
    pub log_index: u64,
    /// Rekor-assigned UUID.
    pub uuid: String,
    /// Base64-encoded SET signature (lifted out so the CLI can log it).
    pub set_signature: String,
}

/// Verify a Rekor receipt offline against a [`TrustedRoot`].
///
/// Checks (in order):
///
/// 1. The receipt sink is [`ExternalSink::Rekor`].
/// 2. The receipt body parses as a typed [`RekorReceiptBody`].
/// 3. The Rekor `body` decodes from base64 and is a JSON object with the
///    expected `kind` = [`REKOR_KIND_HASHEDREKORD_V0_0_1`].
/// 4. The ECDSA P-256 verification of `signedEntryTimestamp` succeeds
///    against the trusted-root's Rekor verifying key and the canonical
///    SET-signing buffer produced by [`rekor_canonical_set_body`].
/// 5. The SHA-256 Merkle inclusion proof reconstructs the declared
///    `rootHash` from the receipt's `body` leaf.
pub fn verify_receipt(
    receipt: &ExternalReceipt,
    trusted_root: &TrustedRoot,
) -> Result<RekorVerification, RekorError> {
    if receipt.sink != ExternalSink::Rekor {
        return Err(RekorError::WrongSink {
            invariant: REKOR_VERIFY_FAILED_INVARIANT,
            observed: receipt.sink,
        });
    }

    let body: RekorReceiptBody =
        serde_json::from_value(receipt.receipt.clone()).map_err(|source| {
            RekorError::MalformedReceipt {
                invariant: REKOR_VERIFY_FAILED_INVARIANT,
                reason: format!("Rekor receipt body did not parse: {source}"),
            }
        })?;

    let decoded_body = BASE64_STANDARD
        .decode(body.body_base64.as_bytes())
        .map_err(|source| RekorError::MalformedReceipt {
            invariant: REKOR_VERIFY_FAILED_INVARIANT,
            reason: format!("Rekor receipt body is not valid base64: {source}"),
        })?;
    let body_json: serde_json::Value =
        serde_json::from_slice(&decoded_body).map_err(|source| RekorError::MalformedReceipt {
            invariant: REKOR_VERIFY_FAILED_INVARIANT,
            reason: format!("Rekor receipt body is not JSON: {source}"),
        })?;
    let kind = body_json
        .get("kind")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default();
    if kind != REKOR_KIND_HASHEDREKORD_V0_0_1 {
        return Err(RekorError::MalformedReceipt {
            invariant: REKOR_VERIFY_FAILED_INVARIANT,
            reason: format!(
                "Rekor receipt body kind `{kind}` is not `{REKOR_KIND_HASHEDREKORD_V0_0_1}`"
            ),
        });
    }

    // BH-3 fix
    // (`docs/reviews/BUG_HUNT_2026-05-12_post_8f43450.md` Finding 3):
    // bind the verifying-key selection to the receipt's `body.logID`
    // so an entry signed by a non-active tlog (rotation, attacker
    // mirror, GHSA-whqx-f9j3-ch6m) cannot be silently verified
    // against the latest-activated key. Refusal surfaces as
    // `RekorError::TlogLogIdUnknown` carrying the stable
    // `rekor.trusted_root.tlog_logid_no_match` invariant.
    let rekor_key =
        trusted_root
            .rekor_verifying_key(&body.log_id)
            .map_err(|source| match source {
                TrustedRootKeyError::TlogLogIdNoMatch {
                    invariant,
                    receipt_log_id,
                    tlog_log_ids,
                } => RekorError::TlogLogIdUnknown {
                    invariant,
                    receipt_log_id,
                    tlog_log_ids,
                },
                other => RekorError::MalformedReceipt {
                    invariant: REKOR_VERIFY_FAILED_INVARIANT,
                    reason: format!("trusted_root has no usable Rekor verifying key: {other}"),
                },
            })?;
    verify_set_signature(&body, &rekor_key)?;
    verify_inclusion_proof(&body, &decoded_body)?;

    Ok(RekorVerification {
        log_index: body.log_index,
        uuid: body.uuid,
        set_signature: body.signed_entry_timestamp,
    })
}

/// Canonical Rekor SET-signing buffer. Stable shared between the
/// generator example, the live submit path, and the offline verifier.
///
/// The Rekor server signs a JSON document with keys sorted in this exact
/// order. Cortex re-derives the same byte sequence so the ECDSA
/// signature check covers the operator-visible fields without depending
/// on a JSON-canonicalization library.
#[must_use]
pub fn rekor_canonical_set_body(
    log_id: &str,
    log_index: u64,
    integrated_time: i64,
    body_base64: &str,
) -> String {
    // Hand-rolled stable JSON — keys in the exact order Rekor signs them.
    // Strings are not expected to contain control characters; integers are
    // emitted without quotes.
    let mut out = String::with_capacity(64 + body_base64.len() + log_id.len());
    out.push('{');
    out.push_str("\"body\":\"");
    out.push_str(body_base64);
    out.push_str("\",\"integratedTime\":");
    out.push_str(&integrated_time.to_string());
    out.push_str(",\"logID\":\"");
    out.push_str(log_id);
    out.push_str("\",\"logIndex\":");
    out.push_str(&log_index.to_string());
    out.push('}');
    out
}

fn verify_set_signature(
    body: &RekorReceiptBody,
    verifying_key: &VerifyingKey,
) -> Result<(), RekorError> {
    let canonical = rekor_canonical_set_body(
        &body.log_id,
        body.log_index,
        body.integrated_time,
        &body.body_base64,
    );
    let signature_bytes = BASE64_STANDARD
        .decode(body.signed_entry_timestamp.as_bytes())
        .map_err(|source| RekorError::SetSignatureInvalid {
            invariant: REKOR_SET_SIGNATURE_INVALID_INVARIANT,
            reason: format!("signedEntryTimestamp is not valid base64: {source}"),
        })?;
    let der_sig = DerSignature::from_bytes(&signature_bytes).map_err(|source| {
        RekorError::SetSignatureInvalid {
            invariant: REKOR_SET_SIGNATURE_INVALID_INVARIANT,
            reason: format!("signedEntryTimestamp is not valid ECDSA DER: {source}"),
        }
    })?;
    let signature: Signature =
        der_sig
            .try_into()
            .map_err(|source: ecdsa::Error| RekorError::SetSignatureInvalid {
                invariant: REKOR_SET_SIGNATURE_INVALID_INVARIANT,
                reason: format!("signedEntryTimestamp DER->fixed-size conversion failed: {source}"),
            })?;

    verifying_key
        .verify(canonical.as_bytes(), &signature)
        .map_err(|source| {
            warn!(
                target: "cortex.audit.anchor.rekor",
                invariant = REKOR_SET_SIGNATURE_INVALID_INVARIANT,
                error = %source,
                "Rekor SET signature verification failed"
            );
            RekorError::SetSignatureInvalid {
                invariant: REKOR_SET_SIGNATURE_INVALID_INVARIANT,
                reason: source.to_string(),
            }
        })?;
    Ok(())
}

fn verify_inclusion_proof(body: &RekorReceiptBody, decoded_leaf: &[u8]) -> Result<(), RekorError> {
    let mut current = sha256(decoded_leaf);
    let mut index = body.inclusion_proof.log_index;
    if index >= body.inclusion_proof.tree_size {
        return Err(RekorError::InclusionProofInvalid {
            invariant: REKOR_INCLUSION_PROOF_INVALID_INVARIANT,
            reason: format!(
                "logIndex {index} is not strictly less than treeSize {}",
                body.inclusion_proof.tree_size
            ),
        });
    }
    let mut bound = body.inclusion_proof.tree_size;
    for sibling_hex in &body.inclusion_proof.hashes {
        let sibling =
            decode_hex_32(sibling_hex).map_err(|reason| RekorError::InclusionProofInvalid {
                invariant: REKOR_INCLUSION_PROOF_INVALID_INVARIANT,
                reason,
            })?;
        let combined = if index % 2 == 0 {
            concat_hash(&current, &sibling)
        } else {
            concat_hash(&sibling, &current)
        };
        current = combined;
        index /= 2;
        bound = bound.div_ceil(2);
        if bound == 0 {
            break;
        }
    }
    let expected_root = decode_hex_32(&body.inclusion_proof.root_hash).map_err(|reason| {
        RekorError::InclusionProofInvalid {
            invariant: REKOR_INCLUSION_PROOF_INVALID_INVARIANT,
            reason,
        }
    })?;
    if current != expected_root {
        warn!(
            target: "cortex.audit.anchor.rekor",
            invariant = REKOR_INCLUSION_PROOF_INVALID_INVARIANT,
            "Rekor inclusion proof did not reconstruct rootHash"
        );
        return Err(RekorError::InclusionProofInvalid {
            invariant: REKOR_INCLUSION_PROOF_INVALID_INVARIANT,
            reason: format!(
                "reconstructed root `{}` does not match declared root `{}`",
                lowercase_hex(&current),
                body.inclusion_proof.root_hash
            ),
        });
    }
    Ok(())
}

fn concat_hash(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] {
    let mut buf = [0u8; 64];
    buf[..32].copy_from_slice(left);
    buf[32..].copy_from_slice(right);
    sha256(&buf)
}

fn decode_hex_32(value: &str) -> Result<[u8; 32], String> {
    if value.len() != 64 {
        return Err(format!(
            "expected 64 lowercase hex chars in proof element, got {}",
            value.len()
        ));
    }
    let bytes = value.as_bytes();
    let mut out = [0u8; 32];
    for (i, chunk) in bytes.chunks_exact(2).enumerate() {
        let hi = decode_hex_nibble(chunk[0])
            .ok_or_else(|| format!("non-hex character at position {}", i * 2))?;
        let lo = decode_hex_nibble(chunk[1])
            .ok_or_else(|| format!("non-hex character at position {}", i * 2 + 1))?;
        out[i] = (hi << 4) | lo;
    }
    Ok(out)
}

fn decode_hex_nibble(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(10 + b - b'a'),
        _ => None,
    }
}

fn lowercase_hex(bytes: &[u8; 32]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(64);
    for b in bytes {
        out.push(HEX[(b >> 4) as usize] as char);
        out.push(HEX[(b & 0x0f) as usize] as char);
    }
    out
}

// =============================================================================
// Error type
// =============================================================================

/// Errors produced by the Rekor submit + verify adapter.
#[derive(Debug, Error)]
pub enum RekorError {
    /// Live submission to Rekor failed at the HTTP layer.
    #[error("{invariant}: Rekor HTTP submission failed: {reason}")]
    SubmitHttp {
        /// Stable invariant token, equal to [`REKOR_SUBMIT_FAILED_INVARIANT`].
        invariant: &'static str,
        /// Human-readable failure reason.
        reason: String,
    },
    /// Rekor returned a response that did not parse as the expected entry shape.
    #[error("{invariant}: Rekor response body did not parse: {reason}")]
    SubmitBody {
        /// Stable invariant token, equal to [`REKOR_SUBMIT_FAILED_INVARIANT`].
        invariant: &'static str,
        /// Human-readable parse failure reason.
        reason: String,
    },
    /// The receipt envelope declared a sink other than Rekor.
    #[error("{invariant}: external receipt sink is `{observed}`, expected `rekor`")]
    WrongSink {
        /// Stable invariant token, equal to [`REKOR_VERIFY_FAILED_INVARIANT`].
        invariant: &'static str,
        /// Observed sink.
        observed: ExternalSink,
    },
    /// The Rekor receipt body did not parse as the expected typed shape.
    #[error("{invariant}: Rekor receipt is malformed: {reason}")]
    MalformedReceipt {
        /// Stable invariant token, equal to [`REKOR_VERIFY_FAILED_INVARIANT`].
        invariant: &'static str,
        /// Human-readable malformation reason.
        reason: String,
    },
    /// The ECDSA P-256 verification of the SET signature failed.
    #[error("{invariant}: Rekor SignedEntryTimestamp did not verify: {reason}")]
    SetSignatureInvalid {
        /// Stable invariant token, equal to [`REKOR_SET_SIGNATURE_INVALID_INVARIANT`].
        invariant: &'static str,
        /// Human-readable verification failure reason.
        reason: String,
    },
    /// The SHA-256 Merkle inclusion proof did not reconstruct the declared root.
    #[error("{invariant}: Rekor inclusion proof did not verify: {reason}")]
    InclusionProofInvalid {
        /// Stable invariant token, equal to [`REKOR_INCLUSION_PROOF_INVALID_INVARIANT`].
        invariant: &'static str,
        /// Human-readable proof failure reason.
        reason: String,
    },
    /// The local trusted root cache is older than the Decision #1 30-day window.
    #[error("{invariant}: trusted-root cache is stale (signed_at={signed_at_rfc3339})")]
    TrustedRootStale {
        /// Stable invariant token, equal to [`REKOR_TRUSTED_ROOT_STALE_INVARIANT`].
        invariant: &'static str,
        /// RFC 3339 timestamp of the cached trust root.
        signed_at_rfc3339: String,
    },
    /// No declared tlog in the trusted root has a `logId.keyId` matching
    /// the Rekor receipt's `body.logID`. Closes BH-3 (Cosign
    /// GHSA-whqx-f9j3-ch6m class). Carries the
    /// [`REKOR_TRUSTED_ROOT_TLOG_LOGID_NO_MATCH_INVARIANT`] invariant so
    /// the CLI can surface a verifier-visible refusal that is distinct
    /// from the generic "trusted_root has no usable Rekor verifying
    /// key" branch.
    #[error(
        "{invariant}: trusted_root has no tlog whose logId.keyId matches Rekor receipt logID `{receipt_log_id}` (declared tlogs: {})",
        tlog_log_ids.join(", ")
    )]
    TlogLogIdUnknown {
        /// Stable invariant token, equal to
        /// [`REKOR_TRUSTED_ROOT_TLOG_LOGID_NO_MATCH_INVARIANT`].
        invariant: &'static str,
        /// `body.logID` from the Rekor receipt that failed to bind.
        receipt_log_id: String,
        /// The tlog `logId.keyId` values declared in the trusted root,
        /// preserved verbatim from the JSON. Empty when every tlog
        /// omitted `logId.keyId`.
        tlog_log_ids: Vec<String>,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::external_sink::trusted_root::TrustedRoot;
    use crate::external_sink::{parse_external_receipt, EXTERNAL_RECEIPT_FORMAT_HEADER_V1};

    fn valid_fixture_text() -> &'static str {
        include_str!("../../../cortex-cli/tests/fixtures/rekor/rekor_receipt_valid.json")
    }

    fn tampered_set_fixture_text() -> &'static str {
        include_str!("../../../cortex-cli/tests/fixtures/rekor/rekor_receipt_tampered_set.json")
    }

    fn tampered_proof_fixture_text() -> &'static str {
        include_str!("../../../cortex-cli/tests/fixtures/rekor/rekor_receipt_tampered_proof.json")
    }

    /// Fixture-specific trust root: parses the agent's pre-merge
    /// `trusted_root_snapshot.json` (v1 shim envelope) and projects the
    /// fixture's Rekor public key into a real Sigstore TUF [`TrustedRoot`]
    /// shape. The fixture key was synthesised offline from
    /// [`crate::external_sink::rekor`]'s `synthesize_rekor_fixture` example
    /// using a fixed SIGNING_SEED, so it cannot verify against the
    /// production Sigstore embedded trust root and must NOT be confused
    /// with the live Rekor channel.
    /// `logID` value the fixture Rekor receipts carry in `body.logID`.
    /// Matched verbatim by [`fixture_trust_root`] via the BH-3
    /// log-bound key selector.
    const FIXTURE_REKOR_LOG_ID: &str = "fixture-log-id";

    fn fixture_trust_root() -> TrustedRoot {
        use chrono::TimeZone;
        #[derive(serde::Deserialize)]
        #[serde(deny_unknown_fields)]
        struct FixtureSnapshot {
            #[allow(dead_code)]
            format_version: u32,
            rekor_public_key_pem: String,
            signed_at: chrono::DateTime<chrono::Utc>,
        }
        let raw =
            include_str!("../../../cortex-cli/tests/fixtures/rekor/trusted_root_snapshot.json");
        let snapshot: FixtureSnapshot =
            serde_json::from_str(raw).expect("fixture trust root parses");
        let _ = chrono::Utc.timestamp_opt(0, 0); // import use
        TrustedRoot::from_fixture_rekor_pem(
            &snapshot.rekor_public_key_pem,
            snapshot.signed_at,
            FIXTURE_REKOR_LOG_ID,
        )
        .expect("fixture Rekor PEM decodes")
    }

    #[test]
    fn canonical_set_body_is_stable_byte_order() {
        let canonical = rekor_canonical_set_body("log-1", 7, 1_700_000_000, "Ym9keQ==");
        assert_eq!(
            canonical,
            "{\"body\":\"Ym9keQ==\",\"integratedTime\":1700000000,\"logID\":\"log-1\",\"logIndex\":7}"
        );
    }

    #[test]
    fn verify_receipt_accepts_well_formed_fixture() {
        let receipt = parse_external_receipt(valid_fixture_text()).expect("fixture parses");
        let trusted_root = fixture_trust_root();
        let verification = verify_receipt(&receipt, &trusted_root).expect("verifies");
        assert_eq!(verification.log_index, 2);
    }

    #[test]
    fn verify_receipt_rejects_tampered_set_signature() {
        let receipt = parse_external_receipt(tampered_set_fixture_text()).expect("fixture parses");
        let trusted_root = fixture_trust_root();
        let err = verify_receipt(&receipt, &trusted_root).unwrap_err();
        assert!(
            matches!(err, RekorError::SetSignatureInvalid { invariant, .. } if invariant == REKOR_SET_SIGNATURE_INVALID_INVARIANT),
            "got {err:?}"
        );
    }

    #[test]
    fn verify_receipt_rejects_tampered_inclusion_proof() {
        let receipt =
            parse_external_receipt(tampered_proof_fixture_text()).expect("fixture parses");
        let trusted_root = fixture_trust_root();
        let err = verify_receipt(&receipt, &trusted_root).unwrap_err();
        assert!(
            matches!(err, RekorError::InclusionProofInvalid { invariant, .. } if invariant == REKOR_INCLUSION_PROOF_INVALID_INVARIANT),
            "got {err:?}"
        );
    }

    #[test]
    fn verify_receipt_rejects_wrong_sink() {
        let mut receipt = parse_external_receipt(valid_fixture_text()).expect("fixture parses");
        receipt.sink = ExternalSink::OpenTimestamps;
        let trusted_root = fixture_trust_root();
        let err = verify_receipt(&receipt, &trusted_root).unwrap_err();
        assert!(matches!(err, RekorError::WrongSink { .. }));
    }

    #[test]
    fn verify_receipt_rejects_receipt_whose_logid_does_not_bind_to_any_tlog() {
        // BH-3 (Cosign GHSA-whqx-f9j3-ch6m): swap the trust root's
        // tlog log_id so the fixture receipt's `body.logID` matches
        // nothing. The verifier MUST refuse with
        // `RekorError::TlogLogIdUnknown` and the
        // `rekor.trusted_root.tlog_logid_no_match` invariant — NOT
        // silently re-use the latest-activated tlog.
        let receipt = parse_external_receipt(valid_fixture_text()).expect("fixture parses");
        // Build a trust root with a different log_id so the receipt's
        // `body.logID` cannot bind.
        use chrono::TimeZone;
        #[derive(serde::Deserialize)]
        #[serde(deny_unknown_fields)]
        struct FixtureSnapshot {
            #[allow(dead_code)]
            format_version: u32,
            rekor_public_key_pem: String,
            signed_at: chrono::DateTime<chrono::Utc>,
        }
        let raw =
            include_str!("../../../cortex-cli/tests/fixtures/rekor/trusted_root_snapshot.json");
        let snapshot: FixtureSnapshot =
            serde_json::from_str(raw).expect("fixture trust root parses");
        let _ = chrono::Utc.timestamp_opt(0, 0);
        let trusted_root = TrustedRoot::from_fixture_rekor_pem(
            &snapshot.rekor_public_key_pem,
            snapshot.signed_at,
            // Intentionally not the fixture's log_id.
            "wrong-log-id-not-the-fixture",
        )
        .expect("fixture Rekor PEM decodes");
        let err = verify_receipt(&receipt, &trusted_root).unwrap_err();
        match err {
            RekorError::TlogLogIdUnknown {
                invariant,
                receipt_log_id,
                ..
            } => {
                assert_eq!(invariant, "rekor.trusted_root.tlog_logid_no_match");
                assert_eq!(receipt_log_id, "fixture-log-id");
            }
            other => panic!("expected TlogLogIdUnknown, got {other:?}"),
        }
    }

    #[test]
    fn fixture_header_is_v1() {
        assert!(valid_fixture_text().starts_with(EXTERNAL_RECEIPT_FORMAT_HEADER_V1));
    }

    /// Live Rekor submission test. Disabled by default; enable with the
    /// `CORTEX_REKOR_LIVE=1` env var. Pollutes the public Rekor log and
    /// requires network reachability, so it must never run on default CI.
    #[test]
    #[ignore = "requires CORTEX_REKOR_LIVE=1; live network call against Sigstore Rekor"]
    fn submit_against_live_rekor_when_env_gated() {
        if std::env::var("CORTEX_REKOR_LIVE").ok().as_deref() != Some("1") {
            eprintln!("skipping live Rekor submission test; set CORTEX_REKOR_LIVE=1 to opt in");
            return;
        }
        let anchor = LedgerAnchor::new(Utc::now(), 1, "a".repeat(64)).expect("anchor");
        let envelope = submit(&anchor, REKOR_DEFAULT_ENDPOINT).expect("live Rekor submission");
        assert_eq!(envelope.sink, ExternalSink::Rekor);
    }
}