1use 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#[derive(Debug, Clone)]
25pub struct ParsedProof {
26 pub kind: ProofKind,
28 pub claims: ProofClaims,
30 pub plan: SignaturePlan,
32 pub disposition: ProofDisposition,
35 pub protected_bytes: Vec<u8>,
38 pub payload_bytes: Vec<u8>,
40 pub structure: CoseStructure,
42 pub signatures: Vec<ParsedSignature>,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum CoseStructure {
49 Sign1,
51 Sign,
53}
54
55#[derive(Debug, Clone)]
57pub struct ParsedSignature {
58 pub alg: i64,
60 pub kid: Vec<u8>,
62 pub group_id: u64,
64 pub protected_bytes: Vec<u8>,
66 pub signature: Vec<u8>,
68}
69
70impl ParsedProof {
71 pub fn parse(cbor_bytes: &[u8]) -> Result<Self> {
85 Self::parse_with_federate_extension(cbor_bytes, false)
86 }
87
88 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 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 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 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 check_empty_unprotected(unprotected)?;
140
141 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 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 let crit_labels = get_crit(&protected_map)?;
159 validate_body_crit(&crit_labels, &protected_map)?;
160
161 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 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 let Some(ks_val) = key_set_val {
176 validate_unattributed_key_set(ks_val, &plan)?;
177 }
178
179 if kind == ProofKind::Response && disposition == ProofDisposition::Unattributed {
181 bail!("proof: response proof must not carry hs_unattributed_key_set");
182 }
183
184 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 let (structure, signatures) = if let CborValue::Array(sig_arr) = sig_or_sigs {
197 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 let sig = as_bstr(sig_or_sigs, "signature")?;
206 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_signatures_against_plan(&signatures, &plan, structure, &protected_map)?;
239
240 let claims = if allow_federate_extension {
242 ProofClaims::decode_deferred_federate(&payload_raw)?
243 } else {
244 ProofClaims::decode(&payload_raw)?
245 };
246
247 if kind == ProofKind::Response && claims.credential_hash.is_some() {
249 bail!("proof: response proof must have null credential_hash");
250 }
251
252 if kind == ProofKind::Response && claims.nonce.is_some() {
257 bail!("proof: response proof must not carry a Nonce (challenge)");
258 }
259
260 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 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 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
300fn 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 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 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 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 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 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 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 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
434pub(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 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 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 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 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 match kty {
503 1 => {
504 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 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 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 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 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 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 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 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 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
644fn 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 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}