Skip to main content

ratify_protocol/v2/
receipt.rs

1//! Verification receipts (object code 0x0008), the prepared receipt body,
2//! receipt-log verification, and receipt/bundle binding. Mirrors Go
3//! `verification_receipt_v2.go` and `verification_receipt_body_v2.go`.
4
5use std::collections::BTreeMap;
6
7use super::context::V2Context;
8use super::crypto::{key_id_v2, valid_prefixed_digest, valid_v2_id, verify_v2_statement, V2ObjectType};
9use super::errors::{err, plain, Classify, V2ErrorClass, V2Result, V2SignError, V2SignResult};
10use super::evaluator::{evaluator_refs_cj, valid_constraint_evaluator_refs_v2, ConstraintEvaluatorRefV2};
11use super::limits::{
12    check_v2_wire_size, valid_v2_timestamp, MAX_VERIFICATION_RECEIPT_BODY_BYTES_V2,
13    MAX_VERIFICATION_RECEIPT_BYTES_V2,
14};
15use super::signer::{sign_v2_statement_with_signer, signer_public_key_v2, LocalSignerV2, SignerV2};
16use super::json::{canonical, obj, parse_wire, Obj, CJ};
17use super::rotation::{statement_body_digest_v2, WitnessEntryV2Result};
18use super::wire::{
19    bundle_hash_v2, encode_proof_bundle_v2, is_wildcard_scope, placeholder_signature,
20    required_scope_v2, validate_scopes_v2, ProofBundleV2, MAX_SAFE,
21};
22use super::witness::{log_position, validate_head};
23use crate::types::{HybridPrivateKey, HybridPublicKey, HybridSignature};
24
25/// Authenticated status evidence reference (issuer-scoped).
26#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
27pub struct StatusEvidenceEntryV2 {
28    pub issuer_id: String,
29    pub status_key_id: String,
30    pub sequence: i64,
31    pub object_type: u16,
32    pub digest: String,
33}
34
35/// Verifier-signed terminal assertion.
36#[derive(Debug, Clone, PartialEq)]
37pub struct VerificationReceiptV2 {
38    pub version: i64,
39    pub log_id: String,
40    pub sequence: i64,
41    pub verifier_id: String,
42    /// Empty means absent (omitted on the wire).
43    pub agent_id: String,
44    /// Empty means absent (omitted on the wire).
45    pub human_id: String,
46    pub bundle_hash: String,
47    pub issuer_ids: Vec<String>,
48    pub decision: String,
49    pub decision_reason: String,
50    pub identity_status: String,
51    pub trust_assessment: String,
52    pub status_assessment: String,
53    pub challenge_assessment: String,
54    /// Present (non-empty) exactly when the claim sealed at least one
55    /// extension evaluator profile (SPEC-v2 §5.2, §5.8).
56    pub constraint_evaluators: Vec<ConstraintEvaluatorRefV2>,
57    pub context_assessment: String,
58    pub context_policy_digest: Option<String>,
59    pub verified_at: i64,
60    pub required_scope: String,
61    pub granted_scope: Vec<String>,
62    pub status_evidence: Vec<StatusEvidenceEntryV2>,
63    pub previous_receipt_hash: Vec<u8>,
64    pub signature: HybridSignature,
65}
66
67/// Caller-authenticated receipt-log state before a candidate receipt.
68#[derive(Debug, Clone, Default)]
69pub struct ReceiptV2Head {
70    pub log_id: String,
71    pub verifier_id: String,
72    pub sequence: i64,
73    pub head_hash: Vec<u8>,
74    pub accepted_digests: BTreeMap<i64, Vec<u8>>,
75    pub frozen: bool,
76}
77
78const FIELDS: &[&str] = &[
79    "version",
80    "log_id",
81    "sequence",
82    "verifier_id",
83    "bundle_hash",
84    "issuer_ids",
85    "decision",
86    "decision_reason",
87    "identity_status",
88    "trust_assessment",
89    "status_assessment",
90    "challenge_assessment",
91    "context_assessment",
92    "context_policy_digest",
93    "verified_at",
94    "required_scope",
95    "granted_scope",
96    "status_evidence_digests",
97    "previous_receipt_hash",
98    "signature",
99];
100const BODY_REQUIRED: &[&str] = &[
101    "version",
102    "verifier_id",
103    "bundle_hash",
104    "issuer_ids",
105    "decision",
106    "decision_reason",
107    "identity_status",
108    "trust_assessment",
109    "status_assessment",
110    "challenge_assessment",
111    "context_assessment",
112    "context_policy_digest",
113    "verified_at",
114    "required_scope",
115    "granted_scope",
116    "status_evidence_digests",
117];
118
119pub(crate) fn evidence_cj(values: &[StatusEvidenceEntryV2]) -> CJ {
120    CJ::Arr(
121        values
122            .iter()
123            .map(|e| {
124                CJ::obj(vec![
125                    ("digest", CJ::s(&e.digest)),
126                    ("issuer_id", CJ::s(&e.issuer_id)),
127                    ("object_type_code", CJ::Int(e.object_type as i64)),
128                    ("sequence", CJ::Int(e.sequence)),
129                    ("status_key_id", CJ::s(&e.status_key_id)),
130                ])
131            })
132            .collect(),
133    )
134}
135
136#[derive(Clone, Copy, PartialEq)]
137enum Shape {
138    Body,
139    Signable,
140    Wire,
141}
142
143fn receipt_cj(r: &VerificationReceiptV2, shape: Shape) -> CJ {
144    let mut f = vec![
145        ("bundle_hash", CJ::s(&r.bundle_hash)),
146        ("challenge_assessment", CJ::s(&r.challenge_assessment)),
147        ("context_assessment", CJ::s(&r.context_assessment)),
148        (
149            "context_policy_digest",
150            r.context_policy_digest.as_deref().map_or(CJ::Null, CJ::s),
151        ),
152        ("decision", CJ::s(&r.decision)),
153        ("decision_reason", CJ::s(&r.decision_reason)),
154        ("granted_scope", CJ::strs(&r.granted_scope)),
155        ("identity_status", CJ::s(&r.identity_status)),
156        ("issuer_ids", CJ::strs(&r.issuer_ids)),
157        ("required_scope", CJ::s(&r.required_scope)),
158        ("status_assessment", CJ::s(&r.status_assessment)),
159        ("status_evidence_digests", evidence_cj(&r.status_evidence)),
160        ("trust_assessment", CJ::s(&r.trust_assessment)),
161        ("verified_at", CJ::Int(r.verified_at)),
162        ("verifier_id", CJ::s(&r.verifier_id)),
163        ("version", CJ::Int(r.version)),
164    ];
165    if !r.agent_id.is_empty() {
166        f.push(("agent_id", CJ::s(&r.agent_id)));
167    }
168    if !r.human_id.is_empty() {
169        f.push(("human_id", CJ::s(&r.human_id)));
170    }
171    if !r.constraint_evaluators.is_empty() {
172        f.push(("constraint_evaluators", evaluator_refs_cj(&r.constraint_evaluators)));
173    }
174    if shape != Shape::Body {
175        f.push(("log_id", CJ::s(&r.log_id)));
176        f.push((
177            "previous_receipt_hash",
178            CJ::Bytes(r.previous_receipt_hash.clone()),
179        ));
180        f.push(("sequence", CJ::Int(r.sequence)));
181    }
182    if shape == Shape::Wire {
183        f.push(("signature", CJ::sig(&r.signature)));
184    }
185    CJ::obj(f)
186}
187
188fn sorted_unique_ids(values: &[String]) -> bool {
189    values
190        .iter()
191        .enumerate()
192        .all(|(i, v)| valid_v2_id(v) && (i == 0 || values[i - 1] < *v))
193}
194
195fn sorted_granted(values: &[String]) -> bool {
196    if values.is_empty() {
197        return true;
198    }
199    if validate_scopes_v2(values).is_err() {
200        return false;
201    }
202    values
203        .iter()
204        .enumerate()
205        .all(|(i, v)| !is_wildcard_scope(v) && (i == 0 || values[i - 1] < *v))
206}
207
208fn sorted_evidence(
209    values: &[StatusEvidenceEntryV2],
210    issuer_ids: &[String],
211    verifier_id: &str,
212    agent_id: &str,
213) -> bool {
214    let mut key_issuers: BTreeMap<&str, &str> = BTreeMap::new();
215    for (i, v) in values.iter().enumerate() {
216        if let Some(prior) = key_issuers.get(v.status_key_id.as_str()) {
217            if *prior != v.issuer_id {
218                return false;
219            }
220        }
221        key_issuers.insert(&v.status_key_id, &v.issuer_id);
222        if !issuer_ids.contains(&v.issuer_id)
223            || !valid_v2_id(&v.status_key_id)
224            || issuer_ids.contains(&v.status_key_id)
225            || v.status_key_id == verifier_id
226            || (!agent_id.is_empty() && v.status_key_id == agent_id)
227            || v.sequence <= 0
228            || v.sequence > MAX_SAFE
229            || (v.object_type != 3 && v.object_type != 5)
230            || !valid_prefixed_digest(&v.digest)
231        {
232            return false;
233        }
234        if i > 0 && compare_evidence(&values[i - 1], v) != std::cmp::Ordering::Less {
235            return false;
236        }
237    }
238    true
239}
240
241pub(crate) fn compare_evidence(
242    a: &StatusEvidenceEntryV2,
243    b: &StatusEvidenceEntryV2,
244) -> std::cmp::Ordering {
245    (
246        &a.issuer_id,
247        &a.status_key_id,
248        a.sequence,
249        a.object_type,
250        &a.digest,
251    )
252        .cmp(&(
253            &b.issuer_id,
254            &b.status_key_id,
255            b.sequence,
256            b.object_type,
257            &b.digest,
258        ))
259}
260
261pub(crate) fn has_accepted_status_history_per_issuer(
262    evidence: &[StatusEvidenceEntryV2],
263    issuer_ids: &[String],
264) -> bool {
265    for issuer in issuer_ids {
266        let mut base = 0i64;
267        let mut key = "";
268        let mut pushes: Vec<i64> = Vec::new();
269        for e in evidence.iter().filter(|e| &e.issuer_id == issuer) {
270            if key.is_empty() {
271                key = &e.status_key_id;
272            } else if key != e.status_key_id {
273                return false;
274            }
275            if e.object_type == 3 {
276                if base != 0 {
277                    return false;
278                }
279                base = e.sequence;
280            } else {
281                if pushes.contains(&e.sequence) {
282                    return false;
283                }
284                pushes.push(e.sequence);
285            }
286        }
287        if base == 0 || pushes.iter().any(|s| *s <= base) {
288            return false;
289        }
290        for s in base + 1..=base + pushes.len() as i64 {
291            if !pushes.contains(&s) {
292                return false;
293            }
294        }
295    }
296    !issuer_ids.is_empty()
297}
298
299pub(crate) fn validate_receipt(r: &VerificationReceiptV2, signature: bool) -> V2Result<()> {
300    if r.version != 2
301        || r.log_id.len() != 32
302        || !super::crypto::lower_hex(&r.log_id)
303        || r.sequence <= 0
304        || r.sequence > MAX_SAFE
305        || !valid_v2_timestamp(r.verified_at)
306    {
307        return plain("wire v2: receipt version, log ID, sequence, or verified_at is invalid");
308    }
309    if !valid_v2_id(&r.verifier_id) || (!r.agent_id.is_empty() && !valid_v2_id(&r.agent_id)) {
310        return plain("wire v2: receipt verifier_id and optional agent_id must be v2 key IDs");
311    }
312    if !valid_prefixed_digest(&r.bundle_hash) || r.previous_receipt_hash.len() != 48 {
313        return plain("wire v2: receipt bundle hash or previous receipt hash is invalid");
314    }
315    if !sorted_unique_ids(&r.issuer_ids) {
316        return plain("wire v2: receipt arrays must be present and canonical");
317    }
318    let reason = r.decision_reason.as_str();
319    if reason != "not_delegated" && reason != "evaluation_interrupted" && r.issuer_ids.is_empty() {
320        return plain(
321            "wire v2: a receipt for a delegated decision must identify its certificate issuers",
322        );
323    }
324    if reason == "evaluation_interrupted"
325        && r.issuer_ids.is_empty()
326        && (r.trust_assessment != "not_evaluated"
327            || r.status_assessment != "not_evaluated"
328            || r.context_assessment != "not_evaluated"
329            || !r.status_evidence.is_empty())
330    {
331        return plain("wire v2: interrupted empty-chain receipt cannot claim completed trust, status, or context checks");
332    }
333    required_scope_v2(&r.required_scope).map_err(|e| e.context("wire v2"))?;
334    let zero = r.previous_receipt_hash.iter().all(|b| *b == 0);
335    if (r.sequence == 1 && !zero) || (r.sequence > 1 && zero) {
336        return plain("wire v2: previous_receipt_hash is inconsistent with receipt sequence");
337    }
338    if !sorted_granted(&r.granted_scope) {
339        return plain("wire v2: granted_scope must be sorted, unique canonical scopes");
340    }
341    if !sorted_evidence(
342        &r.status_evidence,
343        &r.issuer_ids,
344        &r.verifier_id,
345        &r.agent_id,
346    ) {
347        return plain("wire v2: status evidence is invalid, duplicated, or not canonically sorted");
348    }
349    let sa = r.status_assessment.as_str();
350    let ca = r.context_assessment.as_str();
351    if matches!(sa, "current" | "revoked" | "stale") && r.status_evidence.is_empty() {
352        return plain("wire v2: evaluated status requires authenticated evidence");
353    }
354    if r.context_policy_digest
355        .as_deref()
356        .is_some_and(|d| !valid_prefixed_digest(d))
357    {
358        return plain("wire v2: context_policy_digest is invalid");
359    }
360    if !valid_constraint_evaluator_refs_v2(&r.constraint_evaluators)
361        || (!r.constraint_evaluators.is_empty() && r.issuer_ids.is_empty())
362    {
363        return plain("wire v2: constraint_evaluators must be valid extension types with sha384 profile digests, sorted and unique by type, and only for a delegated chain");
364    }
365    if (matches!(ca, "not_evaluated" | "unbound") && r.context_policy_digest.is_some())
366        || (matches!(ca, "bound" | "not_required" | "mismatch")
367            && r.context_policy_digest.is_none())
368    {
369        return plain("wire v2: context_policy_digest does not match context_assessment");
370    }
371    if sa == "not_evaluated" && !r.status_evidence.is_empty() {
372        return plain("wire v2: status evidence cannot be present when status was not evaluated");
373    }
374    if matches!(sa, "current" | "stale")
375        && !has_accepted_status_history_per_issuer(&r.status_evidence, &r.issuer_ids)
376    {
377        return plain("wire v2: current or stale status requires one accepted full-list base and contiguous pushes for every issuer");
378    }
379    if r.challenge_assessment != "current" {
380        return plain("wire v2: terminal receipt challenge_assessment must be current");
381    }
382    validate_decision(r)?;
383    if signature && (r.signature.ed25519.len() != 64 || r.signature.ml_dsa_65.len() != 3309) {
384        return plain(
385            "wire v2: signature must contain 64-byte Ed25519 and 3309-byte ML-DSA-65 components",
386        );
387    }
388    Ok(())
389}
390
391fn valid_deny_pair(reason: &str, status: &str) -> bool {
392    let expected = match reason {
393        "not_delegated" | "delegation_not_authorized" => "delegation_not_authorized",
394        "delegation_expired" => "expired",
395        "delegation_revoked" => "revoked",
396        "scope_denied" => "scope_denied",
397        "invalid_scope" => "invalid_scope",
398        "constraint_denied" => "constraint_denied",
399        "constraint_unverifiable" => "constraint_unverifiable",
400        "constraint_unknown" => "constraint_unknown",
401        "proof_invalid" => "invalid",
402        "unauthorized" => "unauthorized",
403        _ => return false,
404    };
405    expected == status
406}
407
408fn validate_decision(r: &VerificationReceiptV2) -> V2Result<()> {
409    const REASONS: &[&str] = &[
410        "authorized",
411        "not_delegated",
412        "delegation_not_authorized",
413        "delegation_expired",
414        "delegation_revoked",
415        "scope_denied",
416        "constraint_denied",
417        "constraint_unverifiable",
418        "constraint_unknown",
419        "invalid_scope",
420        "proof_invalid",
421        "unauthorized",
422        "status_stale",
423        "status_unavailable",
424        "action_context_unverified",
425        "trust_unavailable",
426        "evaluation_interrupted",
427    ];
428    let reason = r.decision_reason.as_str();
429    let ta = r.trust_assessment.as_str();
430    let sa = r.status_assessment.as_str();
431    let ca = r.context_assessment.as_str();
432    if !REASONS.contains(&reason) {
433        return plain("wire v2: receipt decision_reason is invalid");
434    }
435    if !matches!(
436        ta,
437        "trusted" | "untrusted" | "unavailable" | "not_evaluated"
438    ) {
439        return plain("wire v2: receipt trust_assessment is invalid");
440    }
441    if !matches!(
442        sa,
443        "current" | "revoked" | "stale" | "unavailable" | "not_evaluated"
444    ) {
445        return plain("wire v2: receipt status_assessment is invalid");
446    }
447    if !matches!(
448        ca,
449        "bound" | "not_required" | "unbound" | "unverified" | "mismatch" | "not_evaluated"
450    ) {
451        return plain("wire v2: receipt context_assessment is invalid");
452    }
453    let local = matches!(
454        reason,
455        "scope_denied" | "constraint_denied" | "constraint_unverifiable" | "constraint_unknown"
456    );
457    let constraint = matches!(
458        reason,
459        "constraint_denied" | "constraint_unverifiable" | "constraint_unknown"
460    );
461    if r.decision == "allow" {
462        if reason != "authorized"
463            || r.identity_status != "authorized_agent"
464            || ta != "trusted"
465            || sa != "current"
466            || r.status_evidence.is_empty()
467            || r.granted_scope.is_empty()
468            || !r.granted_scope.contains(&r.required_scope)
469            || (ca != "bound" && ca != "not_required")
470            || r.context_policy_digest.is_none()
471        {
472            return plain("wire v2: allow receipt violates authorization, status, context, or scope requirements");
473        }
474        return Ok(());
475    }
476    if r.decision == "deny" {
477        if !r.granted_scope.is_empty() || !valid_deny_pair(reason, &r.identity_status) {
478            return plain(
479                "wire v2: deny receipt has an invalid reason/status pair or granted scope",
480            );
481        }
482        if reason == "not_delegated" && !r.issuer_ids.is_empty() {
483            return plain("wire v2: not_delegated receipt cannot contain certificate issuers");
484        }
485        if local && sa != "current" {
486            return plain("wire v2: post-status local policy denial requires current status");
487        }
488        if (reason == "unauthorized" && ta != "untrusted")
489            || (reason == "not_delegated" && ta != "not_evaluated")
490            || (reason != "unauthorized" && reason != "not_delegated" && ta != "trusted")
491        {
492            return plain("wire v2: deny receipt trust assessment is inconsistent");
493        }
494        if (reason == "delegation_revoked" && sa != "revoked")
495            || (reason == "not_delegated" && sa != "not_evaluated")
496            || (reason != "delegation_revoked"
497                && reason != "not_delegated"
498                && sa != "not_evaluated"
499                && !(sa == "current" && local))
500        {
501            return plain("wire v2: deny receipt status assessment is inconsistent");
502        }
503        if (reason == "not_delegated" || reason == "unauthorized") && ca != "not_evaluated" {
504            return plain("wire v2: deny receipt context assessment is inconsistent");
505        }
506        if reason == "delegation_revoked" && ca == "not_evaluated" {
507            return plain(
508                "wire v2: delegation_revoked receipt must retain its completed context assessment",
509            );
510        }
511        if !matches!(
512            reason,
513            "delegation_revoked" | "not_delegated" | "unauthorized"
514        ) && !local
515            && ca != "not_evaluated"
516        {
517            return plain("wire v2: context assessment must be not_evaluated for this deny result");
518        }
519        if (reason == "scope_denied" && ca == "not_evaluated")
520            || (constraint
521                && ca != "bound"
522                && ca != "not_required"
523                && !(reason == "constraint_denied" && ca == "mismatch"))
524        {
525            return plain(
526                "wire v2: constraint denial must retain its completed context assessment",
527            );
528        }
529        if (reason == "not_delegated" || reason == "unauthorized") && !r.status_evidence.is_empty()
530        {
531            return plain("wire v2: status evidence is not evaluated for this deny result");
532        }
533        if reason == "constraint_denied"
534            && ca == "mismatch"
535            && r.identity_status != "constraint_denied"
536        {
537            return plain("wire v2: context mismatch must be a constraint denial");
538        }
539        return Ok(());
540    }
541    if r.decision != "indeterminate"
542        || !r.granted_scope.is_empty()
543        || r.identity_status != "authorization_unverified"
544    {
545        return plain("wire v2: receipt decision or indeterminate identity/scope is invalid");
546    }
547    let ok = match reason {
548        "status_stale" => ta == "trusted" && sa == "stale" && ca != "not_evaluated",
549        "status_unavailable" => ta == "trusted" && sa == "unavailable" && ca != "not_evaluated",
550        "trust_unavailable" => {
551            ta == "unavailable"
552                && sa == "not_evaluated"
553                && ca == "not_evaluated"
554                && r.status_evidence.is_empty()
555        }
556        "action_context_unverified" => {
557            ta == "trusted" && sa == "current" && (ca == "unbound" || ca == "unverified")
558        }
559        // Each dimension is independent (SPEC-v2 §6.7): trust keeps its last
560        // state; status and context exist only under a trusted root; context
561        // is recorded only when it completed as bound or not_required.
562        "evaluation_interrupted" => {
563            !((ca != "not_evaluated" && ca != "bound" && ca != "not_required")
564                || (ta != "trusted" && (sa != "not_evaluated" || ca != "not_evaluated")))
565        }
566        _ => return plain("wire v2: indeterminate reason is invalid"),
567    };
568    if !ok {
569        return plain(format!("wire v2: {reason} assessment tuple is invalid"));
570    }
571    Ok(())
572}
573
574fn evidence_from(o: &Obj<'_>) -> V2Result<Vec<StatusEvidenceEntryV2>> {
575    o.array("status_evidence_digests")?
576        .iter()
577        .map(|n| {
578            if n.is_null() {
579                return Ok(StatusEvidenceEntryV2 {
580                    issuer_id: String::new(),
581                    status_key_id: String::new(),
582                    sequence: 0,
583                    object_type: 0,
584                    digest: String::new(),
585                });
586            }
587            let e = obj(n)?;
588            e.only(&[
589                "digest",
590                "issuer_id",
591                "object_type_code",
592                "sequence",
593                "status_key_id",
594            ])?;
595            Ok(StatusEvidenceEntryV2 {
596                issuer_id: e.str("issuer_id")?,
597                status_key_id: e.str("status_key_id")?,
598                sequence: e.i64("sequence")?,
599                object_type: e.u16("object_type_code")?,
600                digest: e.str("digest")?,
601            })
602        })
603        .collect()
604}
605
606fn receipt_from(o: &Obj<'_>) -> V2Result<VerificationReceiptV2> {
607    Ok(VerificationReceiptV2 {
608        version: o.i64("version")?,
609        log_id: o.str("log_id")?,
610        sequence: o.i64("sequence")?,
611        verifier_id: o.str("verifier_id")?,
612        agent_id: o.str("agent_id")?,
613        human_id: o.str("human_id")?,
614        bundle_hash: o.str("bundle_hash")?,
615        issuer_ids: o.str_array("issuer_ids")?,
616        decision: o.str("decision")?,
617        decision_reason: o.str("decision_reason")?,
618        identity_status: o.str("identity_status")?,
619        trust_assessment: o.str("trust_assessment")?,
620        status_assessment: o.str("status_assessment")?,
621        challenge_assessment: o.str("challenge_assessment")?,
622        constraint_evaluators: evaluators_from(o)?,
623        context_assessment: o.str("context_assessment")?,
624        context_policy_digest: o.opt_str("context_policy_digest")?,
625        verified_at: o.i64("verified_at")?,
626        required_scope: o.str("required_scope")?,
627        granted_scope: o.str_array("granted_scope")?,
628        status_evidence: evidence_from(o)?,
629        previous_receipt_hash: o.bytes("previous_receipt_hash")?,
630        signature: o.sig("signature")?,
631    })
632}
633
634fn evaluators_from(o: &Obj<'_>) -> V2Result<Vec<ConstraintEvaluatorRefV2>> {
635    o.array("constraint_evaluators")?
636        .iter()
637        .map(|n| {
638            let e = obj(n)?;
639            e.only(&["profile_digest", "type"])?;
640            Ok(ConstraintEvaluatorRefV2 {
641                kind: e.str("type")?,
642                profile_digest: e.str("profile_digest")?,
643            })
644        })
645        .collect()
646}
647
648fn with_optional(names: &[&'static str]) -> Vec<&'static str> {
649    names
650        .iter()
651        .copied()
652        .chain(["agent_id", "human_id", "constraint_evaluators"])
653        .collect()
654}
655
656/// StatementBodyDigestV2(0x0008, signable body).
657pub fn verification_receipt_v2_digest(r: &VerificationReceiptV2) -> V2Result<Vec<u8>> {
658    validate_receipt(r, false)?;
659    statement_body_digest_v2(0x0008, &canonical(&receipt_cj(r, Shape::Signable))?)
660}
661
662/// Canonical signable bytes (all fields but `signature`).
663pub fn verification_receipt_v2_signable_bytes(r: &VerificationReceiptV2) -> V2Result<Vec<u8>> {
664    canonical(&receipt_cj(r, Shape::Signable))
665}
666
667pub(crate) fn validate_receipt_signable_body(data: &[u8]) -> V2Result<()> {
668    let root = parse_wire(data, &["previous_receipt_hash"], &["bundle_hash"])?;
669    let o = obj(&root)?;
670    o.require(&FIELDS[..FIELDS.len() - 1], &["context_policy_digest"])?;
671    if o.get("signature").is_some() {
672        return plain("signable body must exclude signature");
673    }
674    o.only(&with_optional(&FIELDS[..FIELDS.len() - 1]))?;
675    let r = receipt_from(&o)?;
676    validate_receipt(&r, false)?;
677    if canonical(&receipt_cj(&r, Shape::Signable))? != data {
678        return plain("signable body must use RatifyCanonicalJSON");
679    }
680    Ok(())
681}
682
683/// Canonical wire bytes.
684pub fn encode_verification_receipt_v2(r: &VerificationReceiptV2) -> V2Result<Vec<u8>> {
685    validate_receipt(r, true)?;
686    let data = canonical(&receipt_cj(r, Shape::Wire))?;
687    check_v2_wire_size(
688        &data,
689        "verification receipt",
690        "MAX_VERIFICATION_RECEIPT_BYTES_V2",
691        MAX_VERIFICATION_RECEIPT_BYTES_V2,
692    )?;
693    Ok(data)
694}
695
696/// Strictly decode a canonical v2 verification receipt.
697pub fn decode_verification_receipt_v2(data: &[u8]) -> V2Result<VerificationReceiptV2> {
698    (|| {
699        check_v2_wire_size(
700            data,
701            "verification receipt",
702            "MAX_VERIFICATION_RECEIPT_BYTES_V2",
703            MAX_VERIFICATION_RECEIPT_BYTES_V2,
704        )?;
705        let root = parse_wire(data, &["previous_receipt_hash"], &["bundle_hash"])?;
706        let o = obj(&root)?;
707        o.require(FIELDS, &["context_policy_digest"])?;
708        o.only(&with_optional(FIELDS))?;
709        let r = receipt_from(&o)?;
710        validate_receipt(&r, true)?;
711        match encode_verification_receipt_v2(&r) {
712            Ok(c) if c == data => Ok(r),
713            _ => plain("wire v2: verification receipt is not canonical Ratify JSON"),
714        }
715    })()
716    .classify(V2ErrorClass::Malformed)
717}
718
719/// Sign a receipt under code 0x0008 with the verifier key.
720pub fn sign_verification_receipt_v2(
721    r: &VerificationReceiptV2,
722    verifier_key: &HybridPrivateKey,
723) -> V2SignResult<VerificationReceiptV2> {
724    sign_verification_receipt_v2_with_signer(&V2Context::background(), r, &LocalSignerV2::new(verifier_key)?)
725}
726
727/// [`sign_verification_receipt_v2`] with an external signer whose key ID must
728/// equal `verifier_id`.
729pub fn sign_verification_receipt_v2_with_signer(
730    ctx: &V2Context,
731    r: &VerificationReceiptV2,
732    signer: &dyn SignerV2,
733) -> V2SignResult<VerificationReceiptV2> {
734    validate_receipt(r, false).classify(V2ErrorClass::Malformed)?;
735    let verifier_public = signer_public_key_v2(signer)?;
736    if key_id_v2(&verifier_public).ok().as_deref() != Some(r.verifier_id.as_str()) {
737        return Err(V2SignError::KeyBinding(
738            "receipt verifier_id does not match signing key".into(),
739        ));
740    }
741    let body = verification_receipt_v2_signable_bytes(r).classify(V2ErrorClass::Malformed)?;
742    let mut out = r.clone();
743    out.signature = sign_v2_statement_with_signer(
744        ctx,
745        V2ObjectType::VerificationReceipt,
746        &body,
747        signer,
748        &verifier_public,
749    )?;
750    encode_verification_receipt_v2(&out).classify(V2ErrorClass::Malformed)?;
751    Ok(out)
752}
753
754fn validate_receipt_head(head: &ReceiptV2Head) -> V2Result<()> {
755    if !valid_v2_id(&head.verifier_id) {
756        return err(
757            V2ErrorClass::ConfigurationInvalid,
758            "caller receipt head is invalid",
759        );
760    }
761    validate_head(
762        &head.log_id,
763        head.sequence,
764        &head.head_hash,
765        &head.accepted_digests,
766    )
767}
768
769/// Verify a receipt with a caller-supplied verifier key and log head.
770pub fn verify_verification_receipt_v2(
771    r: &VerificationReceiptV2,
772    verifier_key: &HybridPublicKey,
773    head: &ReceiptV2Head,
774) -> V2Result<WitnessEntryV2Result> {
775    validate_receipt(r, true).classify(V2ErrorClass::Malformed)?;
776    encode_verification_receipt_v2(r).classify(V2ErrorClass::Malformed)?;
777    validate_receipt_head(head)?;
778    if r.log_id != head.log_id || r.verifier_id != head.verifier_id {
779        return err(
780            V2ErrorClass::LogStateMismatch,
781            "receipt log ID or verifier identity does not match caller-authenticated state",
782        );
783    }
784    if r.verifier_id != key_id_v2(verifier_key)? {
785        return err(
786            V2ErrorClass::LogStateMismatch,
787            "receipt verifier_id does not match caller-authenticated key",
788        );
789    }
790    let body = verification_receipt_v2_signable_bytes(r)?;
791    verify_v2_statement(
792        V2ObjectType::VerificationReceipt,
793        &body,
794        &r.signature,
795        verifier_key,
796    )?;
797    let digest = verification_receipt_v2_digest(r)?;
798    log_position(
799        r.sequence,
800        &r.previous_receipt_hash,
801        &digest,
802        head.sequence,
803        &head.head_hash,
804        &head.accepted_digests,
805        head.frozen,
806        &head.log_id,
807    )
808}
809
810/// The canonical outbox body prepared before terminal commit: every field
811/// except log position, previous hash, and signature.
812pub fn verification_receipt_v2_body(r: &VerificationReceiptV2) -> V2Result<Vec<u8>> {
813    let mut candidate = r.clone();
814    candidate.log_id = "0123456789abcdef0123456789abcdef".into();
815    candidate.sequence = 1;
816    candidate.previous_receipt_hash = vec![0; 48];
817    candidate.signature = HybridSignature {
818        ed25519: Vec::new(),
819        ml_dsa_65: Vec::new(),
820    };
821    validate_receipt(&candidate, false)?;
822    candidate.sequence = MAX_SAFE;
823    candidate.previous_receipt_hash[0] = 1;
824    candidate.signature = placeholder_signature();
825    encode_verification_receipt_v2(&candidate)?;
826    canonical(&receipt_cj(r, Shape::Body))
827}
828
829/// Reject a malformed or noncanonical prepared body.
830pub fn decode_verification_receipt_body_v2(data: &[u8]) -> V2Result<VerificationReceiptV2> {
831    (|| {
832        check_v2_wire_size(
833            data,
834            "verification receipt body",
835            "MAX_VERIFICATION_RECEIPT_BODY_BYTES_V2",
836            MAX_VERIFICATION_RECEIPT_BODY_BYTES_V2,
837        )?;
838        let root = parse_wire(data, &[], &["bundle_hash"])?;
839        let o = obj(&root)?;
840        o.require(BODY_REQUIRED, &["context_policy_digest"])?;
841        o.only(&with_optional(BODY_REQUIRED))?;
842        let mut r = receipt_from(&o)?;
843        r.signature = HybridSignature {
844            ed25519: Vec::new(),
845            ml_dsa_65: Vec::new(),
846        };
847        let body = verification_receipt_v2_body(&r).map_err(|e| {
848            e.context("wire v2: verification receipt body is invalid or noncanonical")
849        })?;
850        if body != data {
851            return plain("wire v2: verification receipt body is noncanonical");
852        }
853        Ok(r)
854    })()
855    .classify(V2ErrorClass::Malformed)
856}
857
858/// Assign the next position in a caller-authenticated receipt log.
859pub fn bind_verification_receipt_body_v2(
860    data: &[u8],
861    head: &ReceiptV2Head,
862) -> V2Result<VerificationReceiptV2> {
863    validate_receipt_head(head)?;
864    if head.frozen || head.sequence == MAX_SAFE {
865        return plain("wire v2: receipt log cannot accept another entry");
866    }
867    let mut r = decode_verification_receipt_body_v2(data)?;
868    if r.verifier_id != head.verifier_id {
869        return plain("wire v2: prepared receipt verifier differs from authenticated log");
870    }
871    r.log_id = head.log_id.clone();
872    r.sequence = head.sequence + 1;
873    r.previous_receipt_hash = head.head_hash.clone();
874    validate_receipt(&r, false)?;
875    Ok(r)
876}
877
878/// Bind and sign an exact prepared body with a local verifier key.
879pub fn sign_prepared_verification_receipt_v2(
880    data: &[u8],
881    head: &ReceiptV2Head,
882    verifier_key: &HybridPrivateKey,
883) -> V2SignResult<VerificationReceiptV2> {
884    sign_prepared_verification_receipt_v2_with_signer(
885        &V2Context::background(),
886        data,
887        head,
888        &LocalSignerV2::new(verifier_key)?,
889    )
890}
891
892/// [`sign_prepared_verification_receipt_v2`] with an external verifier signer.
893pub fn sign_prepared_verification_receipt_v2_with_signer(
894    ctx: &V2Context,
895    data: &[u8],
896    head: &ReceiptV2Head,
897    signer: &dyn SignerV2,
898) -> V2SignResult<VerificationReceiptV2> {
899    let bound = bind_verification_receipt_body_v2(data, head)?;
900    let signed = sign_verification_receipt_v2_with_signer(ctx, &bound, signer)?;
901    match verification_receipt_v2_body(&signed) {
902        Ok(b) if b == data => Ok(signed),
903        _ => Err(V2SignError::InvalidObject(super::errors::V2Error::new(
904            V2ErrorClass::Malformed,
905            "wire v2: signed receipt differs from prepared body",
906        ))),
907    }
908}
909
910/// Compare a receipt with its proof bundle (hash, verifier, agent, issuers,
911/// status-key role separation). Trust and status are not re-established.
912pub fn check_verification_receipt_v2_bundle_binding(
913    r: &VerificationReceiptV2,
914    b: &ProofBundleV2,
915) -> V2Result<()> {
916    use V2ErrorClass::*;
917    validate_receipt(r, false).classify(Malformed)?;
918    encode_proof_bundle_v2(b).classify(Malformed)?;
919    if r.verifier_id != b.verifier_id || (!r.agent_id.is_empty() && r.agent_id != b.agent_id) {
920        return err(
921            ReceiptBundleMismatch,
922            "receipt verifier or agent ID does not match the proof bundle",
923        );
924    }
925    let mut roles = vec![b.verifier_id.as_str(), b.agent_id.as_str()];
926    for c in &b.delegations {
927        roles.push(&c.issuer_id);
928        roles.push(&c.subject_id);
929    }
930    if r.status_evidence
931        .iter()
932        .any(|e| roles.contains(&e.status_key_id.as_str()))
933    {
934        return err(
935            ReceiptBundleMismatch,
936            "receipt status key ID overlaps a proof or verifier key role",
937        );
938    }
939    if r.bundle_hash != bundle_hash_v2(b)? {
940        return err(
941            ReceiptBundleMismatch,
942            "receipt bundle_hash does not match the proof bundle",
943        );
944    }
945    let mut issuers: Vec<String> = b.delegations.iter().map(|c| c.issuer_id.clone()).collect();
946    issuers.sort();
947    issuers.dedup();
948    if issuers != r.issuer_ids {
949        return err(
950            ReceiptBundleMismatch,
951            "receipt issuer_ids do not match the proof bundle chain",
952        );
953    }
954    Ok(())
955}