Skip to main content

hyprstream_rpc/proof/
parser.rs

1//! Bounded COSE object parser for the proof-CWT profile.
2//!
3//! Parses an untagged COSE object (COSE_Sign1 or COSE_Sign), validates all
4//! protected headers, `crit` sets, `typ`, `hs_domain`, and the signature plan,
5//! then decodes the claims payload.
6//!
7//! This parser does **not** verify cryptographic signatures — it performs the
8//! bounded structural parse and profile-rule validation that must precede
9//! signature verification. Signature verification uses the extracted
10//! [`ParsedProof`] fields with the existing `hyprstream_crypto` COSE primitives.
11
12use anyhow::{bail, Result};
13use ciborium::value::Value as CborValue;
14
15use super::{
16    claims::ProofClaims, plan::SignaturePlan, ProofDisposition, ProofKind, ALG_ED25519,
17    ALG_ML_DSA_65, COSE_HEADER_ALG, COSE_HEADER_CRIT, COSE_HEADER_KID, COSE_HEADER_TYP,
18    HEADER_HS_DOMAIN, HEADER_HS_LOGICAL_SIGNER_GROUP, HEADER_HS_SIGNATURE_PLAN,
19    HEADER_HS_UNATTRIBUTED_KEY_SET, MAX_COSE_OBJECT_BYTES, MAX_SIGNER_GROUP_ID, PROOF_TYP,
20    REQUEST_PROOF_DOMAIN, RESPONSE_PROOF_DOMAIN, RESPONSE_PROOF_TYP,
21};
22
23/// A parsed and profile-validated proof-CWT, ready for signature verification.
24#[derive(Debug, Clone)]
25pub struct ParsedProof {
26    /// Whether this is a request or response proof.
27    pub kind: ProofKind,
28    /// The decoded claims payload.
29    pub claims: ProofClaims,
30    /// The signature plan extracted from the body protected headers.
31    pub plan: SignaturePlan,
32    /// The disposition: `Unattributed` if the proof carries
33    /// `hs_unattributed_key_set`, `Authenticated` otherwise.
34    pub disposition: ProofDisposition,
35    /// The protected header bytes (the `protected` bstr from the COSE object).
36    /// Needed to reconstruct `Sig_structure` for verification.
37    pub protected_bytes: Vec<u8>,
38    /// The payload bytes (claims-set CBOR).
39    pub payload_bytes: Vec<u8>,
40    /// COSE structure variant.
41    pub structure: CoseStructure,
42    /// Per-signature metadata extracted from the COSE object.
43    pub signatures: Vec<ParsedSignature>,
44}
45
46/// Which COSE structure the proof uses.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum CoseStructure {
49    /// Single-signer: one protected bucket, one signature.
50    Sign1,
51    /// Multi-signer: body + per-signature protected buckets.
52    Sign,
53}
54
55/// A single signature entry extracted from the COSE object.
56#[derive(Debug, Clone)]
57pub struct ParsedSignature {
58    /// The algorithm identifier from the protected header.
59    pub alg: i64,
60    /// The key ID from the protected header.
61    pub kid: Vec<u8>,
62    /// The logical signer group from the protected header (−70102).
63    pub group_id: u64,
64    /// The protected header bytes for this signature entry.
65    pub protected_bytes: Vec<u8>,
66    /// The raw signature bytes.
67    pub signature: Vec<u8>,
68}
69
70impl ParsedProof {
71    /// Parse and profile-validate a proof-CWT byte blob.
72    ///
73    /// Enforces all profile rules that can be checked before signature
74    /// verification:
75    /// - COSE object size cap (2 MiB).
76    /// - `typ` header (RFC 9596 label 16) must match exactly.
77    /// - `hs_domain` must match `typ`.
78    /// - Exact `crit` sets per structure and disposition.
79    /// - `signature_plan` present and valid.
80    /// - `hs_unattributed_key_set` present iff unattributed.
81    /// - Unprotected headers carry nothing.
82    /// - Per-signature: `alg` fully specified, `kid` present, group in plan.
83    /// - Claims payload: closed claim set, deterministic encoding.
84    pub fn parse(cbor_bytes: &[u8]) -> Result<Self> {
85        Self::parse_with_federate_extension(cbor_bytes, false)
86    }
87
88    /// Parse a request proof under the deferred Federate source extension.
89    /// This is intentionally not the generic v16 parser: callers may use it
90    /// only after establishing the deferred Federate envelope profile.
91    pub fn parse_deferred_federate_request(cbor_bytes: &[u8]) -> Result<Self> {
92        let proof = Self::parse_with_federate_extension(cbor_bytes, true)?;
93        if proof.kind != ProofKind::Request {
94            bail!("deferred Federate proof must be a request proof");
95        }
96        if proof.claims.federate_recipient_binding.is_none() {
97            bail!("deferred Federate proof requires recipient binding");
98        }
99        Ok(proof)
100    }
101
102    fn parse_with_federate_extension(
103        cbor_bytes: &[u8],
104        allow_federate_extension: bool,
105    ) -> Result<Self> {
106        if cbor_bytes.len() > MAX_COSE_OBJECT_BYTES {
107            bail!(
108                "proof: object size {} exceeds cap of {} bytes",
109                cbor_bytes.len(),
110                MAX_COSE_OBJECT_BYTES
111            );
112        }
113
114        // Raw-byte deterministic audit of the complete COSE object (finding 2).
115        super::cbor_audit::audit_deterministic(cbor_bytes)?;
116
117        let value: CborValue = ciborium::de::from_reader(&mut std::io::Cursor::new(cbor_bytes))
118            .map_err(|e| anyhow::anyhow!("proof: COSE CBOR decode failed: {e}"))?;
119
120        let arr = match &value {
121            CborValue::Array(a) => a,
122            _ => bail!("proof: expected COSE array"),
123        };
124
125        // COSE_Sign1 = [protected, unprotected, payload, signature]
126        // COSE_Sign  = [protected, unprotected, payload, signatures]
127        if arr.len() != 4 {
128            bail!("proof: expected 4-element COSE array, got {}", arr.len());
129        }
130
131        let protected_raw = as_bstr(&arr[0], "protected")?;
132        // Audit protected header bstr for deterministic encoding (finding 2).
133        super::cbor_audit::audit_deterministic(&protected_raw)?;
134        let unprotected = &arr[1];
135        let payload_raw = as_bstr(&arr[2], "payload")?;
136        let sig_or_sigs = &arr[3];
137
138        // Unprotected header MUST be empty.
139        check_empty_unprotected(unprotected)?;
140
141        // Decode protected header.
142        let protected: CborValue =
143            ciborium::de::from_reader(&mut std::io::Cursor::new(&protected_raw))
144                .map_err(|e| anyhow::anyhow!("proof: protected header CBOR decode: {e}"))?;
145        let protected_map = as_map(&protected, "protected header")?;
146
147        // Extract and validate typ + hs_domain.
148        let typ = get_text(&protected_map, COSE_HEADER_TYP, "typ")?;
149        let hs_domain = get_text(&protected_map, HEADER_HS_DOMAIN, "hs_domain")?;
150
151        let kind = match (typ.as_str(), hs_domain.as_str()) {
152            (t, d) if t == PROOF_TYP && d == REQUEST_PROOF_DOMAIN => ProofKind::Request,
153            (t, d) if t == RESPONSE_PROOF_TYP && d == RESPONSE_PROOF_DOMAIN => ProofKind::Response,
154            _ => bail!("proof: typ/hs_domain mismatch: typ={typ}, domain={hs_domain}"),
155        };
156
157        // Validate crit set.
158        let crit_labels = get_crit(&protected_map)?;
159        validate_body_crit(&crit_labels, &protected_map)?;
160
161        // Extract signature plan.
162        let plan_val = get_value(&protected_map, HEADER_HS_SIGNATURE_PLAN)
163            .ok_or_else(|| anyhow::anyhow!("proof: missing hs_signature_plan"))?;
164        let plan = SignaturePlan::decode(plan_val)?;
165
166        // Determine disposition from presence of hs_unattributed_key_set.
167        let key_set_val = get_value(&protected_map, HEADER_HS_UNATTRIBUTED_KEY_SET);
168        let disposition = if key_set_val.is_some() {
169            ProofDisposition::Unattributed
170        } else {
171            ProofDisposition::Authenticated
172        };
173
174        // If unattributed, decode and strictly validate the key set (finding 3).
175        if let Some(ks_val) = key_set_val {
176            validate_unattributed_key_set(ks_val, &plan)?;
177        }
178
179        // Response proofs MUST NOT carry an unattributed key set.
180        if kind == ProofKind::Response && disposition == ProofDisposition::Unattributed {
181            bail!("proof: response proof must not carry hs_unattributed_key_set");
182        }
183
184        // Validate alg in protected header (must be in profile).
185        if let Some(alg_val) = get_value(&protected_map, COSE_HEADER_ALG) {
186            let alg = match alg_val {
187                CborValue::Integer(i) => i128::from(*i) as i64,
188                _ => bail!("proof: alg must be integer"),
189            };
190            if alg != ALG_ED25519 && alg != ALG_ML_DSA_65 {
191                bail!("proof: alg {alg} not in profile");
192            }
193        }
194
195        // Determine COSE structure from the 4th element.
196        let (structure, signatures) = if let CborValue::Array(sig_arr) = sig_or_sigs {
197            // COSE_Sign: signatures is an array of [protected, unprotected, signature]
198            let mut sigs = Vec::with_capacity(sig_arr.len());
199            for entry in sig_arr {
200                sigs.push(parse_signature_entry(entry)?);
201            }
202            (CoseStructure::Sign, sigs)
203        } else {
204            // COSE_Sign1: 4th element is the signature bstr.
205            let sig = as_bstr(sig_or_sigs, "signature")?;
206            // For Sign1, the protected header is the merged bucket — extract
207            // per-signature metadata from it.
208            let alg = get_int_or_default(&protected_map, COSE_HEADER_ALG, 0)?;
209            let kid = match get_value(&protected_map, COSE_HEADER_KID) {
210                Some(CborValue::Bytes(b)) => b.clone(),
211                _ => bail!("proof: Sign1 missing kid in merged protected header"),
212            };
213            let group_id = match get_value(&protected_map, HEADER_HS_LOGICAL_SIGNER_GROUP) {
214                Some(CborValue::Integer(i)) if i128::from(*i) >= 0 => {
215                    let g = i128::from(*i);
216                    if g > MAX_SIGNER_GROUP_ID as i128 {
217                        bail!(
218                            "proof: Sign1 hs_logical_signer_group {g} exceeds ceiling {MAX_SIGNER_GROUP_ID}"
219                        );
220                    }
221                    g as u64
222                }
223                _ => bail!("proof: Sign1 missing hs_logical_signer_group"),
224            };
225            (
226                CoseStructure::Sign1,
227                vec![ParsedSignature {
228                    alg,
229                    kid,
230                    group_id,
231                    protected_bytes: protected_raw.clone(),
232                    signature: sig,
233                }],
234            )
235        };
236
237        // Validate that each signature entry matches exactly one plan component.
238        validate_signatures_against_plan(&signatures, &plan, structure, &protected_map)?;
239
240        // Decode claims payload.
241        let claims = if allow_federate_extension {
242            ProofClaims::decode_deferred_federate(&payload_raw)?
243        } else {
244            ProofClaims::decode(&payload_raw)?
245        };
246
247        // If this is a response proof, credential_hash must be null.
248        if kind == ProofKind::Response && claims.credential_hash.is_some() {
249            bail!("proof: response proof must have null credential_hash");
250        }
251
252        // A response proof carries no server challenge: the response overlay
253        // (Gate-2 value 2) says Nonce is always absent. A response proof
254        // presenting a Nonce denies (it is neither an unattributed request nor
255        // subject to the anti-stockpiling challenge).
256        if kind == ProofKind::Response && claims.nonce.is_some() {
257            bail!("proof: response proof must not carry a Nonce (challenge)");
258        }
259
260        // Credential hash / disposition consistency (finding: N-15).
261        // Only applies to request proofs — response proofs always have null
262        // credential_hash and never carry an unattributed key set.
263        if kind == ProofKind::Request {
264            if disposition == ProofDisposition::Authenticated && claims.credential_hash.is_none() {
265                bail!("proof: authenticated proof must have non-null credential_hash");
266            }
267            if disposition == ProofDisposition::Unattributed && claims.credential_hash.is_some() {
268                bail!("proof: unattributed proof must have null credential_hash");
269            }
270        }
271
272        // If unattributed, Nonce (challenge) is REQUIRED.
273        if disposition == ProofDisposition::Unattributed && claims.nonce.is_none() {
274            bail!("proof: unattributed proof requires server challenge (Nonce)");
275        }
276
277        Ok(Self {
278            kind,
279            claims,
280            plan,
281            disposition,
282            protected_bytes: protected_raw,
283            payload_bytes: payload_raw,
284            structure,
285            signatures,
286        })
287    }
288
289    /// Frozen CDDL §7.1 content-bound replay namespace. Labels and plan order
290    /// do not create fresh namespaces. Authenticated proofs instead use their
291    /// credential-resolved primary enrollment record.
292    pub fn unattributed_replay_thumbprint(&self) -> Option<[u8; 32]> {
293        if self.disposition != ProofDisposition::Unattributed {
294            return None;
295        }
296        super::admission::unattributed_thumbprint(&self.protected_bytes).ok()
297    }
298}
299
300// ---------------------------------------------------------------------------
301// Internal helpers
302// ---------------------------------------------------------------------------
303
304fn parse_signature_entry(v: &CborValue) -> Result<ParsedSignature> {
305    let arr = match v {
306        CborValue::Array(a) => a,
307        _ => bail!("signature entry: expected array"),
308    };
309    if arr.len() != 3 {
310        bail!("signature entry: expected 3 elements, got {}", arr.len());
311    }
312    let protected_raw = as_bstr(&arr[0], "sig protected")?;
313    // Audit per-signature protected header for deterministic encoding (finding 2).
314    super::cbor_audit::audit_deterministic(&protected_raw)?;
315    let unprotected = &arr[1];
316    let signature = as_bstr(&arr[2], "signature")?;
317
318    check_empty_unprotected(unprotected)?;
319
320    let protected: CborValue = ciborium::de::from_reader(&mut std::io::Cursor::new(&protected_raw))
321        .map_err(|e| anyhow::anyhow!("sig protected decode: {e}"))?;
322    let pmap = as_map(&protected, "sig protected")?;
323
324    // Validate crit for per-signature protected: exactly [-70102].
325    let crit = get_crit(&pmap)?;
326    validate_sig_crit(&crit)?;
327
328    let alg = match get_value(&pmap, COSE_HEADER_ALG) {
329        Some(CborValue::Integer(i)) => i128::from(*i) as i64,
330        _ => bail!("sig protected: missing alg"),
331    };
332    if alg != ALG_ED25519 && alg != ALG_ML_DSA_65 {
333        bail!("sig protected: alg {alg} not in profile");
334    }
335
336    let kid = match get_value(&pmap, COSE_HEADER_KID) {
337        Some(CborValue::Bytes(b)) => b.clone(),
338        _ => bail!("sig protected: missing kid"),
339    };
340
341    let group_id = match get_value(&pmap, HEADER_HS_LOGICAL_SIGNER_GROUP) {
342        Some(CborValue::Integer(i)) if i128::from(*i) >= 0 => {
343            let g = i128::from(*i);
344            if g > MAX_SIGNER_GROUP_ID as i128 {
345                bail!(
346                    "sig protected: hs_logical_signer_group {g} exceeds ceiling {MAX_SIGNER_GROUP_ID}"
347                );
348            }
349            g as u64
350        }
351        _ => bail!("sig protected: missing hs_logical_signer_group"),
352    };
353
354    Ok(ParsedSignature {
355        alg,
356        kid,
357        group_id,
358        protected_bytes: protected_raw,
359        signature,
360    })
361}
362
363fn validate_signatures_against_plan(
364    sigs: &[ParsedSignature],
365    plan: &SignaturePlan,
366    structure: CoseStructure,
367    body_protected: &[(&CborValue, &CborValue)],
368) -> Result<()> {
369    // Enforce strict 1:1 bijection: each signature matches exactly one plan
370    // component, and each plan component is covered by exactly one signature
371    // (finding 3).
372    let total_plan = plan.total_components();
373    if sigs.len() != total_plan {
374        bail!(
375            "proof: {} signatures but plan expects {}",
376            sigs.len(),
377            total_plan
378        );
379    }
380
381    // Track which (group_id, alg, kid) tuples have been matched.
382    let mut matched: Vec<(u64, i64, Vec<u8>)> = Vec::new();
383
384    for sig in sigs {
385        let group = plan
386            .groups
387            .iter()
388            .find(|g| g.group_id == sig.group_id)
389            .ok_or_else(|| {
390                anyhow::anyhow!("proof: signature group {} not in plan", sig.group_id)
391            })?;
392
393        // Find the unique matching component.
394        let comp = group
395            .components
396            .iter()
397            .find(|c| c.alg == sig.alg && c.kid == sig.kid)
398            .ok_or_else(|| {
399                anyhow::anyhow!(
400                    "proof: signature (alg={}, kid={}) not in plan group {}",
401                    sig.alg,
402                    hex::encode(&sig.kid),
403                    sig.group_id
404                )
405            })?;
406
407        // Check for duplicate (no two signatures match the same component).
408        let tuple = (sig.group_id, comp.alg, comp.kid.clone());
409        if matched.contains(&tuple) {
410            bail!(
411                "proof: duplicate signature for group {} component (alg={}, kid={})",
412                sig.group_id,
413                comp.alg,
414                hex::encode(&comp.kid)
415            );
416        }
417        matched.push(tuple);
418    }
419
420    // Verify every plan component was matched exactly once.
421    if matched.len() != total_plan {
422        bail!(
423            "proof: {}/{} plan components matched by signatures",
424            matched.len(),
425            total_plan
426        );
427    }
428
429    let _ = structure;
430    let _ = body_protected;
431    Ok(())
432}
433
434/// Strictly validate an unattributed `COSE_KeySet` against the plan.
435///
436/// Every element must parse, be understood, match exactly one plan component
437/// by kid, algorithm, key type, and curve/parameters, in the plan's component
438/// order. Private key material is forbidden. A malformed, unknown, duplicate,
439/// surplus, reordered, or mismatched key denies the complete proof (finding 3).
440pub(super) fn validate_unattributed_key_set(
441    ks_val: &CborValue,
442    plan: &SignaturePlan,
443) -> Result<()> {
444    let arr = match ks_val {
445        CborValue::Array(a) => a,
446        _ => bail!("proof: hs_unattributed_key_set must be array"),
447    };
448
449    if arr.is_empty() {
450        bail!("proof: unattributed key set must not be empty");
451    }
452    if arr.len() > 2 {
453        bail!("proof: unattributed key set must have at most 2 elements");
454    }
455
456    // The unattributed proof MUST have exactly one logical signer group.
457    if plan.groups.len() != 1 {
458        bail!(
459            "proof: unattributed proof must have exactly one signer group, got {}",
460            plan.groups.len()
461        );
462    }
463
464    let group = &plan.groups[0];
465    if arr.len() != group.components.len() {
466        bail!(
467            "proof: key set has {} elements but plan group has {} components",
468            arr.len(),
469            group.components.len()
470        );
471    }
472
473    // Match each key to exactly one plan component by kid + alg, in order.
474    let mut matched_components = vec![false; group.components.len()];
475
476    for key_val in arr {
477        let key_map_inner = match key_val {
478            CborValue::Map(m) => m,
479            _ => bail!("proof: key-set element must be a map"),
480        };
481        let key_map: Vec<(&CborValue, &CborValue)> =
482            key_map_inner.iter().map(|(k, v)| (k, v)).collect();
483
484        // Extract kty, kid, alg.
485        let kty = get_int_from_map(&key_map, 1, "kty")?;
486        let kid = match get_value_from_map(&key_map, 2) {
487            Some(CborValue::Bytes(b)) => b.clone(),
488            _ => bail!("proof: key-set element missing kid"),
489        };
490        let alg = get_int_from_map(&key_map, 3, "alg")?;
491
492        // Reject private key material.
493        // OKP: key -4 is the private key. AKP: key -2 is the private key.
494        if kty == 1 && get_value_from_map(&key_map, -4).is_some() {
495            bail!("proof: private key material in unattributed key set");
496        }
497        if kty == 7 && get_value_from_map(&key_map, -2).is_some() {
498            bail!("proof: private key material in unattributed key set");
499        }
500
501        // Validate key structure per type.
502        match kty {
503            1 => {
504                // OKP / Ed25519
505                let crv = get_int_from_map(&key_map, -1, "crv")?;
506                if crv != 6 {
507                    bail!("proof: key-set OKP crv must be Ed25519 (6), got {crv}");
508                }
509                match get_value_from_map(&key_map, -2) {
510                    Some(CborValue::Bytes(x)) if x.len() == 32 => {}
511                    _ => bail!("proof: key-set OKP x must be 32 bytes"),
512                }
513                if alg != ALG_ED25519 {
514                    bail!("proof: key-set OKP alg must be Ed25519 ({ALG_ED25519})");
515                }
516            }
517            7 => {
518                // AKP / ML-DSA-65 (RFC 9964)
519                match get_value_from_map(&key_map, -1) {
520                    Some(CborValue::Bytes(pub_key)) if pub_key.len() == 1952 => {}
521                    _ => bail!("proof: key-set AKP pub must be 1952 bytes"),
522                }
523                if alg != ALG_ML_DSA_65 {
524                    bail!("proof: key-set AKP alg must be ML-DSA-65 ({ALG_ML_DSA_65})");
525                }
526            }
527            _ => bail!("proof: key-set element kty {kty} not in profile (OKP=1, AKP=7)"),
528        }
529
530        // Match to exactly one plan component.
531        let comp_idx = group
532            .components
533            .iter()
534            .position(|c| c.alg == alg && c.kid == kid);
535        match comp_idx {
536            Some(idx) => {
537                if matched_components[idx] {
538                    bail!("proof: duplicate key-set element for component {idx}");
539                }
540                matched_components[idx] = true;
541            }
542            None => bail!(
543                "proof: key-set element (alg={alg}, kid={}) has no matching plan component",
544                hex::encode(&kid)
545            ),
546        }
547    }
548
549    // Every plan component must be matched.
550    if !matched_components.iter().all(|&m| m) {
551        bail!("proof: not all plan components matched by key-set elements");
552    }
553
554    Ok(())
555}
556
557fn get_int_from_map(map: &[(&CborValue, &CborValue)], label: i64, name: &str) -> Result<i64> {
558    match get_value_from_map(map, label) {
559        Some(CborValue::Integer(i)) => Ok(i128::from(*i)
560            .try_into()
561            .map_err(|_| anyhow::anyhow!("proof: {name} (label {label}) out of i64 range"))?),
562        Some(_) => bail!("proof: {name} (label {label}) must be integer"),
563        None => bail!("proof: key-set element missing {name} (label {label})"),
564    }
565}
566
567fn get_value_from_map<'a>(
568    map: &[(&'a CborValue, &'a CborValue)],
569    label: i64,
570) -> Option<&'a CborValue> {
571    map.iter()
572        .find(|(k, _)| matches!(k, CborValue::Integer(i) if i128::from(*i) == label as i128))
573        .map(|(_, v)| *v)
574}
575
576fn validate_body_crit(crit: &[i64], protected: &[(&CborValue, &CborValue)]) -> Result<()> {
577    // Exact crit set per the CDDL:
578    // COSE_Sign body authenticated:  [-70101, -70100]
579    // COSE_Sign body unattributed:   [-70103, -70101, -70100]
580    // COSE_Sign1 merged authenticated: [-70102, -70101, -70100]
581    // COSE_Sign1 merged unattributed:  [-70103, -70102, -70101, -70100]
582    //
583    // We determine the expected set from what's actually present. Since the
584    // same parser handles both structures, we check that the crit set exactly
585    // matches the set of hs_* labels present in this bucket, and that those
586    // labels are all in crit.
587
588    let has_key_set = protected
589        .iter()
590        .any(|(k, _)| matches!(k, CborValue::Integer(i) if i128::from(*i) as i64 == HEADER_HS_UNATTRIBUTED_KEY_SET));
591    let has_group = protected
592        .iter()
593        .any(|(k, _)| matches!(k, CborValue::Integer(i) if i128::from(*i) as i64 == HEADER_HS_LOGICAL_SIGNER_GROUP));
594
595    // Build expected crit set.
596    let mut expected = vec![HEADER_HS_SIGNATURE_PLAN, HEADER_HS_DOMAIN];
597    if has_key_set {
598        expected.insert(0, HEADER_HS_UNATTRIBUTED_KEY_SET);
599    }
600    if has_group {
601        // In Sign1, the group label is in the merged bucket.
602        let pos = if has_key_set { 2 } else { 1 };
603        expected.insert(pos, HEADER_HS_LOGICAL_SIGNER_GROUP);
604    }
605    expected.sort();
606
607    let mut actual: Vec<i64> = crit.to_vec();
608    actual.sort();
609
610    if actual != expected {
611        bail!(
612            "proof: body crit set {:?} does not match expected {:?}",
613            actual,
614            expected
615        );
616    }
617
618    // Every crit label must occur in this same protected bucket.
619    for label in &expected {
620        let present = protected
621            .iter()
622            .any(|(k, _)| matches!(k, CborValue::Integer(i) if i128::from(*i) as i64 == *label));
623        if !present {
624            bail!("proof: crit label {label} not in same protected bucket");
625        }
626    }
627
628    Ok(())
629}
630
631fn validate_sig_crit(crit: &[i64]) -> Result<()> {
632    // Per-signature protected crit: exactly [-70102].
633    let expected = vec![HEADER_HS_LOGICAL_SIGNER_GROUP];
634    if crit != expected {
635        bail!(
636            "proof: sig crit {:?} does not match expected {:?}",
637            crit,
638            expected
639        );
640    }
641    Ok(())
642}
643
644// ---------------------------------------------------------------------------
645// CBOR map helpers
646// ---------------------------------------------------------------------------
647
648fn as_bstr(v: &CborValue, name: &str) -> Result<Vec<u8>> {
649    match v {
650        CborValue::Bytes(b) => Ok(b.clone()),
651        _ => bail!("{name}: expected bstr"),
652    }
653}
654
655fn as_map<'a>(v: &'a CborValue, name: &str) -> Result<Vec<(&'a CborValue, &'a CborValue)>> {
656    match v {
657        CborValue::Map(m) => Ok(m.iter().map(|(k, v)| (k, v)).collect()),
658        _ => bail!("{name}: expected map"),
659    }
660}
661
662fn check_empty_unprotected(v: &CborValue) -> Result<()> {
663    match v {
664        CborValue::Map(m) if m.is_empty() => Ok(()),
665        CborValue::Map(_) => bail!("proof: unprotected header must be empty"),
666        _ => bail!("proof: unprotected header must be empty map"),
667    }
668}
669
670fn get_text(map: &[(&CborValue, &CborValue)], label: i64, name: &str) -> Result<String> {
671    match get_value(map, label) {
672        Some(CborValue::Text(s)) => Ok(s.clone()),
673        Some(_) => bail!("{name}: must be text"),
674        None => bail!("{name}: missing (label {label})"),
675    }
676}
677
678fn get_value<'a>(map: &[(&'a CborValue, &'a CborValue)], label: i64) -> Option<&'a CborValue> {
679    map.iter()
680        .find(|(k, _)| matches!(k, CborValue::Integer(i) if i128::from(*i) as i64 == label))
681        .map(|(_, v)| *v)
682}
683
684fn get_crit(map: &[(&CborValue, &CborValue)]) -> Result<Vec<i64>> {
685    match get_value(map, COSE_HEADER_CRIT) {
686        Some(CborValue::Array(arr)) => {
687            let mut out = Vec::with_capacity(arr.len());
688            for elem in arr {
689                match elem {
690                    CborValue::Integer(i) => out.push(i128::from(*i) as i64),
691                    _ => bail!("crit: non-integer label"),
692                }
693            }
694            // Check ascending and unique.
695            for w in out.windows(2) {
696                if w[0] >= w[1] {
697                    bail!("crit: labels must be strictly ascending and unique");
698                }
699            }
700            Ok(out)
701        }
702        Some(_) => bail!("crit: must be array"),
703        None => bail!("crit: missing"),
704    }
705}
706
707fn get_int_or_default(map: &[(&CborValue, &CborValue)], label: i64, default: i64) -> Result<i64> {
708    match get_value(map, label) {
709        Some(CborValue::Integer(i)) => Ok(i128::from(*i) as i64),
710        Some(_) => bail!("label {label}: must be integer"),
711        None => Ok(default),
712    }
713}