Skip to main content

ratify_protocol/v2/
wire.rs

1//! Delegation certificates (0x0001), proof bundles and challenge
2//! presentations (0x0002), revocation lists (0x0003) and pushes (0x0005).
3//! Mirrors Go `protocol_v2_wire.go`.
4
5use super::constraints::{validate_v2_constraint_fields, ConstraintV2, CONSTRAINT_RESOURCE_PATH};
6use super::context::V2Context;
7use super::crypto::{equal_keys, key_id_v2, sha384, valid_v2_id, verify_v2_statement, V2ObjectType};
8use super::errors::{err, plain, Classify, V2Error, V2ErrorClass, V2Result, V2SignError, V2SignResult};
9use super::json::{canonical, obj, parse_wire, JNode, CJ, JV};
10use super::limits::{
11    check_v2_wire_size, valid_v2_timestamp, MAX_DELEGATION_CERT_BYTES_V2, MAX_PROOF_BUNDLE_BYTES_V2,
12    MAX_REVOCATION_LIST_BYTES_V2, MAX_REVOCATION_LIST_REFS_V2, MAX_REVOCATION_PUSH_BYTES_V2,
13    MAX_REVOCATION_PUSH_REFS_V2, V2_MAX_DELEGATION_LIFETIME_SECONDS, V2_MAX_TIMESTAMP_SECONDS,
14};
15use super::signer::{sign_v2_statement_with_signer, signer_public_key_v2, LocalSignerV2, SignerV2};
16use crate::resource_path::{normalize_resource_path, resource_paths_nested};
17use crate::scope::{scope_wildcards, validate_scopes, vocabulary, CUSTOM_SCOPE_PREFIX};
18use crate::types::{
19    HybridPrivateKey, HybridPublicKey, HybridSignature, MAX_CONSTRAINTS_PER_CERT,
20    MAX_DELEGATION_CHAIN_DEPTH, MAX_IDENTIFIER_LENGTH_BYTES, MAX_SCOPES_PER_CERT,
21    MAX_SCOPE_LENGTH_BYTES,
22};
23
24pub(crate) const MAX_SAFE: i64 = crate::canonical::wire_int::MAX_SAFE_INTEGER;
25
26/// Delegation certificate (object code 0x0001).
27#[derive(Debug, Clone)]
28pub struct DelegationCertV2 {
29    pub version: i64,
30    pub cert_id: String,
31    pub issuer_id: String,
32    pub issuer_pub_key: HybridPublicKey,
33    pub subject_id: String,
34    pub subject_pub_key: HybridPublicKey,
35    pub scope: Vec<String>,
36    pub constraints: Vec<ConstraintV2>,
37    pub issued_at: i64,
38    pub expires_at: i64,
39    pub signature: HybridSignature,
40}
41
42/// Proof bundle carrying a challenge presentation (object code 0x0002).
43/// `None` fields encode as JSON `null`.
44#[derive(Debug, Clone)]
45pub struct ProofBundleV2 {
46    pub version: i64,
47    pub verifier_id: String,
48    pub agent_id: String,
49    pub agent_pub_key: HybridPublicKey,
50    pub delegations: Vec<DelegationCertV2>,
51    pub delegation_digest: Vec<u8>,
52    pub challenge: Vec<u8>,
53    pub challenge_at: i64,
54    pub challenge_sig: HybridSignature,
55    pub session_context: Option<Vec<u8>>,
56    pub stream_id: Option<Vec<u8>>,
57    pub stream_seq: Option<i64>,
58}
59
60/// Issuer-scoped revoked certificate reference.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct RevokedCertV2 {
63    pub cert_id: String,
64}
65
66/// Full revocation snapshot (object code 0x0003).
67#[derive(Debug, Clone)]
68pub struct RevocationListV2 {
69    pub version: i64,
70    pub issuer_id: String,
71    pub updated_at: i64,
72    pub next_update: i64,
73    pub sequence: i64,
74    pub revoked: Vec<RevokedCertV2>,
75    pub signature: HybridSignature,
76}
77
78/// Incremental revocation push (object code 0x0005).
79#[derive(Debug, Clone)]
80pub struct RevocationPushV2 {
81    pub version: i64,
82    pub issuer_id: String,
83    pub sequence: i64,
84    pub pushed_at: i64,
85    pub revoked: Vec<RevokedCertV2>,
86    pub signature: HybridSignature,
87}
88
89const DELEGATION_FIELDS: &[&str] = &[
90    "version",
91    "cert_id",
92    "issuer_id",
93    "issuer_pub_key",
94    "subject_id",
95    "subject_pub_key",
96    "scope",
97    "constraints",
98    "issued_at",
99    "expires_at",
100    "signature",
101];
102const BUNDLE_FIELDS: &[&str] = &[
103    "version",
104    "verifier_id",
105    "agent_id",
106    "agent_pub_key",
107    "delegations",
108    "delegation_digest",
109    "challenge",
110    "challenge_at",
111    "challenge_sig",
112    "session_context",
113    "stream_id",
114    "stream_seq",
115];
116const LIST_FIELDS: &[&str] = &[
117    "version",
118    "issuer_id",
119    "updated_at",
120    "next_update",
121    "sequence",
122    "revoked",
123    "signature",
124];
125const PUSH_FIELDS: &[&str] = &[
126    "version",
127    "issuer_id",
128    "sequence",
129    "pushed_at",
130    "revoked",
131    "signature",
132];
133
134// ---------------------------------------------------------------------------
135// Scopes
136
137fn is_wildcard(scope: &str) -> bool {
138    scope_wildcards().contains_key(scope)
139}
140
141/// Protocol v2 delegation scope rules (post-claim): non-empty, registered or
142/// custom, no `custom:*`, no duplicates.
143pub fn validate_scopes_v2(scopes: &[String]) -> V2Result<()> {
144    if scopes.is_empty() {
145        return plain("scope must be a non-empty array");
146    }
147    if let Some(e) = validate_scopes(scopes) {
148        return plain(e);
149    }
150    for (i, scope) in scopes.iter().enumerate() {
151        if scope == "custom:*" {
152            return plain("custom:* is not a valid scope");
153        }
154        if scopes[..i].contains(scope) {
155            return plain(format!("duplicate scope {scope:?}"));
156        }
157    }
158    Ok(())
159}
160
161/// Exactly one requestable action scope (SPEC-v2 §2.4): a registered
162/// canonical non-wildcard scope, or one exact `custom:` extension scope. A
163/// canonical wildcard, `custom:*`, the bare prefix `custom:`, an empty string,
164/// and a scope longer than `MAX_SCOPE_LENGTH_BYTES` are rejected. A custom
165/// required scope is an exact string matched by byte equality.
166pub fn validate_required_scope_v2(scope: &str) -> V2Result<()> {
167    required_scope_v2(scope).classify(V2ErrorClass::InvalidRequiredScope)
168}
169
170/// Unclassified form for decoders, which report an invalid embedded required
171/// scope as `malformed` (Go `ValidateRequiredScopeV2` inside a decoder).
172pub(crate) fn required_scope_v2(scope: &str) -> V2Result<()> {
173    if vocabulary().contains(&scope) && !is_wildcard(scope) {
174        return Ok(());
175    }
176    if scope.starts_with(CUSTOM_SCOPE_PREFIX)
177        && scope.len() > CUSTOM_SCOPE_PREFIX.len()
178        && scope != "custom:*"
179        && scope.len() <= MAX_SCOPE_LENGTH_BYTES
180    {
181        return Ok(());
182    }
183    plain("required scope must be one canonical scope or one exact custom: scope")
184}
185
186pub(crate) fn is_wildcard_scope(scope: &str) -> bool {
187    is_wildcard(scope)
188}
189
190fn constraints_cj(cs: &[ConstraintV2]) -> V2Result<CJ> {
191    Ok(CJ::Arr(cs.iter().map(ConstraintV2::to_cj).collect::<V2Result<_>>()?))
192}
193
194// ---------------------------------------------------------------------------
195// Delegation certificate
196
197fn validate_signature_lengths(sig: &HybridSignature) -> V2Result<()> {
198    if sig.ed25519.len() != 64 || sig.ml_dsa_65.len() != 3309 {
199        return plain(
200            "wire v2: signature must contain 64-byte Ed25519 and 3309-byte ML-DSA-65 components",
201        );
202    }
203    Ok(())
204}
205
206pub(crate) fn placeholder_signature() -> HybridSignature {
207    HybridSignature {
208        ed25519: vec![0; 64],
209        ml_dsa_65: vec![0; 3309],
210    }
211}
212
213pub(crate) fn validate_delegation_cert_v2(c: &DelegationCertV2) -> V2Result<()> {
214    if c.version != 2 {
215        return plain("version must be 2");
216    }
217    if !valid_v2_timestamp(c.issued_at) || !valid_v2_timestamp(c.expires_at) {
218        return plain(format!(
219            "issued_at and expires_at must be inside 0..{V2_MAX_TIMESTAMP_SECONDS}"
220        ));
221    }
222    if c.cert_id.is_empty() || c.cert_id.len() > MAX_IDENTIFIER_LENGTH_BYTES {
223        return plain("cert_id must be non-empty and within the identifier byte limit");
224    }
225    if !valid_v2_id(&c.issuer_id) || !valid_v2_id(&c.subject_id) {
226        return plain("issuer_id and subject_id must be 64 lowercase hexadecimal characters");
227    }
228    let issuer = key_id_v2(&c.issuer_pub_key).map_err(|e| e.context("issuer key"))?;
229    let subject = key_id_v2(&c.subject_pub_key).map_err(|e| e.context("subject key"))?;
230    if c.issuer_id != issuer || c.subject_id != subject {
231        return err(
232            V2ErrorClass::KeyIdMismatch,
233            "key ID does not match complete public key",
234        );
235    }
236    if c.scope.iter().any(|s| s.len() > MAX_SCOPE_LENGTH_BYTES) {
237        return plain("scope exceeds the protocol byte limit");
238    }
239    if c.scope.len() > MAX_SCOPES_PER_CERT || c.constraints.len() > MAX_CONSTRAINTS_PER_CERT {
240        return plain("scope or constraint count exceeds protocol bound");
241    }
242    for (i, constraint) in c.constraints.iter().enumerate() {
243        constraint
244            .to_cj()
245            .map_err(|e| e.context(format!("constraint {i}")))?;
246    }
247    Ok(())
248}
249
250fn cert_cj(c: &DelegationCertV2, with_signature: bool) -> V2Result<CJ> {
251    let mut fields = vec![
252        ("cert_id", CJ::s(&c.cert_id)),
253        ("constraints", constraints_cj(&c.constraints)?),
254        ("expires_at", CJ::Int(c.expires_at)),
255        ("issued_at", CJ::Int(c.issued_at)),
256        ("issuer_id", CJ::s(&c.issuer_id)),
257        ("issuer_pub_key", CJ::key(&c.issuer_pub_key)),
258        ("scope", CJ::strs(&c.scope)),
259        ("subject_id", CJ::s(&c.subject_id)),
260        ("subject_pub_key", CJ::key(&c.subject_pub_key)),
261        ("version", CJ::Int(c.version)),
262    ];
263    if with_signature {
264        fields.push(("signature", CJ::sig(&c.signature)));
265    }
266    Ok(CJ::obj(fields))
267}
268
269/// Canonical signable projection of a certificate (all fields but `signature`).
270pub fn delegation_cert_v2_signable_bytes(c: &DelegationCertV2) -> V2Result<Vec<u8>> {
271    canonical(&cert_cj(c, false)?)
272}
273
274/// Shape checks on a raw certificate that Go performs before struct decoding.
275fn precheck_cert_node(node: &JNode) -> V2Result<()> {
276    let o = obj(node)?;
277    o.require(DELEGATION_FIELDS, &[])?;
278    let constraints = match o.get("constraints").map(|n| &n.v) {
279        Some(JV::Arr(items)) => items,
280        _ => return plain("wire v2: constraints must be an array"),
281    };
282    match o.get("scope") {
283        Some(scope) => validate_v2_scope_array(scope)?,
284        None => return plain("wire v2: required field \"scope\" is missing"),
285    }
286    for (i, raw) in constraints.iter().enumerate() {
287        validate_v2_constraint_fields(raw).map_err(|e| e.context(format!("wire v2 constraint {i}")))?;
288    }
289    Ok(())
290}
291
292fn validate_v2_scope_array(node: &JNode) -> V2Result<()> {
293    let JV::Arr(items) = &node.v else {
294        return plain("wire v2: scope must be an array of strings");
295    };
296    if items.len() > MAX_SCOPES_PER_CERT {
297        return plain("wire v2: scope count exceeds protocol bound");
298    }
299    for (i, item) in items.iter().enumerate() {
300        match &item.v {
301            JV::Str(s) if s.len() <= MAX_SCOPE_LENGTH_BYTES => {}
302            _ => return plain(format!("wire v2: scope {i} must be a bounded string")),
303        }
304    }
305    Ok(())
306}
307
308fn cert_from_node(node: &JNode) -> V2Result<DelegationCertV2> {
309    let o = obj(node)?;
310    o.only(DELEGATION_FIELDS)?;
311    let mut constraints = Vec::new();
312    for c in o.array("constraints")? {
313        constraints.push(ConstraintV2::from_node(c)?);
314    }
315    Ok(DelegationCertV2 {
316        version: o.i64("version")?,
317        cert_id: o.str("cert_id")?,
318        issuer_id: o.str("issuer_id")?,
319        issuer_pub_key: o.pub_key("issuer_pub_key")?,
320        subject_id: o.str("subject_id")?,
321        subject_pub_key: o.pub_key("subject_pub_key")?,
322        scope: o.str_array("scope")?,
323        constraints,
324        issued_at: o.i64("issued_at")?,
325        expires_at: o.i64("expires_at")?,
326        signature: o.sig("signature")?,
327    })
328}
329
330/// Strictly decode one v2 delegation certificate.
331pub fn decode_delegation_cert_v2(data: &[u8]) -> V2Result<DelegationCertV2> {
332    decode_cert_inner(data).classify(V2ErrorClass::Malformed)
333}
334
335fn decode_cert_inner(data: &[u8]) -> V2Result<DelegationCertV2> {
336    check_v2_wire_size(data, "certificate", "MAX_DELEGATION_CERT_BYTES_V2", MAX_DELEGATION_CERT_BYTES_V2)?;
337    let root = parse_wire(data, &[], &[])?;
338    precheck_cert_node(&root)?;
339    let cert = cert_from_node(&root)?;
340    validate_delegation_cert_v2(&cert)?;
341    validate_signature_lengths(&cert.signature)?;
342    Ok(cert)
343}
344
345/// Canonical wire bytes of a certificate (validated, then round-trip checked).
346pub fn encode_delegation_cert_v2(c: &DelegationCertV2) -> V2Result<Vec<u8>> {
347    validate_delegation_cert_v2(c)?;
348    validate_signature_lengths(&c.signature)?;
349    let encoded = canonical(&cert_cj(c, true)?)?;
350    decode_delegation_cert_v2(&encoded)
351        .map_err(|e| e.context("invalid v2 delegation certificate"))?;
352    Ok(encoded)
353}
354
355/// Verify one certificate's structure, key-ID bindings, and issuer signature
356/// (code 0x0001) with its own issuer key. Trust is not established here.
357pub fn verify_delegation_cert_v2_signature(c: &DelegationCertV2) -> V2Result<()> {
358    validate_delegation_cert_v2(c).classify(V2ErrorClass::Malformed)?;
359    validate_signature_lengths(&c.signature).classify(V2ErrorClass::Malformed)?;
360    let signable = delegation_cert_v2_signable_bytes(c).classify(V2ErrorClass::Malformed)?;
361    verify_v2_statement(
362        V2ObjectType::DelegationCertificate,
363        &signable,
364        &c.signature,
365        &c.issuer_pub_key,
366    )
367}
368
369/// Return a signed copy of `cert` under the issuer's v2 private key. The
370/// issuer duties of [`sign_delegation_cert_v2_with_signer`] apply.
371pub fn sign_delegation_cert_v2(
372    cert: &DelegationCertV2,
373    issuer_key: &HybridPrivateKey,
374) -> V2SignResult<DelegationCertV2> {
375    sign_delegation_cert_v2_with_signer(&V2Context::background(), cert, &LocalSignerV2::new(issuer_key)?)
376}
377
378/// Sign `cert` with an external signer whose complete public key must equal
379/// the certificate issuer key.
380///
381/// The issuer duties of SPEC-v2 §5.1 and §5.2 are checked before any signer
382/// method runs: the certificate must validate, carry valid v2 scopes, have
383/// `issued_at < expires_at` and a lifetime of at most 315360000 seconds, and
384/// carry a jointly satisfiable set of `resource_path` constraints. These are
385/// issuer hygiene only; verifiers apply their own rules independently.
386pub fn sign_delegation_cert_v2_with_signer(
387    ctx: &V2Context,
388    cert: &DelegationCertV2,
389    signer: &dyn SignerV2,
390) -> V2SignResult<DelegationCertV2> {
391    validate_delegation_cert_v2(cert).classify(V2ErrorClass::Malformed)?;
392    validate_scopes_v2(cert.scope.as_slice())
393        .map_err(|e| V2SignError::IssuerDuty(format!("v2 issuer scope: {}", e.message)))?;
394    validate_delegation_issuance_v2(cert)?;
395    let issuer_pub = signer_public_key_v2(signer)?;
396    let issuer_id = key_id_v2(&issuer_pub).classify(V2ErrorClass::Malformed)?;
397    if cert.issuer_id != issuer_id || !equal_keys(&cert.issuer_pub_key, &issuer_pub) {
398        return Err(V2SignError::KeyBinding(
399            "v2 issuer key does not match certificate issuer".into(),
400        ));
401    }
402    let mut unsigned = cert.clone();
403    unsigned.signature = placeholder_signature();
404    let mut prepared = decode_delegation_cert_v2(&encode_delegation_cert_v2(&unsigned)?)?;
405    let signable = delegation_cert_v2_signable_bytes(&prepared)?;
406    prepared.signature = sign_v2_statement_with_signer(
407        ctx,
408        V2ObjectType::DelegationCertificate,
409        &signable,
410        signer,
411        &issuer_pub,
412    )?;
413    let signed = decode_delegation_cert_v2(&encode_delegation_cert_v2(&prepared)?)?;
414    verify_v2_statement(
415        V2ObjectType::DelegationCertificate,
416        &signable,
417        &signed.signature,
418        &issuer_pub,
419    )
420    .map_err(V2SignError::SignatureRejected)?;
421    Ok(signed)
422}
423
424/// Issuer duties a decoder does not enforce (Go `validateDelegationIssuanceV2`).
425pub(crate) fn validate_delegation_issuance_v2(cert: &DelegationCertV2) -> V2SignResult<()> {
426    let duty = |m: String| Err(V2SignError::IssuerDuty(m));
427    if cert.issued_at >= cert.expires_at {
428        return duty("issued_at must be earlier than expires_at".into());
429    }
430    if cert.expires_at - cert.issued_at > V2_MAX_DELEGATION_LIFETIME_SECONDS {
431        return duty(format!(
432            "delegation lifetime exceeds {V2_MAX_DELEGATION_LIFETIME_SECONDS} seconds"
433        ));
434    }
435    let mut resource_id = "";
436    let mut prefixes: Vec<&str> = Vec::new();
437    for (i, c) in cert.constraints.iter().enumerate() {
438        if c.kind != CONSTRAINT_RESOURCE_PATH {
439            continue;
440        }
441        if !c.path_prefix.is_empty() {
442            if let Err(e) = normalize_resource_path(&c.path_prefix) {
443                return duty(format!("constraint {i} path_prefix can never match: {e}"));
444            }
445        }
446        if resource_id.is_empty() {
447            resource_id = &c.resource_id;
448        } else if c.resource_id != resource_id {
449            return duty(format!(
450                "constraint {i} names a different resource_id; the resource_path set is jointly unsatisfiable"
451            ));
452        }
453        for prior in &prefixes {
454            if !resource_paths_nested(prior, &c.path_prefix) {
455                return duty(format!(
456                    "constraint {i} path_prefix {:?} does not nest with {prior:?}; the resource_path set is jointly unsatisfiable",
457                    c.path_prefix
458                ));
459            }
460        }
461        prefixes.push(&c.path_prefix);
462    }
463    Ok(())
464}
465
466// ---------------------------------------------------------------------------
467// Proof bundle
468
469fn opt_bytes_cj(v: &Option<Vec<u8>>) -> CJ {
470    v.as_ref().map_or(CJ::Null, |b| CJ::Bytes(b.clone()))
471}
472
473fn bundle_cj(b: &ProofBundleV2) -> V2Result<CJ> {
474    Ok(CJ::obj(vec![
475        ("agent_id", CJ::s(&b.agent_id)),
476        ("agent_pub_key", CJ::key(&b.agent_pub_key)),
477        ("challenge", CJ::Bytes(b.challenge.clone())),
478        ("challenge_at", CJ::Int(b.challenge_at)),
479        ("challenge_sig", CJ::sig(&b.challenge_sig)),
480        ("delegation_digest", CJ::Bytes(b.delegation_digest.clone())),
481        (
482            "delegations",
483            CJ::Arr(
484                b.delegations
485                    .iter()
486                    .map(|c| cert_cj(c, true))
487                    .collect::<V2Result<_>>()?,
488            ),
489        ),
490        ("session_context", opt_bytes_cj(&b.session_context)),
491        ("stream_id", opt_bytes_cj(&b.stream_id)),
492        ("stream_seq", b.stream_seq.map_or(CJ::Null, CJ::Int)),
493        ("verifier_id", CJ::s(&b.verifier_id)),
494        ("version", CJ::Int(b.version)),
495    ]))
496}
497
498/// Canonical challenge-presentation signable (code 0x0002): the bundle
499/// without `delegations` and `challenge_sig`.
500pub fn presentation_v2_signable_bytes(b: &ProofBundleV2) -> V2Result<Vec<u8>> {
501    canonical(&CJ::obj(vec![
502        ("agent_id", CJ::s(&b.agent_id)),
503        ("agent_pub_key", CJ::key(&b.agent_pub_key)),
504        ("challenge", CJ::Bytes(b.challenge.clone())),
505        ("challenge_at", CJ::Int(b.challenge_at)),
506        ("delegation_digest", CJ::Bytes(b.delegation_digest.clone())),
507        ("session_context", opt_bytes_cj(&b.session_context)),
508        ("stream_id", opt_bytes_cj(&b.stream_id)),
509        ("stream_seq", b.stream_seq.map_or(CJ::Null, CJ::Int)),
510        ("verifier_id", CJ::s(&b.verifier_id)),
511        ("version", CJ::Int(b.version)),
512    ]))
513}
514
515/// SHA-384("ratify-protocol-delegations-v2\0" || canonical(certs)).
516pub fn delegation_digest_v2(certs: &[DelegationCertV2]) -> V2Result<Vec<u8>> {
517    let canonical_certs = canonical(&CJ::Arr(
518        certs
519            .iter()
520            .map(|c| cert_cj(c, true))
521            .collect::<V2Result<_>>()?,
522    ))?;
523    Ok(sha384(&[
524        b"ratify-protocol-delegations-v2\0",
525        &canonical_certs,
526    ]))
527}
528
529/// "sha384:" + hex(SHA-384("ratify-protocol-bundle-v2\0" || canonical bundle)).
530pub fn bundle_hash_v2(b: &ProofBundleV2) -> V2Result<String> {
531    let encoded = encode_proof_bundle_v2(b)?;
532    Ok(bundle_hash_of_bytes(&encoded))
533}
534
535pub(crate) fn bundle_hash_of_bytes(encoded: &[u8]) -> String {
536    format!(
537        "sha384:{}",
538        hex::encode(sha384(&[b"ratify-protocol-bundle-v2\0", encoded]))
539    )
540}
541
542/// Strictly decode a v2 proof bundle.
543pub fn decode_proof_bundle_v2(data: &[u8]) -> V2Result<ProofBundleV2> {
544    decode_bundle_inner(data).classify(V2ErrorClass::Malformed)
545}
546
547fn decode_bundle_inner(data: &[u8]) -> V2Result<ProofBundleV2> {
548    check_v2_wire_size(data, "proof bundle", "MAX_PROOF_BUNDLE_BYTES_V2", MAX_PROOF_BUNDLE_BYTES_V2)?;
549    let root = parse_wire(data, &["delegation_digest"], &[])?;
550    let o = obj(&root)?;
551    o.require(
552        BUNDLE_FIELDS,
553        &["session_context", "stream_id", "stream_seq"],
554    )?;
555    let Some(JV::Arr(raw_certs)) = o.get("delegations").map(|n| &n.v) else {
556        return plain("wire v2: delegations must be an array");
557    };
558    for (i, raw) in raw_certs.iter().enumerate() {
559        precheck_cert_node(raw).map_err(|e| e.context(format!("wire v2 delegation {i}")))?;
560    }
561    o.only(BUNDLE_FIELDS)?;
562    let mut delegations = Vec::new();
563    for raw in raw_certs {
564        delegations.push(cert_from_node(raw)?);
565    }
566    let bundle = ProofBundleV2 {
567        version: o.i64("version")?,
568        verifier_id: o.str("verifier_id")?,
569        agent_id: o.str("agent_id")?,
570        agent_pub_key: o.pub_key("agent_pub_key")?,
571        delegations,
572        delegation_digest: o.bytes("delegation_digest")?,
573        challenge: o.bytes("challenge")?,
574        challenge_at: o.i64("challenge_at")?,
575        challenge_sig: o.sig("challenge_sig")?,
576        session_context: o.opt_bytes("session_context")?,
577        stream_id: o.opt_bytes("stream_id")?,
578        stream_seq: o.opt_i64("stream_seq")?,
579    };
580    if bundle.version != 2 {
581        return plain("wire v2: version must be 2");
582    }
583    if !valid_v2_id(&bundle.verifier_id) || !valid_v2_id(&bundle.agent_id) {
584        return plain(
585            "wire v2: verifier_id and agent_id must be 64 lowercase hexadecimal characters",
586        );
587    }
588    if bundle.delegations.len() > MAX_DELEGATION_CHAIN_DEPTH {
589        return plain("wire v2: delegation chain exceeds MAX_DELEGATION_CHAIN_DEPTH");
590    }
591    if bundle.challenge.len() != 32 {
592        return plain("wire v2: challenge must be 32 bytes");
593    }
594    if !valid_v2_timestamp(bundle.challenge_at) {
595        return plain(format!("wire v2: challenge_at is outside 0..{V2_MAX_TIMESTAMP_SECONDS}"));
596    }
597    if bundle.delegation_digest.len() != 48 {
598        return plain("wire v2: delegation_digest must be 48 bytes");
599    }
600    if bundle
601        .session_context
602        .as_ref()
603        .is_some_and(|s| s.len() != 32)
604    {
605        return plain("wire v2: session_context must be null or 32 bytes");
606    }
607    if bundle.stream_id.is_some() != bundle.stream_seq.is_some() {
608        return plain("wire v2: stream_id and stream_seq must both be null or both set");
609    }
610    if let (Some(id), Some(seq)) = (&bundle.stream_id, bundle.stream_seq) {
611        if id.len() != 32 || seq <= 0 {
612            return plain(
613                "wire v2: bound stream requires 32-byte stream_id and positive stream_seq",
614            );
615        }
616    }
617    validate_signature_lengths(&bundle.challenge_sig)?;
618    for (i, c) in bundle.delegations.iter().enumerate() {
619        validate_delegation_cert_v2(c).map_err(|e| e.context(format!("wire v2 delegation {i}")))?;
620        validate_signature_lengths(&c.signature)
621            .map_err(|e| e.context(format!("wire v2 delegation {i}")))?;
622    }
623    Ok(bundle)
624}
625
626/// Canonical wire bytes of a proof bundle (round-trip checked).
627pub fn encode_proof_bundle_v2(b: &ProofBundleV2) -> V2Result<Vec<u8>> {
628    let encoded = canonical(&bundle_cj(b)?)?;
629    decode_proof_bundle_v2(&encoded).map_err(|e| e.context("invalid v2 proof bundle"))?;
630    Ok(encoded)
631}
632
633/// Compute the delegation digest and sign the presentation with the agent
634/// private key. Trust in the terminal issuer is not established.
635pub fn sign_proof_bundle_v2(
636    bundle: &ProofBundleV2,
637    agent_key: &HybridPrivateKey,
638) -> V2SignResult<ProofBundleV2> {
639    sign_proof_bundle_v2_with_signer(&V2Context::background(), bundle, &LocalSignerV2::new(agent_key)?)
640}
641
642/// [`sign_proof_bundle_v2`] with an external signer whose complete public
643/// key must equal the bundle agent key.
644pub fn sign_proof_bundle_v2_with_signer(
645    ctx: &V2Context,
646    bundle: &ProofBundleV2,
647    signer: &dyn SignerV2,
648) -> V2SignResult<ProofBundleV2> {
649    let agent_pub = signer_public_key_v2(signer)?;
650    let agent_id = key_id_v2(&agent_pub).classify(V2ErrorClass::Malformed)?;
651    if bundle.agent_id != agent_id || !equal_keys(&bundle.agent_pub_key, &agent_pub) {
652        return Err(V2SignError::KeyBinding(
653            "v2 agent key does not match proof bundle agent".into(),
654        ));
655    }
656    let mut unsigned = bundle.clone();
657    unsigned.challenge_sig = placeholder_signature();
658    unsigned.delegation_digest = vec![0; 48];
659    let mut prepared = decode_proof_bundle_v2(&encode_proof_bundle_v2(&unsigned)?)?;
660    prepared.delegation_digest = delegation_digest_v2(&prepared.delegations)?;
661    let signable = presentation_v2_signable_bytes(&prepared)?;
662    prepared.challenge_sig = sign_v2_statement_with_signer(
663        ctx,
664        V2ObjectType::ChallengePresentation,
665        &signable,
666        signer,
667        &agent_pub,
668    )?;
669    let signed = decode_proof_bundle_v2(&encode_proof_bundle_v2(&prepared)?)?;
670    verify_proof_bundle_v2_signatures(&signed).map_err(V2SignError::SignatureRejected)?;
671    Ok(signed)
672}
673
674/// Structure (key IDs, digest, duplicates, linkage) first, then every
675/// certificate signature and the challenge signature. Trust is not evaluated.
676pub fn verify_proof_bundle_v2_signatures(b: &ProofBundleV2) -> V2Result<()> {
677    verify_proof_bundle_v2_structure(b)?;
678    for (i, c) in b.delegations.iter().enumerate() {
679        let signable = delegation_cert_v2_signable_bytes(c).classify(V2ErrorClass::Malformed)?;
680        verify_v2_statement(
681            V2ObjectType::DelegationCertificate,
682            &signable,
683            &c.signature,
684            &c.issuer_pub_key,
685        )
686        .map_err(|e| e.context(format!("delegation {i} signature")))?;
687    }
688    let signable = presentation_v2_signable_bytes(b).classify(V2ErrorClass::Malformed)?;
689    verify_v2_statement(
690        V2ObjectType::ChallengePresentation,
691        &signable,
692        &b.challenge_sig,
693        &b.agent_pub_key,
694    )
695}
696
697pub(crate) fn verify_proof_bundle_v2_structure(b: &ProofBundleV2) -> V2Result<()> {
698    use V2ErrorClass::*;
699    if b.version != 2 {
700        return err(Malformed, "v2 proof bundle version must be 2");
701    }
702    if b.delegations.len() > MAX_DELEGATION_CHAIN_DEPTH
703        || b.challenge.len() != 32
704        || b.delegation_digest.len() != 48
705    {
706        return err(
707            Malformed,
708            "v2 proof bundle exceeds a chain bound or has an invalid challenge/digest length",
709        );
710    }
711    if b.stream_seq.is_some_and(|s| s > MAX_SAFE) {
712        return err(
713            Malformed,
714            "v2 stream sequence exceeds the safe integer range",
715        );
716    }
717    if b.session_context.as_ref().is_some_and(|s| s.len() != 32) {
718        return err(Malformed, "v2 session_context must be null or 32 bytes");
719    }
720    let stream_ok = match (&b.stream_id, b.stream_seq) {
721        (None, None) => true,
722        (Some(id), Some(seq)) => id.len() == 32 && seq > 0,
723        _ => false,
724    };
725    if !stream_ok {
726        return err(
727            Malformed,
728            "v2 stream_id and stream_seq must both be null or a 32-byte ID and positive sequence",
729        );
730    }
731    if !valid_v2_id(&b.agent_id) || !valid_v2_id(&b.verifier_id) {
732        return err(Malformed, "v2 verifier and agent IDs must be canonical");
733    }
734    let agent_id = key_id_v2(&b.agent_pub_key).classify(Malformed)?;
735    if agent_id != b.agent_id {
736        return err(KeyIdMismatch, "agent_id does not match agent_pub_key");
737    }
738    for (i, c) in b.delegations.iter().enumerate() {
739        validate_delegation_cert_v2(c)
740            .map_err(|e| e.context(format!("delegation {i}")))
741            .classify(Malformed)?;
742    }
743    let digest = delegation_digest_v2(&b.delegations).classify(Malformed)?;
744    if digest != b.delegation_digest {
745        return err(DelegationDigestMismatch, "delegation_digest mismatch");
746    }
747    let mut seen: Vec<(&str, &str)> = Vec::new();
748    for (i, c) in b.delegations.iter().enumerate() {
749        let r = (c.issuer_id.as_str(), c.cert_id.as_str());
750        if seen.contains(&r) {
751            return err(DuplicateCertificateRef, "duplicate delegation reference");
752        }
753        seen.push(r);
754        if let Some(parent) = b.delegations.get(i + 1) {
755            if c.issuer_id != parent.subject_id
756                || !equal_keys(&c.issuer_pub_key, &parent.subject_pub_key)
757            {
758                return err(
759                    ChainLinkageMismatch,
760                    format!("delegation chain link {i} does not match parent subject"),
761                );
762            }
763        }
764    }
765    if let Some(leaf) = b.delegations.first() {
766        if leaf.subject_id != b.agent_id || !equal_keys(&leaf.subject_pub_key, &b.agent_pub_key) {
767            return err(
768                ChainLinkageMismatch,
769                "agent key does not match leaf delegation subject",
770            );
771        }
772    }
773    Ok(())
774}
775
776// ---------------------------------------------------------------------------
777// Revocation list and push
778
779fn validate_revoked(refs: &[RevokedCertV2]) -> V2Result<()> {
780    let mut seen = std::collections::HashSet::with_capacity(refs.len());
781    for r in refs {
782        if r.cert_id.is_empty() || !seen.insert(r.cert_id.as_str()) {
783            return plain("v2 revoked cert IDs must be non-empty and unique");
784        }
785        if r.cert_id.len() > MAX_IDENTIFIER_LENGTH_BYTES {
786            return plain(format!("v2 revoked cert ID exceeds {MAX_IDENTIFIER_LENGTH_BYTES} bytes"));
787        }
788    }
789    Ok(())
790}
791
792pub(crate) fn validate_revocation_list_v2(l: &RevocationListV2) -> V2Result<()> {
793    if l.version != 2
794        || !valid_v2_id(&l.issuer_id)
795        || l.sequence <= 0
796        || l.sequence > MAX_SAFE
797        || !valid_v2_timestamp(l.updated_at)
798        || !valid_v2_timestamp(l.next_update)
799        || l.next_update <= l.updated_at
800    {
801        return plain("v2 revocation list has invalid version, issuer, sequence, or time bounds");
802    }
803    if l.revoked.len() > MAX_REVOCATION_LIST_REFS_V2 {
804        return plain(format!(
805            "v2 revocation list exceeds MAX_REVOCATION_LIST_REFS_V2 ({MAX_REVOCATION_LIST_REFS_V2})"
806        ));
807    }
808    validate_revoked(&l.revoked)
809}
810
811pub(crate) fn validate_revocation_push_v2(p: &RevocationPushV2) -> V2Result<()> {
812    if p.version != 2
813        || !valid_v2_id(&p.issuer_id)
814        || p.sequence <= 0
815        || p.sequence > MAX_SAFE
816        || !valid_v2_timestamp(p.pushed_at)
817    {
818        return plain("v2 revocation push has invalid version, issuer, sequence, or timestamp");
819    }
820    if p.revoked.len() > MAX_REVOCATION_PUSH_REFS_V2 {
821        return plain(format!(
822            "v2 revocation push exceeds MAX_REVOCATION_PUSH_REFS_V2 ({MAX_REVOCATION_PUSH_REFS_V2})"
823        ));
824    }
825    validate_revoked(&p.revoked)
826}
827
828fn revoked_cj(refs: &[RevokedCertV2]) -> CJ {
829    CJ::Arr(
830        refs.iter()
831            .map(|r| CJ::obj(vec![("cert_id", CJ::s(&r.cert_id))]))
832            .collect(),
833    )
834}
835
836fn list_cj(l: &RevocationListV2, with_signature: bool) -> CJ {
837    let mut f = vec![
838        ("issuer_id", CJ::s(&l.issuer_id)),
839        ("next_update", CJ::Int(l.next_update)),
840        ("revoked", revoked_cj(&l.revoked)),
841        ("sequence", CJ::Int(l.sequence)),
842        ("updated_at", CJ::Int(l.updated_at)),
843        ("version", CJ::Int(l.version)),
844    ];
845    if with_signature {
846        f.push(("signature", CJ::sig(&l.signature)));
847    }
848    CJ::obj(f)
849}
850
851fn push_cj(p: &RevocationPushV2, with_signature: bool) -> CJ {
852    let mut f = vec![
853        ("issuer_id", CJ::s(&p.issuer_id)),
854        ("pushed_at", CJ::Int(p.pushed_at)),
855        ("revoked", revoked_cj(&p.revoked)),
856        ("sequence", CJ::Int(p.sequence)),
857        ("version", CJ::Int(p.version)),
858    ];
859    if with_signature {
860        f.push(("signature", CJ::sig(&p.signature)));
861    }
862    CJ::obj(f)
863}
864
865/// Canonical revocation-list signable (code 0x0003).
866pub fn revocation_list_v2_signable_bytes(l: &RevocationListV2) -> V2Result<Vec<u8>> {
867    validate_revocation_list_v2(l)?;
868    canonical(&list_cj(l, false))
869}
870
871/// Canonical revocation-push signable (code 0x0005).
872pub fn revocation_push_v2_signable_bytes(p: &RevocationPushV2) -> V2Result<Vec<u8>> {
873    validate_revocation_push_v2(p)?;
874    canonical(&push_cj(p, false))
875}
876
877/// Accepts exactly the bytes [`revocation_list_v2_signable_bytes`] produces
878/// for a valid list.
879pub(crate) fn validate_revocation_list_signable_body(body: &[u8]) -> V2Result<()> {
880    (|| {
881        let names = &LIST_FIELDS[..6];
882        let root = parse_wire(body, &[], &[])?;
883        let o = obj(&root)?;
884        o.require(names, &[])?;
885        o.only(names)?;
886        let l = RevocationListV2 {
887            version: o.i64("version")?,
888            issuer_id: o.str("issuer_id")?,
889            updated_at: o.i64("updated_at")?,
890            next_update: o.i64("next_update")?,
891            sequence: o.i64("sequence")?,
892            revoked: revoked_from(&o)?,
893            signature: HybridSignature {
894                ed25519: Vec::new(),
895                ml_dsa_65: Vec::new(),
896            },
897        };
898        if revocation_list_v2_signable_bytes(&l)? != body {
899            return plain("must use RatifyCanonicalJSON");
900        }
901        Ok(())
902    })()
903    .map_err(|e| e.context("revocation list signable body"))
904}
905
906/// Accepts exactly the bytes [`revocation_push_v2_signable_bytes`] produces
907/// for a valid push.
908pub(crate) fn validate_revocation_push_signable_body(body: &[u8]) -> V2Result<()> {
909    (|| {
910        let names = &PUSH_FIELDS[..5];
911        let root = parse_wire(body, &[], &[])?;
912        let o = obj(&root)?;
913        o.require(names, &[])?;
914        o.only(names)?;
915        let p = RevocationPushV2 {
916            version: o.i64("version")?,
917            issuer_id: o.str("issuer_id")?,
918            sequence: o.i64("sequence")?,
919            pushed_at: o.i64("pushed_at")?,
920            revoked: revoked_from(&o)?,
921            signature: HybridSignature {
922                ed25519: Vec::new(),
923                ml_dsa_65: Vec::new(),
924            },
925        };
926        if revocation_push_v2_signable_bytes(&p)? != body {
927            return plain("must use RatifyCanonicalJSON");
928        }
929        Ok(())
930    })()
931    .map_err(|e| e.context("revocation push signable body"))
932}
933
934fn revoked_from(o: &super::json::Obj<'_>) -> V2Result<Vec<RevokedCertV2>> {
935    o.array("revoked")?
936        .iter()
937        .map(|n| {
938            if n.is_null() {
939                return Ok(RevokedCertV2 {
940                    cert_id: String::new(),
941                });
942            }
943            let e = obj(n)?;
944            e.only(&["cert_id"])?;
945            Ok(RevokedCertV2 {
946                cert_id: e.str("cert_id")?,
947            })
948        })
949        .collect()
950}
951
952/// Strictly decode a v2 revocation list.
953pub fn decode_revocation_list_v2(data: &[u8]) -> V2Result<RevocationListV2> {
954    (|| {
955        check_v2_wire_size(data, "revocation list", "MAX_REVOCATION_LIST_BYTES_V2", MAX_REVOCATION_LIST_BYTES_V2)?;
956        let root = parse_wire(data, &[], &[])?;
957        let o = obj(&root)?;
958        o.require(LIST_FIELDS, &[])?;
959        o.only(LIST_FIELDS)?;
960        let l = RevocationListV2 {
961            version: o.i64("version")?,
962            issuer_id: o.str("issuer_id")?,
963            updated_at: o.i64("updated_at")?,
964            next_update: o.i64("next_update")?,
965            sequence: o.i64("sequence")?,
966            revoked: revoked_from(&o)?,
967            signature: o.sig("signature")?,
968        };
969        validate_revocation_list_v2(&l)?;
970        validate_signature_lengths(&l.signature)?;
971        Ok(l)
972    })()
973    .classify(V2ErrorClass::Malformed)
974}
975
976/// Strictly decode a v2 revocation push.
977pub fn decode_revocation_push_v2(data: &[u8]) -> V2Result<RevocationPushV2> {
978    (|| {
979        check_v2_wire_size(data, "revocation push", "MAX_REVOCATION_PUSH_BYTES_V2", MAX_REVOCATION_PUSH_BYTES_V2)?;
980        let root = parse_wire(data, &[], &[])?;
981        let o = obj(&root)?;
982        o.require(PUSH_FIELDS, &[])?;
983        o.only(PUSH_FIELDS)?;
984        let p = RevocationPushV2 {
985            version: o.i64("version")?,
986            issuer_id: o.str("issuer_id")?,
987            sequence: o.i64("sequence")?,
988            pushed_at: o.i64("pushed_at")?,
989            revoked: revoked_from(&o)?,
990            signature: o.sig("signature")?,
991        };
992        validate_revocation_push_v2(&p)?;
993        validate_signature_lengths(&p.signature)?;
994        Ok(p)
995    })()
996    .classify(V2ErrorClass::Malformed)
997}
998
999/// Canonical wire bytes of a revocation list.
1000pub fn encode_revocation_list_v2(l: &RevocationListV2) -> V2Result<Vec<u8>> {
1001    validate_revocation_list_v2(l)?;
1002    validate_signature_lengths(&l.signature)?;
1003    let encoded = canonical(&list_cj(l, true))?;
1004    decode_revocation_list_v2(&encoded)?;
1005    Ok(encoded)
1006}
1007
1008/// Canonical wire bytes of a revocation push.
1009pub fn encode_revocation_push_v2(p: &RevocationPushV2) -> V2Result<Vec<u8>> {
1010    validate_revocation_push_v2(p)?;
1011    validate_signature_lengths(&p.signature)?;
1012    let encoded = canonical(&push_cj(p, true))?;
1013    decode_revocation_push_v2(&encoded)?;
1014    Ok(encoded)
1015}
1016
1017/// Verify a list under the caller-authenticated status key bound to `trusted_issuer_id`.
1018pub fn verify_revocation_list_v2_signature(
1019    l: &RevocationListV2,
1020    trusted_issuer_id: &str,
1021    status_key: &HybridPublicKey,
1022) -> V2Result<()> {
1023    validate_revocation_list_v2(l).classify(V2ErrorClass::Malformed)?;
1024    if trusted_issuer_id != l.issuer_id {
1025        return err(
1026            V2ErrorClass::StatusKeyBindingMismatch,
1027            "v2 revocation list issuer does not match authenticated status-key binding",
1028        );
1029    }
1030    let signable = revocation_list_v2_signable_bytes(l)?;
1031    verify_v2_statement(
1032        V2ObjectType::RevocationList,
1033        &signable,
1034        &l.signature,
1035        status_key,
1036    )
1037}
1038
1039/// Verify a push under the caller-authenticated status key bound to `trusted_issuer_id`.
1040pub fn verify_revocation_push_v2_signature(
1041    p: &RevocationPushV2,
1042    trusted_issuer_id: &str,
1043    status_key: &HybridPublicKey,
1044) -> V2Result<()> {
1045    validate_revocation_push_v2(p).classify(V2ErrorClass::Malformed)?;
1046    if trusted_issuer_id != p.issuer_id {
1047        return err(
1048            V2ErrorClass::StatusKeyBindingMismatch,
1049            "v2 revocation push issuer does not match authenticated status-key binding",
1050        );
1051    }
1052    let signable = revocation_push_v2_signable_bytes(p)?;
1053    verify_v2_statement(
1054        V2ObjectType::RevocationPush,
1055        &signable,
1056        &p.signature,
1057        status_key,
1058    )
1059}
1060
1061fn check_status_signer(
1062    issuer_id: &str,
1063    bound_issuer_id: &str,
1064    bound_status_key: &HybridPublicKey,
1065    signer: &dyn SignerV2,
1066) -> V2SignResult<HybridPublicKey> {
1067    let binding = |m: &str| V2SignError::InvalidObject(V2Error::new(V2ErrorClass::StatusKeyBindingMismatch, m));
1068    if bound_issuer_id.is_empty() || issuer_id != bound_issuer_id {
1069        return Err(binding("status object issuer does not match caller-authenticated status-key binding"));
1070    }
1071    let derived = signer_public_key_v2(signer)?;
1072    if !equal_keys(&derived, bound_status_key) {
1073        return Err(binding("status key does not match caller-authenticated issuer status-key binding"));
1074    }
1075    Ok(derived)
1076}
1077
1078/// Return a signed copy of `list` under the caller-authenticated status key.
1079pub fn sign_revocation_list_v2(
1080    list: &RevocationListV2,
1081    bound_issuer_id: &str,
1082    bound_status_key: &HybridPublicKey,
1083    status_key: &HybridPrivateKey,
1084) -> V2SignResult<RevocationListV2> {
1085    sign_revocation_list_v2_with_signer(
1086        &V2Context::background(),
1087        list,
1088        bound_issuer_id,
1089        bound_status_key,
1090        &LocalSignerV2::new(status_key)?,
1091    )
1092}
1093
1094/// [`sign_revocation_list_v2`] with an external signer whose complete public
1095/// key must equal `bound_status_key`.
1096pub fn sign_revocation_list_v2_with_signer(
1097    ctx: &V2Context,
1098    list: &RevocationListV2,
1099    bound_issuer_id: &str,
1100    bound_status_key: &HybridPublicKey,
1101    signer: &dyn SignerV2,
1102) -> V2SignResult<RevocationListV2> {
1103    validate_revocation_list_v2(list).classify(V2ErrorClass::Malformed)?;
1104    let status_pub = check_status_signer(&list.issuer_id, bound_issuer_id, bound_status_key, signer)?;
1105    let mut prepared = list.clone();
1106    prepared.signature = placeholder_signature();
1107    let mut prepared = decode_revocation_list_v2(&encode_revocation_list_v2(&prepared)?)?;
1108    let signable = revocation_list_v2_signable_bytes(&prepared)?;
1109    prepared.signature =
1110        sign_v2_statement_with_signer(ctx, V2ObjectType::RevocationList, &signable, signer, &status_pub)?;
1111    let signed = decode_revocation_list_v2(&encode_revocation_list_v2(&prepared)?)?;
1112    verify_revocation_list_v2_signature(&signed, bound_issuer_id, bound_status_key)
1113        .map_err(V2SignError::SignatureRejected)?;
1114    Ok(signed)
1115}
1116
1117/// Return a signed copy of `push` under the caller-authenticated status key.
1118pub fn sign_revocation_push_v2(
1119    push: &RevocationPushV2,
1120    bound_issuer_id: &str,
1121    bound_status_key: &HybridPublicKey,
1122    status_key: &HybridPrivateKey,
1123) -> V2SignResult<RevocationPushV2> {
1124    sign_revocation_push_v2_with_signer(
1125        &V2Context::background(),
1126        push,
1127        bound_issuer_id,
1128        bound_status_key,
1129        &LocalSignerV2::new(status_key)?,
1130    )
1131}
1132
1133/// [`sign_revocation_push_v2`] with an external signer whose complete public
1134/// key must equal `bound_status_key`.
1135pub fn sign_revocation_push_v2_with_signer(
1136    ctx: &V2Context,
1137    push: &RevocationPushV2,
1138    bound_issuer_id: &str,
1139    bound_status_key: &HybridPublicKey,
1140    signer: &dyn SignerV2,
1141) -> V2SignResult<RevocationPushV2> {
1142    validate_revocation_push_v2(push).classify(V2ErrorClass::Malformed)?;
1143    let status_pub = check_status_signer(&push.issuer_id, bound_issuer_id, bound_status_key, signer)?;
1144    let mut prepared = push.clone();
1145    prepared.signature = placeholder_signature();
1146    let mut prepared = decode_revocation_push_v2(&encode_revocation_push_v2(&prepared)?)?;
1147    let signable = revocation_push_v2_signable_bytes(&prepared)?;
1148    prepared.signature =
1149        sign_v2_statement_with_signer(ctx, V2ObjectType::RevocationPush, &signable, signer, &status_pub)?;
1150    let signed = decode_revocation_push_v2(&encode_revocation_push_v2(&prepared)?)?;
1151    verify_revocation_push_v2_signature(&signed, bound_issuer_id, bound_status_key)
1152        .map_err(V2SignError::SignatureRejected)?;
1153    Ok(signed)
1154}
1155
1156fn status_digest(code: u16, encoded: &[u8]) -> Vec<u8> {
1157    sha384(&[
1158        b"ratify-protocol-status-evidence-v2\0",
1159        &code.to_be_bytes(),
1160        encoded,
1161    ])
1162}
1163
1164/// StatusEvidenceDigest(0x0003, list): binds audit evidence to the complete
1165/// signed canonical list. It does not establish validity or freshness.
1166pub fn status_evidence_digest_list_v2(l: &RevocationListV2) -> V2Result<Vec<u8>> {
1167    Ok(status_digest(0x0003, &encode_revocation_list_v2(l)?))
1168}
1169
1170/// StatusEvidenceDigest(0x0005, push).
1171pub fn status_evidence_digest_push_v2(p: &RevocationPushV2) -> V2Result<Vec<u8>> {
1172    Ok(status_digest(0x0005, &encode_revocation_push_v2(p)?))
1173}
1174
1175/// A complete signed status object for [`status_evidence_digest_v2`].
1176#[derive(Debug, Clone, Copy)]
1177pub enum StatusEvidenceObjectV2<'a> {
1178    List(&'a RevocationListV2),
1179    Push(&'a RevocationPushV2),
1180}
1181
1182/// Go `StatusEvidenceDigest(code, object)` under an explicit object type
1183/// code: 0x0003 requires a list and 0x0005 a push (`malformed` otherwise);
1184/// any other code is `unsupported_object_type` with no digest.
1185pub fn status_evidence_digest_v2(object_type: u16, object: StatusEvidenceObjectV2<'_>) -> V2Result<Vec<u8>> {
1186    match (object_type, object) {
1187        (0x0003, StatusEvidenceObjectV2::List(l)) => status_evidence_digest_list_v2(l),
1188        (0x0005, StatusEvidenceObjectV2::Push(p)) => status_evidence_digest_push_v2(p),
1189        (0x0003, _) => plain("status evidence type 0x0003 requires RevocationListV2"),
1190        (0x0005, _) => plain("status evidence type 0x0005 requires RevocationPushV2"),
1191        _ => err(
1192            V2ErrorClass::UnsupportedObjectType,
1193            format!("unsupported status evidence object type: {object_type:04x}"),
1194        ),
1195    }
1196}