Skip to main content

hyprstream_rpc/proof/
verify.rs

1//! COSE signature verification for proof CWTs.
2//!
3//! After the structural parser validates headers, claims, and plan topology,
4//! this module reconstructs the COSE `Sig_structure` and verifies each
5//! component signature against the resolved key material:
6//!
7//! - **Unattributed proofs**: keys from the self-asserted `COSE_KeySet` in
8//!   the body protected header (`hs_unattributed_key_set`).
9//! - **Authenticated proofs**: keys from the credential `cnf`-resolved
10//!   signer-suite record (provided by the caller).
11//!
12//! Uses `coset`'s built-in `CoseSign1::verify_detached_signature` and
13//! `CoseSign::verify_detached_signature` for Sig_structure construction.
14
15use std::collections::HashMap;
16
17use anyhow::{anyhow, bail, Result};
18use coset::CborSerializable;
19
20use ed25519_dalek::Verifier;
21
22use super::{
23    enrollment::{EnrollmentResolver, SignerRole, SignerSuiteRecord},
24    parser::{CoseStructure, ParsedProof},
25    plan::SignerGroup,
26    ProofDisposition, ProofKind, ALG_ED25519, ALG_ML_DSA_65,
27};
28
29/// One additional enrolled logical signer that approved this request.
30///
31/// Carries everything a generated approver rule must constrain: which signed
32/// logical group it occupied, the suite it verified under, the enrolled
33/// principal, and the enrolled approver role. Dropping any of these would let
34/// an unnamed group, or a group under the wrong suite, count toward a
35/// threshold.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct VerifiedApprover {
38    /// The signed plan's logical signer group ID this approver occupied.
39    pub group_id: u64,
40    /// The exact suite ID this group declared and verified under.
41    pub suite: String,
42    /// The enrolled principal this approver group resolved to.
43    pub principal: String,
44    /// The approver role the enrollment carries, when it names one.
45    pub role: Option<String>,
46}
47
48/// What a successful verification establishes about the proof's signers.
49#[derive(Debug, Clone)]
50pub struct VerifiedProof {
51    /// The replay namespace this proof is admitted under (§4.5): the
52    /// credential-bound primary signer-suite thumbprint for authenticated
53    /// proofs, the plan/key-set thumbprint for unattributed ones.
54    pub replay_thumbprint: [u8; 32],
55    /// The resolved primary principal, for authenticated proofs only. An
56    /// unattributed key set proves only internal proof consistency and is
57    /// never an identity.
58    pub primary_principal: Option<String>,
59    /// The exact suite ID the primary logical signer group declared and
60    /// verified under. The method's generated policy compares against this,
61    /// never against a scalar hint on the body.
62    pub primary_suite: String,
63    /// The additional enrolled logical signers that approved, in ascending
64    /// group order. Empty for a single-signer proof.
65    pub approvers: Vec<VerifiedApprover>,
66}
67
68/// Verify all component signatures on a parsed request proof.
69///
70/// For unattributed proofs, the public keys come from the proof's
71/// body-protected `hs_unattributed_key_set` — self-asserted material that
72/// proves only internal consistency. For authenticated proofs, every logical
73/// signer group resolves through `resolver` to an enrolled signer-suite record
74/// that pins its exact suite, ordered component keys, principal, and epoch;
75/// a component verifying under any unpinned key denies.
76///
77/// A missing credential key or a missing resolver is `Rejected`; neither
78/// downgrades to the unattributed branch.
79pub fn verify_proof_signatures(
80    proof: &ParsedProof,
81    cnf_ed25519_key: Option<&ed25519_dalek::VerifyingKey>,
82    resolver: Option<&dyn EnrollmentResolver>,
83    now: u64,
84) -> Result<VerifiedProof> {
85    if proof.kind != ProofKind::Request {
86        bail!("verify_proof_signatures: only request proofs; use verify_response_proof");
87    }
88    // W1: verifier-clock freshness (design §4.5) — iat within skew on BOTH
89    // sides, not expired, and remaining lifetime within the disposition
90    // maximum. Every bound is evaluated at the injected verifier clock `now`,
91    // never issued lifetime (canonical vectors N-54..N-57).
92    let (max_remaining, disposition) = match proof.disposition {
93        ProofDisposition::Unattributed => (
94            super::MAX_REMAINING_LIFETIME_UNATTRIBUTED_SECS,
95            "unattributed",
96        ),
97        ProofDisposition::Authenticated => (
98            super::MAX_REMAINING_LIFETIME_AUTHENTICATED_SECS,
99            "authenticated",
100        ),
101    };
102    let future_skew = proof.claims.iat.saturating_sub(now);
103    let past_skew = now.saturating_sub(proof.claims.iat);
104    if future_skew > super::MAX_CLOCK_SKEW_SECS || past_skew > super::MAX_CLOCK_SKEW_SECS {
105        bail!(
106            "proof iat out of verifier-clock skew: |iat {} - verifier_now {now}| > {}s ({disposition})",
107            proof.claims.iat,
108            super::MAX_CLOCK_SKEW_SECS
109        );
110    }
111    if now >= proof.claims.exp {
112        bail!(
113            "proof expired: verifier_now {now} >= exp {}",
114            proof.claims.exp
115        );
116    }
117    if proof.claims.exp - now > max_remaining {
118        bail!(
119            "proof over-lifetime: exp - verifier_now {}s > {disposition} max {max_remaining}s",
120            proof.claims.exp - now
121        );
122    }
123    match proof.disposition {
124        ProofDisposition::Unattributed => {
125            verify_unattributed(proof)?;
126            let thumbprint = proof.unattributed_replay_thumbprint().ok_or_else(|| {
127                anyhow!("unattributed proof: cannot compute replay namespace thumbprint")
128            })?;
129            let primary_suite = proof
130                .plan
131                .groups
132                .first()
133                .map(|g| g.suite_id.clone())
134                .ok_or_else(|| anyhow!("unattributed proof has an empty signature plan"))?;
135            if proof.plan.groups.len() != 1 {
136                bail!(
137                    "unattributed proof must carry exactly one signer group, got {}",
138                    proof.plan.groups.len()
139                );
140            }
141            Ok(VerifiedProof {
142                replay_thumbprint: thumbprint,
143                primary_principal: None,
144                primary_suite,
145                approvers: Vec::new(),
146            })
147        }
148        ProofDisposition::Authenticated => {
149            let cnf = cnf_ed25519_key.ok_or_else(|| {
150                anyhow!("authenticated proof requires a resolved credential cnf key")
151            })?;
152            let resolver = resolver.ok_or_else(|| {
153                anyhow!("authenticated proof requires an enrollment resolver; none installed")
154            })?;
155            verify_authenticated(proof, cnf, resolver, now)
156        }
157    }
158}
159
160/// Verify a response proof against the enrolled service identity for the
161/// service domain the *request* was addressed to, and against the exact
162/// request it answers.
163///
164/// A response signed by a different enrolled service's key — even a validly
165/// enrolled one — fails: the caller compares against the one service it
166/// addressed, never against "any enrolled service" (§9.4). A response proof
167/// can never verify for another request ID.
168pub fn verify_response_proof(
169    proof: &ParsedProof,
170    expected_service_domain: &str,
171    expected_request_id: &super::RequestId,
172    expected_response_binding: Option<&super::response::ResponseBinding>,
173    resolver: &dyn EnrollmentResolver,
174    now: u64,
175) -> Result<VerifiedProof> {
176    if proof.kind != ProofKind::Response {
177        bail!("verify_response_proof: proof is not a response proof");
178    }
179    // The response proof's cti echoes the request_id it answers (N-22).
180    if &proof.claims.request_id != expected_request_id {
181        bail!(
182            "response proof cti {} does not match the request_id {} it must answer",
183            hex::encode(proof.claims.request_id),
184            hex::encode(expected_request_id)
185        );
186    }
187    if proof.claims.aud != expected_service_domain {
188        bail!(
189            "response proof aud '{}' is not the addressed service domain '{}'",
190            proof.claims.aud,
191            expected_service_domain
192        );
193    }
194    // The response binding must equal the originating request's binding
195    // field-for-field — locally valid maps still deny against the wrong
196    // request (canonical vector N-32).
197    if proof.claims.response_binding.as_ref() != expected_response_binding {
198        bail!(
199            "response proof response_binding does not equal the originating \
200             request's binding field-for-field (N-32)"
201        );
202    }
203    // For a bound response proof, the signed schema id must name the realized
204    // binding's root type — a cross-field equality CDDL cannot express
205    // (canonical vector N-31).
206    if let Some(binding) = &proof.claims.response_binding {
207        if proof.claims.capnp_schema_id != binding.root_type_id {
208            bail!(
209                "response proof -70002 ({}) must equal the realized response_binding's \
210                 root_type_id ({}) (N-31)",
211                proof.claims.capnp_schema_id,
212                binding.root_type_id
213            );
214        }
215    }
216
217    let record = resolver
218        .resolve_service(expected_service_domain)
219        .ok_or_else(|| {
220            anyhow!("no enrolled response signer for service domain '{expected_service_domain}'")
221        })?;
222    record.check_usable(now, proof.claims.exp, SignerRole::Service)?;
223
224    let groups = &proof.plan.groups;
225    if groups.len() != 1 {
226        bail!(
227            "response proof must carry exactly one signer group, got {}",
228            groups.len()
229        );
230    }
231    if !group_matches_record(&groups[0], &record) {
232        bail!("response proof plan does not match the enrolled service signer record");
233    }
234
235    let mut resolved = HashMap::new();
236    resolved.insert(groups[0].group_id, record.clone());
237    verify_entries_against_records(proof, &resolved)?;
238
239    Ok(VerifiedProof {
240        replay_thumbprint: record.replay_thumbprint(),
241        primary_principal: Some(record.principal),
242        primary_suite: record.suite_id,
243        approvers: Vec::new(),
244    })
245}
246
247/// Verify an unattributed proof's signatures against the self-asserted
248/// COSE_KeySet in the body protected header.
249fn verify_unattributed(proof: &ParsedProof) -> Result<()> {
250    // Re-decode the COSE object to get coset types.
251    let cbor_bytes = proof_to_cose_bytes(proof)?;
252
253    // Extract Ed25519 public keys from the key set.
254    let keys = extract_ed25519_keys_from_protected(&proof.protected_bytes)?;
255
256    if keys.is_empty() {
257        bail!("unattributed proof: no Ed25519 keys in key set");
258    }
259
260    match proof.structure {
261        CoseStructure::Sign1 => {
262            let entry = proof
263                .signatures
264                .first()
265                .ok_or_else(|| anyhow!("COSE_Sign1 has no signature entry"))?;
266            if entry.alg != ALG_ED25519 {
267                bail!("unattributed COSE_Sign1: alg {} not in profile", entry.alg);
268            }
269            // Match the key by its exact kid — never positionally.
270            let key = find_key_by_kid(&keys, &entry.kid).ok_or_else(|| {
271                anyhow!("unattributed proof: no key set entry for the signature kid")
272            })?;
273            let sign1 = coset::CoseSign1::from_slice(&cbor_bytes)
274                .map_err(|e| anyhow!("COSE_Sign1 decode: {e}"))?;
275            sign1
276                .verify_signature(&[], |sig, data| verify_ed25519(sig, data, key))
277                .map_err(|e| anyhow!("Ed25519 signature verification failed: {e}"))
278        }
279        CoseStructure::Sign => {
280            let sign = coset::CoseSign::from_slice(&cbor_bytes)
281                .map_err(|e| anyhow!("COSE_Sign decode: {e}"))?;
282            // Every required component MUST verify. No component is skipped.
283            for (i, parsed_sig) in proof.signatures.iter().enumerate() {
284                match parsed_sig.alg {
285                    ALG_ED25519 => {
286                        let key = find_key_by_kid(&keys, &parsed_sig.kid)
287                            .ok_or_else(|| anyhow!("sig {i}: no Ed25519 key for kid"))?;
288                        sign.verify_signature(i, &[], |s, d| verify_ed25519(s, d, key))
289                            .map_err(|e| anyhow!("sig {i} Ed25519 verification: {e}"))?;
290                    }
291                    ALG_ML_DSA_65 => {
292                        let pq_key = extract_mldsa65_key_from_protected(
293                            &proof.protected_bytes,
294                            &parsed_sig.kid,
295                        )?
296                        .ok_or_else(|| anyhow!("sig {i}: no ML-DSA-65 key for kid"))?;
297                        sign.verify_signature(i, &[], |s, d| verify_mldsa65(s, d, &pq_key))
298                            .map_err(|e| anyhow!("sig {i} ML-DSA-65 verification: {e}"))?;
299                    }
300                    other => bail!("unknown algorithm {other} in signature; denying"),
301                }
302            }
303            Ok(())
304        }
305    }
306}
307
308/// Verify an authenticated proof's component signatures against per-entry
309/// enrollment records.
310///
311/// Every logical signer group resolves independently:
312///
313/// - the **primary** group is the one whose declared suite and ordered
314///   `(alg, kid)` components exactly match the record the credential `cnf`
315///   key resolves to — exactly one group may match;
316/// - every **additional** group resolves through the anchored approver
317///   enrollment for its first component's key ID;
318/// - resolved groups must name distinct principals and must not share a
319///   pinned public key, so one key holder cannot satisfy two logical signers;
320/// - every signature entry verifies under the exact key its own group's
321///   record pins for its `(alg, kid)` — an unpinned key denies even when it
322///   is validly enrolled to the same principal.
323fn verify_authenticated(
324    proof: &ParsedProof,
325    cnf_key: &ed25519_dalek::VerifyingKey,
326    resolver: &dyn EnrollmentResolver,
327    now: u64,
328) -> Result<VerifiedProof> {
329    let primary = resolver
330        .resolve_primary(cnf_key)
331        .ok_or_else(|| anyhow!("no enrolled signer-suite record for the credential cnf key"))?;
332    primary.check_usable(now, proof.claims.exp, SignerRole::Primary)?;
333    if !primary.pins_ed25519(cnf_key) {
334        bail!("resolved primary record does not pin the credential cnf key");
335    }
336
337    // Exactly one plan group may claim the credential-bound primary record.
338    let primary_groups: Vec<&SignerGroup> = proof
339        .plan
340        .groups
341        .iter()
342        .filter(|g| group_matches_record(g, &primary))
343        .collect();
344    if primary_groups.len() != 1 {
345        bail!(
346            "expected exactly one plan group matching the cnf-resolved signer suite, found {}",
347            primary_groups.len()
348        );
349    }
350    let primary_group_id = primary_groups[0].group_id;
351
352    let mut resolved: HashMap<u64, SignerSuiteRecord> = HashMap::new();
353    resolved.insert(primary_group_id, primary.clone());
354
355    for group in &proof.plan.groups {
356        if group.group_id == primary_group_id {
357            continue;
358        }
359        let anchor_kid = &group
360            .components
361            .first()
362            .ok_or_else(|| anyhow!("plan group {} has no components", group.group_id))?
363            .kid;
364        let record = resolver.resolve_approver(anchor_kid).ok_or_else(|| {
365            anyhow!(
366                "no enrolled approver for group {} anchor kid {}",
367                group.group_id,
368                hex::encode(anchor_kid)
369            )
370        })?;
371        record.check_usable(now, proof.claims.exp, SignerRole::Approver)?;
372        if !group_matches_record(group, &record) {
373            bail!(
374                "plan group {} does not match its resolved approver enrollment",
375                group.group_id
376            );
377        }
378        resolved.insert(group.group_id, record);
379    }
380
381    check_distinct_signers(&resolved)?;
382    verify_entries_against_records(proof, &resolved)?;
383
384    // Approvers in ascending plan-group order, so a threshold rule sees the
385    // same set the signed plan declares.
386    let mut approvers: Vec<VerifiedApprover> = proof
387        .plan
388        .groups
389        .iter()
390        .filter(|g| g.group_id != primary_group_id)
391        .filter_map(|g| resolved.get(&g.group_id).map(|record| (g, record)))
392        .map(|(group, record)| VerifiedApprover {
393            group_id: group.group_id,
394            suite: record.suite_id.clone(),
395            principal: record.principal.clone(),
396            role: record.approver_role.clone(),
397        })
398        .collect();
399    approvers.shrink_to_fit();
400
401    Ok(VerifiedProof {
402        replay_thumbprint: primary.replay_thumbprint(),
403        primary_principal: Some(primary.principal),
404        primary_suite: primary.suite_id,
405        approvers,
406    })
407}
408
409/// A plan group matches an enrollment record only if the declared suite and
410/// the ordered `(alg, kid)` component list are exactly equal — no supersets,
411/// no reordering, no principal-level equivalence.
412fn group_matches_record(group: &SignerGroup, record: &SignerSuiteRecord) -> bool {
413    group.suite_id == record.suite_id
414        && group.components.len() == record.components.len()
415        && group
416            .components
417            .iter()
418            .zip(record.components.iter())
419            .all(|(c, e)| c.alg == e.alg && c.kid == e.kid)
420}
421
422/// Distinct logical signer groups must resolve to distinct enrolled
423/// principals, and no pinned public key may be counted in two groups.
424fn check_distinct_signers(resolved: &HashMap<u64, SignerSuiteRecord>) -> Result<()> {
425    let mut principals: HashMap<&str, u64> = HashMap::new();
426    let mut keys: HashMap<Vec<u8>, u64> = HashMap::new();
427    for (group_id, record) in resolved {
428        if let Some(other) = principals.insert(record.principal.as_str(), *group_id) {
429            bail!(
430                "principal '{}' is counted in both group {} and group {}",
431                record.principal,
432                other,
433                group_id
434            );
435        }
436        for component in &record.components {
437            if let Some(other) = keys.insert(component.key.encoded(), *group_id) {
438                bail!(
439                    "one pinned key is counted in both group {} and group {}",
440                    other,
441                    group_id
442                );
443            }
444        }
445    }
446    Ok(())
447}
448
449/// Verify every signature entry under the exact key pinned by its own
450/// group's record, over the COSE `Sig_structure` with a zero-length
451/// `external_aad`.
452fn verify_entries_against_records(
453    proof: &ParsedProof,
454    resolved: &HashMap<u64, SignerSuiteRecord>,
455) -> Result<()> {
456    let cbor_bytes = proof_to_cose_bytes(proof)?;
457
458    match proof.structure {
459        CoseStructure::Sign1 => {
460            let entry = proof
461                .signatures
462                .first()
463                .ok_or_else(|| anyhow!("COSE_Sign1 has no signature entry"))?;
464            let record = resolved
465                .get(&entry.group_id)
466                .ok_or_else(|| anyhow!("no resolved record for group {}", entry.group_id))?;
467            let component = record.component(entry.alg, &entry.kid).ok_or_else(|| {
468                anyhow!(
469                    "group {} pins no key for (alg={}, kid={})",
470                    entry.group_id,
471                    entry.alg,
472                    hex::encode(&entry.kid)
473                )
474            })?;
475            let sign1 = coset::CoseSign1::from_slice(&cbor_bytes)
476                .map_err(|e| anyhow!("COSE_Sign1 decode: {e}"))?;
477            sign1
478                .verify_signature(&[], |sig, data| component.key.verify(sig, data))
479                .map_err(|e| anyhow!("enrolled key verification failed: {e}"))
480        }
481        CoseStructure::Sign => {
482            let sign = coset::CoseSign::from_slice(&cbor_bytes)
483                .map_err(|e| anyhow!("COSE_Sign decode: {e}"))?;
484            for (i, entry) in proof.signatures.iter().enumerate() {
485                let record = resolved
486                    .get(&entry.group_id)
487                    .ok_or_else(|| anyhow!("no resolved record for group {}", entry.group_id))?;
488                let component = record.component(entry.alg, &entry.kid).ok_or_else(|| {
489                    anyhow!(
490                        "group {} pins no key for (alg={}, kid={})",
491                        entry.group_id,
492                        entry.alg,
493                        hex::encode(&entry.kid)
494                    )
495                })?;
496                sign.verify_signature(i, &[], |sig, data| component.key.verify(sig, data))
497                    .map_err(|e| {
498                        anyhow!(
499                            "sig {i} (group {}, alg {}) verification failed: {e}",
500                            entry.group_id,
501                            entry.alg
502                        )
503                    })?;
504            }
505            Ok(())
506        }
507    }
508}
509
510/// Reconstruct the raw COSE bytes from the parsed proof fields.
511/// The ParsedProof stores the decoded components; we need to re-encode
512/// the COSE object to verify with coset.
513fn proof_to_cose_bytes(proof: &ParsedProof) -> Result<Vec<u8>> {
514    // The proof was originally parsed from raw bytes. For verification, we
515    // need to reconstruct or retain those bytes. Since we stored
516    // protected_bytes and payload_bytes, we can reconstruct the COSE array.
517    use ciborium::value::Value as CborValue;
518
519    let unprotected = CborValue::Map(vec![]);
520    let protected_bstr = CborValue::Bytes(proof.protected_bytes.clone());
521    let payload_bstr = CborValue::Bytes(proof.payload_bytes.clone());
522
523    let cose_value = match proof.structure {
524        CoseStructure::Sign1 => {
525            let sig_bstr = CborValue::Bytes(proof.signatures[0].signature.clone());
526            CborValue::Array(vec![protected_bstr, unprotected, payload_bstr, sig_bstr])
527        }
528        CoseStructure::Sign => {
529            let mut sig_entries = Vec::new();
530            for sig in &proof.signatures {
531                let sig_protected_bstr = CborValue::Bytes(sig.protected_bytes.clone());
532                sig_entries.push(CborValue::Array(vec![
533                    sig_protected_bstr,
534                    CborValue::Map(vec![]),
535                    CborValue::Bytes(sig.signature.clone()),
536                ]));
537            }
538            CborValue::Array(vec![
539                protected_bstr,
540                unprotected,
541                payload_bstr,
542                CborValue::Array(sig_entries),
543            ])
544        }
545    };
546
547    let mut buf = Vec::new();
548    ciborium::ser::into_writer(&cose_value, &mut buf)
549        .map_err(|e| anyhow!("COSE re-encode: {e}"))?;
550    Ok(buf)
551}
552
553/// Extract Ed25519 public keys from the body-protected header's
554/// `hs_unattributed_key_set`.
555fn extract_ed25519_keys_from_protected(
556    protected_bytes: &[u8],
557) -> Result<Vec<(Vec<u8>, ed25519_dalek::VerifyingKey)>> {
558    let protected: ciborium::Value =
559        ciborium::de::from_reader(&mut std::io::Cursor::new(protected_bytes))
560            .map_err(|e| anyhow!("protected header decode: {e}"))?;
561
562    let map = match &protected {
563        ciborium::Value::Map(m) => m,
564        _ => bail!("protected header not a map"),
565    };
566
567    // Find hs_unattributed_key_set (-70103)
568    let key_set = map
569        .iter()
570        .find(|(k, _)| {
571            matches!(k,
572                ciborium::Value::Integer(i)
573                if i128::from(*i) == super::HEADER_HS_UNATTRIBUTED_KEY_SET as i128
574            )
575        })
576        .map(|(_, v)| v)
577        .ok_or_else(|| anyhow!("no hs_unattributed_key_set in protected header"))?;
578
579    let key_arr = match key_set {
580        ciborium::Value::Array(a) => a,
581        _ => bail!("key set not an array"),
582    };
583
584    let mut keys = Vec::new();
585    for key_val in key_arr {
586        let key_map = match key_val {
587            ciborium::Value::Map(m) => m,
588            _ => continue,
589        };
590
591        // Check kty == 1 (OKP)
592        let kty = key_map
593            .iter()
594            .find(|(k, _)| matches!(k, ciborium::Value::Integer(i) if i128::from(*i) == 1))
595            .and_then(|(_, v)| match v {
596                ciborium::Value::Integer(i) => Some(i128::from(*i)),
597                _ => None,
598            });
599
600        if kty != Some(1) {
601            continue; // Skip non-OKP keys (ML-DSA-65 handled separately)
602        }
603
604        // Extract kid (label 2)
605        let kid = key_map
606            .iter()
607            .find(|(k, _)| matches!(k, ciborium::Value::Integer(i) if i128::from(*i) == 2))
608            .and_then(|(_, v)| match v {
609                ciborium::Value::Bytes(b) => Some(b.clone()),
610                _ => None,
611            })
612            .unwrap_or_default();
613
614        // Extract x (label -2) — the 32-byte Ed25519 public key
615        let x = key_map
616            .iter()
617            .find(|(k, _)| matches!(k, ciborium::Value::Integer(i) if i128::from(*i) == -2))
618            .and_then(|(_, v)| match v {
619                ciborium::Value::Bytes(b) => Some(b.clone()),
620                _ => None,
621            })
622            .ok_or_else(|| anyhow!("OKP key missing x coordinate"))?;
623
624        if x.len() != 32 {
625            bail!("Ed25519 x coordinate must be 32 bytes, got {}", x.len());
626        }
627
628        let mut pk_bytes = [0u8; 32];
629        pk_bytes.copy_from_slice(&x);
630        let verifying_key = ed25519_dalek::VerifyingKey::from_bytes(&pk_bytes)
631            .map_err(|e| anyhow!("invalid Ed25519 key: {e}"))?;
632
633        keys.push((kid, verifying_key));
634    }
635
636    Ok(keys)
637}
638
639/// Find a key by kid from the list of (kid, key) pairs.
640fn find_key_by_kid<'a>(
641    keys: &'a [(Vec<u8>, ed25519_dalek::VerifyingKey)],
642    kid: &[u8],
643) -> Option<&'a ed25519_dalek::VerifyingKey> {
644    keys.iter().find(|(k, _)| k == kid).map(|(_, vk)| vk)
645}
646
647/// Verify an Ed25519 signature.
648fn verify_ed25519(
649    sig: &[u8],
650    data: &[u8],
651    key: &ed25519_dalek::VerifyingKey,
652) -> Result<(), &'static str> {
653    if sig.len() != 64 {
654        return Err("signature must be 64 bytes");
655    }
656    let mut sig_bytes = [0u8; 64];
657    sig_bytes.copy_from_slice(sig);
658    let sig = ed25519_dalek::Signature::from_bytes(&sig_bytes);
659    key.verify(data, &sig)
660        .map_err(|_| "Ed25519 verification failed")
661}
662
663/// Extract an ML-DSA-65 public key from the body-protected header's
664/// COSE_KeySet by matching kid.
665fn extract_mldsa65_key_from_protected(
666    protected_bytes: &[u8],
667    kid: &[u8],
668) -> Result<Option<crate::crypto::pq::MlDsaVerifyingKey>> {
669    let protected: ciborium::Value =
670        ciborium::de::from_reader(&mut std::io::Cursor::new(protected_bytes))
671            .map_err(|e| anyhow!("protected header decode: {e}"))?;
672
673    let map = match &protected {
674        ciborium::Value::Map(m) => m,
675        _ => bail!("protected header not a map"),
676    };
677
678    let key_set = map
679        .iter()
680        .find(|(k, _)| {
681            matches!(k,
682                ciborium::Value::Integer(i)
683                if i128::from(*i) == super::HEADER_HS_UNATTRIBUTED_KEY_SET as i128
684            )
685        })
686        .map(|(_, v)| v);
687
688    let key_set = match key_set {
689        Some(v) => v,
690        None => return Ok(None),
691    };
692
693    let key_arr = match key_set {
694        ciborium::Value::Array(a) => a,
695        _ => bail!("key set not an array"),
696    };
697
698    for key_val in key_arr {
699        let key_map = match key_val {
700            ciborium::Value::Map(m) => m,
701            _ => continue,
702        };
703
704        // Check kty == 7 (AKP)
705        let kty = key_map
706            .iter()
707            .find(|(k, _)| matches!(k, ciborium::Value::Integer(i) if i128::from(*i) == 7))
708            .and_then(|(_, v)| match v {
709                ciborium::Value::Integer(i) => Some(i128::from(*i)),
710                _ => None,
711            });
712
713        if kty != Some(7) {
714            continue;
715        }
716
717        // Match kid
718        let key_kid = key_map
719            .iter()
720            .find(|(k, _)| matches!(k, ciborium::Value::Integer(i) if i128::from(*i) == 2))
721            .and_then(|(_, v)| match v {
722                ciborium::Value::Bytes(b) => Some(b.clone()),
723                _ => None,
724            })
725            .unwrap_or_default();
726
727        if key_kid != kid {
728            continue;
729        }
730
731        // Extract pub (label -1) — 1952-byte ML-DSA-65 public key
732        let pub_key = key_map
733            .iter()
734            .find(|(k, _)| matches!(k, ciborium::Value::Integer(i) if i128::from(*i) == -1))
735            .and_then(|(_, v)| match v {
736                ciborium::Value::Bytes(b) => Some(b.clone()),
737                _ => None,
738            })
739            .ok_or_else(|| anyhow!("AKP key missing pub field"))?;
740
741        if pub_key.len() != 1952 {
742            bail!("ML-DSA-65 pub must be 1952 bytes, got {}", pub_key.len());
743        }
744
745        let vk = crate::crypto::pq::ml_dsa_vk_from_bytes(&pub_key)?;
746        return Ok(Some(vk));
747    }
748
749    Ok(None)
750}
751
752/// Verify an ML-DSA-65 signature.
753fn verify_mldsa65(
754    sig: &[u8],
755    data: &[u8],
756    key: &crate::crypto::pq::MlDsaVerifyingKey,
757) -> Result<(), &'static str> {
758    crate::crypto::pq::ml_dsa_verify(key, data, sig).map_err(|_| "ML-DSA-65 verification failed")
759}
760
761#[cfg(test)]
762#[allow(clippy::unwrap_used, clippy::expect_used)]
763mod tests {
764    use super::super::parser::ParsedProof;
765    use super::super::tests::{
766        classical_enrollment, ed25519_public, hybrid_enrollment, FIXTURE_NOW, FIXTURE_REQUEST_ID,
767    };
768    use super::*;
769
770    fn load_vector(id: &str) -> Vec<u8> {
771        let vectors = super::super::tests::load_positive_vectors();
772        vectors
773            .iter()
774            .find(|(v_id, _)| v_id == id)
775            .unwrap_or_else(|| panic!("vector {id} must exist"))
776            .1
777            .clone()
778    }
779
780    fn parse(id: &str) -> ParsedProof {
781        ParsedProof::parse(&load_vector(id)).unwrap_or_else(|e| panic!("{id} must parse: {e}"))
782    }
783
784    fn client_cnf() -> ed25519_dalek::VerifyingKey {
785        ed25519_public("client-ed25519-1")
786    }
787
788    /// The canonical roster's HYBRID credential cnf-bound key: the Ed25519
789    /// component of the WNS hybrid signer (P-2), distinct from the classical
790    /// client key by construction.
791    fn hybrid_client_cnf() -> ed25519_dalek::VerifyingKey {
792        ed25519_public("client-ed25519-hy-1")
793    }
794
795    // -- unattributed ------------------------------------------------------
796
797    #[test]
798    fn p1_unattributed_signature_verifies() {
799        let proof = parse("P-1");
800        assert_eq!(proof.disposition, ProofDisposition::Unattributed);
801        assert_eq!(proof.structure, CoseStructure::Sign1);
802        let verified = verify_proof_signatures(&proof, None, None, FIXTURE_NOW)
803            .expect("P-1 self-asserted Ed25519 signature must verify");
804        assert!(
805            verified.primary_principal.is_none(),
806            "an unattributed key set is never an identity"
807        );
808        assert_eq!(
809            verified.replay_thumbprint,
810            proof.unattributed_replay_thumbprint().unwrap()
811        );
812    }
813
814    #[test]
815    fn p1_corrupted_signature_denies() {
816        let mut proof = parse("P-1");
817        proof.signatures[0].signature[0] ^= 0xFF;
818        assert!(verify_proof_signatures(&proof, None, None, FIXTURE_NOW).is_err());
819    }
820
821    // -- authenticated: enrolled suites verify -----------------------------
822
823    #[test]
824    fn p2_hybrid_verifies_under_its_enrolled_suite() {
825        let proof = parse("P-2");
826        assert_eq!(proof.disposition, ProofDisposition::Authenticated);
827        assert_eq!(proof.structure, CoseStructure::Sign);
828        assert_eq!(proof.signatures.len(), 2);
829        let resolver = hybrid_enrollment();
830        let verified = verify_proof_signatures(
831            &proof,
832            Some(&hybrid_client_cnf()),
833            Some(&resolver),
834            FIXTURE_NOW,
835        )
836        .expect("P-2 must verify: both Ed25519 and ML-DSA-65 components");
837        assert_eq!(verified.primary_principal.as_deref(), Some("client"));
838    }
839
840    // P-4 is the sole authenticated classical *single-group* Sign1 vector; the
841    // merged v16-A fixture re-issued it at the amended four-field
842    // `response_binding`, so it now parses and verifies under this lane's
843    // amended parser (see the inline four-field conformance tests in
844    // `proof::response`).
845    #[test]
846    fn p4_classical_sign1_verifies_under_its_enrolled_suite() {
847        let proof = parse("P-4");
848        let resolver = classical_enrollment();
849        verify_proof_signatures(&proof, Some(&client_cnf()), Some(&resolver), FIXTURE_NOW)
850            .expect("P-4 must verify under the enrolled classical suite");
851    }
852
853    #[test]
854    fn p5_two_logical_groups_verify_against_distinct_enrollments() {
855        let proof = parse("P-5");
856        assert_eq!(proof.plan.groups.len(), 2);
857        let resolver = classical_enrollment();
858        let verified =
859            verify_proof_signatures(&proof, Some(&client_cnf()), Some(&resolver), FIXTURE_NOW)
860                .expect("P-5 must verify: primary group plus one anchored approver");
861        assert_eq!(verified.primary_principal.as_deref(), Some("client"));
862    }
863
864    /// The replay namespace excludes approver groups: the same primary signer
865    /// is admitted under one namespace whether or not approvers are present.
866    ///
867    /// This one compares P-4's single-group thumbprint against P-5's, so it
868    /// needs P-4 specifically.
869    #[test]
870    fn approver_groups_do_not_change_the_replay_namespace() {
871        let resolver = classical_enrollment();
872        let p4 = verify_proof_signatures(
873            &parse("P-4"),
874            Some(&client_cnf()),
875            Some(&resolver),
876            FIXTURE_NOW,
877        )
878        .unwrap();
879        let p5 = verify_proof_signatures(
880            &parse("P-5"),
881            Some(&client_cnf()),
882            Some(&resolver),
883            FIXTURE_NOW,
884        )
885        .unwrap();
886        assert_eq!(p4.replay_thumbprint, p5.replay_thumbprint);
887    }
888
889    /// The unattributed namespace is disjoint from the authenticated one.
890    #[test]
891    fn unattributed_and_authenticated_namespaces_are_disjoint() {
892        let resolver = classical_enrollment();
893        let unattributed = verify_proof_signatures(&parse("P-1"), None, None, FIXTURE_NOW).unwrap();
894        // Any authenticated classical proof serves; P-5 is the multi-group one.
895        let authenticated = verify_proof_signatures(
896            &parse("P-5"),
897            Some(&client_cnf()),
898            Some(&resolver),
899            FIXTURE_NOW,
900        )
901        .unwrap();
902        assert_ne!(
903            unattributed.replay_thumbprint,
904            authenticated.replay_thumbprint
905        );
906    }
907
908    // -- authenticated: fail-closed ----------------------------------------
909
910    /// A missing enrollment resolver, or a credential with no enrolled
911    /// signer-suite record, is Rejected — never downgraded to the
912    /// self-asserted branch.
913    #[test]
914    fn missing_resolver_or_enrollment_denies() {
915        // Any authenticated proof exercises the missing-resolver /
916        // empty-enrollment denials.
917        let proof = parse("P-5");
918        assert!(
919            verify_proof_signatures(&proof, Some(&client_cnf()), None, FIXTURE_NOW).is_err(),
920            "no resolver installed must deny"
921        );
922        assert!(
923            verify_proof_signatures(
924                &proof,
925                Some(&client_cnf()),
926                Some(&super::super::enrollment::InMemoryEnrollmentResolver::new()),
927                FIXTURE_NOW
928            )
929            .is_err(),
930            "an empty enrollment must deny"
931        );
932    }
933
934    /// A missing credential is Rejected for every authenticated vector.
935    #[test]
936    fn missing_credential_denies() {
937        let resolver = classical_enrollment();
938        // P-2 (hybrid Sign), P-4 (classical Sign1), and P-5 (classical
939        // two-group Sign) keep the no-credential denial covered across both
940        // suites and topologies.
941        for id in ["P-2", "P-4", "P-5"] {
942            assert!(
943                verify_proof_signatures(&parse(id), None, Some(&resolver), FIXTURE_NOW).is_err(),
944                "{id} with no credential must deny"
945            );
946        }
947    }
948
949    /// A credential that resolves to no enrolled record denies, even though
950    /// the proof's own signatures are internally valid.
951    #[test]
952    fn unenrolled_credential_denies() {
953        let stranger = ed25519_dalek::SigningKey::from_bytes(&[3u8; 32]).verifying_key();
954        let resolver = classical_enrollment();
955        assert!(verify_proof_signatures(
956            &parse("P-5"),
957            Some(&stranger),
958            Some(&resolver),
959            FIXTURE_NOW
960        )
961        .is_err());
962    }
963
964    /// Component-key separation: a key enrolled for the WNS hybrid suite is
965    /// unusable in the standalone suite, and vice versa. Each vector verifies
966    /// under exactly the deployment that enrolled its suite.
967    #[test]
968    fn cross_suite_enrollment_denies() {
969        let hybrid = hybrid_enrollment();
970        let classical = classical_enrollment();
971        // P-4 and P-5 are both standalone-suite (classical Sign1 and Sign
972        // respectively); each must deny under the hybrid-only enrollment.
973        assert!(
974            verify_proof_signatures(
975                &parse("P-4"),
976                Some(&client_cnf()),
977                Some(&hybrid),
978                FIXTURE_NOW
979            )
980            .is_err(),
981            "P-4 (standalone suite) must deny under a hybrid enrollment"
982        );
983        assert!(
984            verify_proof_signatures(
985                &parse("P-5"),
986                Some(&client_cnf()),
987                Some(&hybrid),
988                FIXTURE_NOW
989            )
990            .is_err(),
991            "P-5 (standalone suite) must deny under a hybrid enrollment"
992        );
993        assert!(
994            verify_proof_signatures(
995                &parse("P-2"),
996                Some(&client_cnf()),
997                Some(&classical),
998                FIXTURE_NOW
999            )
1000            .is_err(),
1001            "P-2 (hybrid suite) must deny under a standalone enrollment"
1002        );
1003    }
1004
1005    /// A corrupted post-quantum component denies the whole proof: no
1006    /// component is optional, and a surviving classical signature cannot
1007    /// carry a hybrid group.
1008    #[test]
1009    fn corrupted_ml_dsa_component_denies() {
1010        let mut proof = parse("P-2");
1011        let idx = proof
1012            .signatures
1013            .iter()
1014            .position(|s| s.alg == ALG_ML_DSA_65)
1015            .expect("P-2 has an ML-DSA-65 component");
1016        proof.signatures[idx].signature[0] ^= 0xFF;
1017        let resolver = hybrid_enrollment();
1018        assert!(
1019            verify_proof_signatures(
1020                &proof,
1021                Some(&hybrid_client_cnf()),
1022                Some(&resolver),
1023                FIXTURE_NOW
1024            )
1025            .is_err(),
1026            "a corrupted ML-DSA-65 component must deny"
1027        );
1028    }
1029
1030    /// The classical component of a hybrid proof is equally mandatory.
1031    #[test]
1032    fn corrupted_ed25519_component_of_a_hybrid_proof_denies() {
1033        let mut proof = parse("P-2");
1034        let idx = proof
1035            .signatures
1036            .iter()
1037            .position(|s| s.alg == ALG_ED25519)
1038            .expect("P-2 has an Ed25519 component");
1039        proof.signatures[idx].signature[0] ^= 0xFF;
1040        let resolver = hybrid_enrollment();
1041        assert!(verify_proof_signatures(
1042            &proof,
1043            Some(&hybrid_client_cnf()),
1044            Some(&resolver),
1045            FIXTURE_NOW
1046        )
1047        .is_err());
1048    }
1049
1050    /// A revoked enrollment denies; so does one whose validity has passed,
1051    /// and a proof that would outlive its credential.
1052    #[test]
1053    fn revoked_expired_or_overlong_enrollment_denies() {
1054        // The revoked / expired / proof-outlives-credential denials apply to
1055        // any credential-bound proof under the same enrollment.
1056        let proof = parse("P-5");
1057        let cnf = client_cnf();
1058
1059        let mut revoked = classical_enrollment();
1060        {
1061            let mut r = revoked.resolve_primary(&cnf).unwrap();
1062            r.revoked = true;
1063            revoked = rebuild_primary(r, &cnf);
1064        }
1065        assert!(
1066            verify_proof_signatures(&proof, Some(&cnf), Some(&revoked), FIXTURE_NOW).is_err(),
1067            "revoked enrollment must deny"
1068        );
1069
1070        let resolver = classical_enrollment();
1071        let past_validity = resolver.resolve_primary(&cnf).unwrap().not_after + 1;
1072        assert!(
1073            verify_proof_signatures(&proof, Some(&cnf), Some(&resolver), past_validity).is_err(),
1074            "expired enrollment must deny"
1075        );
1076
1077        let mut short = classical_enrollment();
1078        {
1079            let mut r = short.resolve_primary(&cnf).unwrap();
1080            r.not_after = proof.claims.exp - 1;
1081            short = rebuild_primary(r, &cnf);
1082        }
1083        assert!(
1084            verify_proof_signatures(&proof, Some(&cnf), Some(&short), FIXTURE_NOW).is_err(),
1085            "a proof outliving its credential must deny"
1086        );
1087    }
1088
1089    fn rebuild_primary(
1090        record: super::super::enrollment::SignerSuiteRecord,
1091        cnf: &ed25519_dalek::VerifyingKey,
1092    ) -> super::super::enrollment::InMemoryEnrollmentResolver {
1093        let mut resolver = super::super::enrollment::InMemoryEnrollmentResolver::new();
1094        resolver.enrol_primary(cnf, record).unwrap();
1095        resolver
1096    }
1097
1098    /// An approver enrollment cannot stand in as the credential-bound primary
1099    /// signer: one key holder must not satisfy two logical roles.
1100    #[test]
1101    fn an_approver_enrollment_cannot_act_as_primary() {
1102        use super::super::enrollment::{
1103            ComponentKey, EnrolledComponent, InMemoryEnrollmentResolver, SignerRole,
1104            SignerSuiteRecord,
1105        };
1106        let cnf = client_cnf();
1107        let approver_shaped = SignerSuiteRecord {
1108            principal: "client".into(),
1109            suite_id: super::super::SUITE_CLASSICAL.into(),
1110            components: vec![EnrolledComponent::new(
1111                b"client-ed25519-1".to_vec(),
1112                ComponentKey::Ed25519(cnf),
1113            )],
1114            epoch: 1,
1115            role: SignerRole::Approver,
1116            approver_role: None,
1117            enrollment_policy_id: "test-enrollment-v1".to_owned(),
1118            not_after: 1_786_000_600,
1119            revoked: false,
1120        };
1121        // The registration surface refuses it outright...
1122        let mut resolver = InMemoryEnrollmentResolver::new();
1123        assert!(resolver
1124            .enrol_primary(&cnf, approver_shaped.clone())
1125            .is_err());
1126        // ...and the role check denies even if a resolver returned it anyway.
1127        assert!(approver_shaped
1128            .check_usable(FIXTURE_NOW, 1_786_000_030, SignerRole::Primary)
1129            .is_err());
1130    }
1131
1132    /// Two logical signer groups resolving to the same principal deny: a
1133    /// multi-party approval requires distinct enrolled principals.
1134    #[test]
1135    fn two_groups_resolving_to_one_principal_deny() {
1136        use super::super::enrollment::{
1137            ComponentKey, EnrolledComponent, InMemoryEnrollmentResolver, SignerRole,
1138            SignerSuiteRecord,
1139        };
1140        let cnf = client_cnf();
1141        let mut resolver = InMemoryEnrollmentResolver::new();
1142        resolver
1143            .enrol_primary(
1144                &cnf,
1145                SignerSuiteRecord {
1146                    principal: "client".into(),
1147                    suite_id: super::super::SUITE_CLASSICAL.into(),
1148                    components: vec![EnrolledComponent::new(
1149                        b"client-ed25519-1".to_vec(),
1150                        ComponentKey::Ed25519(cnf),
1151                    )],
1152                    epoch: 1,
1153                    role: SignerRole::Primary,
1154                    approver_role: None,
1155                    enrollment_policy_id: "test-enrollment-v1".to_owned(),
1156                    not_after: 1_786_000_600,
1157                    revoked: false,
1158                },
1159            )
1160            .unwrap();
1161        // The approver group is enrolled to the *same* principal.
1162        resolver
1163            .enrol_approver(SignerSuiteRecord {
1164                principal: "client".into(),
1165                suite_id: super::super::SUITE_CLASSICAL.into(),
1166                components: vec![EnrolledComponent::new(
1167                    b"approver-ed25519-1".to_vec(),
1168                    ComponentKey::Ed25519(ed25519_public("approver-ed25519-1")),
1169                )],
1170                epoch: 1,
1171                role: SignerRole::Approver,
1172                approver_role: None,
1173                enrollment_policy_id: "test-enrollment-v1".to_owned(),
1174                not_after: 1_786_000_600,
1175                revoked: false,
1176            })
1177            .unwrap();
1178        assert!(
1179            verify_proof_signatures(&parse("P-5"), Some(&cnf), Some(&resolver), FIXTURE_NOW)
1180                .is_err(),
1181            "P-5 must deny when both groups resolve to one principal"
1182        );
1183    }
1184
1185    // -- response proofs ---------------------------------------------------
1186
1187    #[test]
1188    fn p3_response_proof_verifies_against_the_enrolled_service() {
1189        let proof = parse("P-3");
1190        let resolver = classical_enrollment();
1191        let verified = verify_response_proof(
1192            &proof,
1193            "registry.svc.hyprstream.test",
1194            &FIXTURE_REQUEST_ID,
1195            None,
1196            &resolver,
1197            FIXTURE_NOW,
1198        )
1199        .expect("P-3 must verify against the enrolled service signer");
1200        assert_eq!(
1201            verified.primary_principal.as_deref(),
1202            Some("registry-service")
1203        );
1204    }
1205
1206    /// A response proof is only trusted for the service domain the request was
1207    /// addressed to, and is never accepted through the request path.
1208    #[test]
1209    fn response_proof_is_scoped_and_never_a_request() {
1210        let proof = parse("P-3");
1211        let resolver = classical_enrollment();
1212        assert!(
1213            verify_response_proof(
1214                &proof,
1215                "other.svc.hyprstream.test",
1216                &FIXTURE_REQUEST_ID,
1217                None,
1218                &resolver,
1219                FIXTURE_NOW
1220            )
1221            .is_err(),
1222            "a response for another service domain must deny"
1223        );
1224        assert!(
1225            verify_proof_signatures(&proof, Some(&client_cnf()), Some(&resolver), FIXTURE_NOW)
1226                .is_err(),
1227            "a response proof must never verify through the request path"
1228        );
1229        assert!(
1230            // Any request proof must be refused through the response path.
1231            verify_response_proof(
1232                &parse("P-5"),
1233                "registry.svc.hyprstream.test",
1234                &FIXTURE_REQUEST_ID,
1235                None,
1236                &resolver,
1237                FIXTURE_NOW
1238            )
1239            .is_err(),
1240            "a request proof must never verify through the response path"
1241        );
1242    }
1243
1244    /// A response signed by a different enrolled service's key denies, even
1245    /// though that key is validly enrolled elsewhere.
1246    #[test]
1247    fn response_signed_by_another_enrolled_service_denies() {
1248        use super::super::enrollment::{
1249            ComponentKey, EnrolledComponent, InMemoryEnrollmentResolver, SignerRole,
1250            SignerSuiteRecord,
1251        };
1252        let mut resolver = InMemoryEnrollmentResolver::new();
1253        // The addressed domain enrols a *different* service key.
1254        resolver
1255            .enrol_service(
1256                "registry.svc.hyprstream.test",
1257                SignerSuiteRecord {
1258                    principal: "other-service".into(),
1259                    suite_id: super::super::SUITE_CLASSICAL.into(),
1260                    components: vec![EnrolledComponent::new(
1261                        b"service-ed25519-1".to_vec(),
1262                        ComponentKey::Ed25519(ed25519_public("approver-ed25519-1")),
1263                    )],
1264                    epoch: 1,
1265                    role: SignerRole::Service,
1266                    approver_role: None,
1267                    enrollment_policy_id: "test-enrollment-v1".to_owned(),
1268                    not_after: 1_786_000_600,
1269                    revoked: false,
1270                },
1271            )
1272            .unwrap();
1273        assert!(verify_response_proof(
1274            &parse("P-3"),
1275            "registry.svc.hyprstream.test",
1276            &FIXTURE_REQUEST_ID,
1277            None,
1278            &resolver,
1279            FIXTURE_NOW
1280        )
1281        .is_err());
1282    }
1283
1284    #[test]
1285    fn response_proof_without_service_enrollment_denies() {
1286        let resolver = super::super::enrollment::InMemoryEnrollmentResolver::new();
1287        assert!(verify_response_proof(
1288            &parse("P-3"),
1289            "registry.svc.hyprstream.test",
1290            &FIXTURE_REQUEST_ID,
1291            None,
1292            &resolver,
1293            FIXTURE_NOW
1294        )
1295        .is_err());
1296    }
1297}