Skip to main content

hyprstream_rpc/proof/
build.rs

1//! Authenticated request-proof CWT production for the frozen v16 WNS profile.
2//!
3//! This module emits only the primary authenticated Ed25519 + ML-DSA-65
4//! profile.  It takes already-owned proof-dedicated signer material and exact
5//! credential/body inputs; it neither mints credentials nor consults mesh,
6//! envelope, or enrollment key stores.  Callers must arrange the separately
7//! enrolled proof keys and the credential's `cnf` binding before transmission.
8
9use crate::transport_traits::Signer;
10use anyhow::{bail, Result};
11use ciborium::value::Value as CborValue;
12use ed25519_dalek::Signer as _;
13use rand::RngCore as _;
14use sha2::{Digest as _, Sha256};
15
16use super::{
17    recipient_binding::FederateRecipientBinding,
18    response::{KemRecipient, ProtectionMode, ResponseBinding, ResponseKind},
19    CredentialHash, RequestId, ALG_ED25519, ALG_ML_DSA_65, CLAIM_CAPNP_BODY_BYTES,
20    CLAIM_CAPNP_SCHEMA_ID, CLAIM_CREDENTIAL_HASH, CLAIM_FEDERATE_RECIPIENT_BINDING,
21    CLAIM_RESPONSE_BINDING, COSE_HEADER_ALG, COSE_HEADER_CRIT, COSE_HEADER_KID, COSE_HEADER_TYP,
22    CWT_CLAIM_AUD, CWT_CLAIM_CTI, CWT_CLAIM_EXP, CWT_CLAIM_IAT, HEADER_HS_DOMAIN,
23    HEADER_HS_LOGICAL_SIGNER_GROUP, HEADER_HS_SIGNATURE_PLAN, MAX_BODY_BYTES, MAX_KID_BYTES,
24    PROOF_TYP, REQUEST_PROOF_DOMAIN, SUITE_HYBRID,
25};
26
27/// Proof-dedicated private components for the sole supported producer suite.
28///
29/// These keys are deliberately supplied by the caller.  They must be distinct
30/// from mesh, envelope, CA, and node identity keys, and their public halves
31/// must already be enrolled as one primary WNS suite by the verifier.
32pub struct AuthenticatedHybridProofSigner {
33    ed25519: ed25519_dalek::SigningKey,
34    ed25519_kid: Vec<u8>,
35    ml_dsa_65: crate::crypto::pq::MlDsaSigningKey,
36    ml_dsa_65_kid: Vec<u8>,
37}
38
39impl AuthenticatedHybridProofSigner {
40    /// Constructs a proof signer from already-owned, proof-dedicated keys.
41    pub fn new(
42        ed25519: ed25519_dalek::SigningKey,
43        ed25519_kid: impl Into<Vec<u8>>,
44        ml_dsa_65: crate::crypto::pq::MlDsaSigningKey,
45        ml_dsa_65_kid: impl Into<Vec<u8>>,
46    ) -> Result<Self> {
47        let ed25519_kid = ed25519_kid.into();
48        let ml_dsa_65_kid = ml_dsa_65_kid.into();
49        validate_kid(&ed25519_kid, "Ed25519")?;
50        validate_kid(&ml_dsa_65_kid, "ML-DSA-65")?;
51        Ok(Self {
52            ed25519,
53            ed25519_kid,
54            ml_dsa_65,
55            ml_dsa_65_kid,
56        })
57    }
58}
59
60/// Exact request commitments for an authenticated proof CWT.
61pub struct AuthenticatedRequestProofInput<'a> {
62    /// Canonical addressed RPC service domain.
63    pub service_domain: &'a str,
64    /// Exact credential bytes presented with the envelope; hashed as claim
65    /// `-70001` without parsing, normalization, or substitution.
66    pub credential: &'a [u8],
67    /// Unix seconds used for CWT `iat`. W1 freshness is evaluated by the
68    /// verifier against its injected clock; the producer records this value
69    /// without consulting an ambient clock or imposing an `exp`/`iat` rule.
70    pub issued_at: u64,
71    /// Unix seconds used for CWT `exp`. W1 freshness is evaluated by the
72    /// verifier against its injected clock; the producer records this value
73    /// without consulting an ambient clock or imposing an issued-lifetime cap.
74    pub expires_at: u64,
75    /// Exact Cap'n Proto root schema ID for `capnp_schema_id`.
76    pub capnp_schema_id: u64,
77    /// Exact canonical Cap'n Proto request bytes for `capnp_body_bytes`.
78    pub capnp_body: &'a [u8],
79    /// Commitment to response delivery, or `None` for cleartext unary.
80    pub response_binding: Option<&'a ResponseBinding>,
81    /// Optional recipient-pair commitment for deferred Federate requests.
82    /// Generic request proofs omit this source-slice extension.
83    pub federate_recipient_binding: Option<&'a FederateRecipientBinding>,
84}
85
86/// Produces a deterministic authenticated request proof in the sole supported
87/// WNS profile: one logical group with Ed25519 followed by ML-DSA-65.
88///
89/// The result is an untagged, deterministic `COSE_Sign`, parseable and
90/// cryptographically verifiable by [`super::parser::ParsedProof`] and
91/// [`super::verify::verify_proof_signatures`].  Unsupported plans and
92/// classical-only emission are intentionally unavailable.
93pub fn build_authenticated_hybrid_request_proof(
94    input: &AuthenticatedRequestProofInput<'_>,
95    signer: &AuthenticatedHybridProofSigner,
96) -> Result<Vec<u8>> {
97    // The public producer never accepts caller-selected replay identifiers.
98    let mut request_id: RequestId = [0; super::REQUEST_ID_SIZE];
99    rand::rngs::OsRng.fill_bytes(&mut request_id);
100    build_authenticated_hybrid_request_proof_with_id(input, signer, request_id)
101}
102
103// Private seam for a reproducible signed test vector. Production always enters
104// through the public builder above and generates its own request ID.
105fn build_authenticated_hybrid_request_proof_with_id(
106    input: &AuthenticatedRequestProofInput<'_>,
107    signer: &AuthenticatedHybridProofSigner,
108    request_id: RequestId,
109) -> Result<Vec<u8>> {
110    let (body_protected, ed_protected, pq_protected, payload) = prepare_hybrid_proof(
111        input,
112        &signer.ed25519_kid,
113        &signer.ml_dsa_65_kid,
114        request_id,
115    )?;
116    let ed_tbs = signature_structure(&body_protected, &ed_protected, &payload)?;
117    let pq_tbs = signature_structure(&body_protected, &pq_protected, &payload)?;
118    let ed_signature = signer.ed25519.sign(&ed_tbs).to_bytes().to_vec();
119    let pq_signature = crate::crypto::pq::ml_dsa_sign(&signer.ml_dsa_65, &pq_tbs);
120    finish_hybrid_proof(
121        body_protected,
122        ed_protected,
123        pq_protected,
124        payload,
125        ed_signature,
126        pq_signature,
127    )
128}
129
130/// Produce the same v16 COSE_Sign bytes with a browser-backed signer. Its
131/// private proof keys may remain in an isolated JS vault; only the exact
132/// Sig_structure bytes cross the callback boundary. A fresh CWT request ID is
133/// generated here for every call.
134pub async fn build_authenticated_hybrid_request_proof_with_signer<S: Signer>(
135    input: &AuthenticatedRequestProofInput<'_>,
136    signer: &S,
137    ed25519_kid: &[u8],
138    ml_dsa_65_kid: &[u8],
139) -> Result<Vec<u8>> {
140    let mut request_id = [0; super::REQUEST_ID_SIZE];
141    rand::rngs::OsRng.fill_bytes(&mut request_id);
142    build_authenticated_hybrid_request_proof_with_signer_and_id(
143        input,
144        signer,
145        ed25519_kid,
146        ml_dsa_65_kid,
147        request_id,
148    )
149    .await
150}
151
152async fn build_authenticated_hybrid_request_proof_with_signer_and_id<S: Signer>(
153    input: &AuthenticatedRequestProofInput<'_>,
154    signer: &S,
155    ed25519_kid: &[u8],
156    ml_dsa_65_kid: &[u8],
157    request_id: RequestId,
158) -> Result<Vec<u8>> {
159    let pq_public = signer
160        .pq_pubkey()
161        .ok_or_else(|| anyhow::anyhow!("request proof: browser signer has no ML-DSA-65 key"))?;
162    let pq_key = crate::crypto::pq::ml_dsa_vk_from_bytes(&pq_public)?;
163    let ed_key = ed25519_dalek::VerifyingKey::from_bytes(&signer.pubkey())?;
164    let (body_protected, ed_protected, pq_protected, payload) =
165        prepare_hybrid_proof(input, ed25519_kid, ml_dsa_65_kid, request_id)?;
166    let ed_tbs = signature_structure(&body_protected, &ed_protected, &payload)?;
167    let pq_tbs = signature_structure(&body_protected, &pq_protected, &payload)?;
168    let ed_signature = signer.sign(&ed_tbs).await?;
169    ed_key.verify_strict(
170        &ed_tbs,
171        &ed25519_dalek::Signature::from_bytes(&ed_signature),
172    )?;
173    let pq_signature = signer.pq_sign(&pq_tbs).await?.ok_or_else(|| {
174        anyhow::anyhow!("request proof: browser signer omitted ML-DSA-65 signature")
175    })?;
176    crate::crypto::pq::ml_dsa_verify(&pq_key, &pq_tbs, &pq_signature)?;
177    finish_hybrid_proof(
178        body_protected,
179        ed_protected,
180        pq_protected,
181        payload,
182        ed_signature.to_vec(),
183        pq_signature,
184    )
185}
186
187fn prepare_hybrid_proof(
188    input: &AuthenticatedRequestProofInput<'_>,
189    ed25519_kid: &[u8],
190    ml_dsa_65_kid: &[u8],
191    request_id: RequestId,
192) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>)> {
193    validate_kid(ed25519_kid, "Ed25519")?;
194    validate_kid(ml_dsa_65_kid, "ML-DSA-65")?;
195    crate::envelope::validate_service_domain(input.service_domain)?;
196    if input.credential.is_empty() {
197        bail!("request proof: credential bytes must not be empty");
198    }
199    if input.capnp_body.len() > MAX_BODY_BYTES {
200        bail!(
201            "request proof: capnp body {} exceeds {} bytes",
202            input.capnp_body.len(),
203            MAX_BODY_BYTES
204        );
205    }
206    let credential_hash: CredentialHash = Sha256::digest(input.credential).into();
207    let payload = encode_claims(input, credential_hash, request_id)?;
208    let body_protected = encode_body_protected(ed25519_kid, ml_dsa_65_kid)?;
209    let ed_protected = encode_signature_protected(ALG_ED25519, ed25519_kid)?;
210    let pq_protected = encode_signature_protected(ALG_ML_DSA_65, ml_dsa_65_kid)?;
211    Ok((body_protected, ed_protected, pq_protected, payload))
212}
213
214fn finish_hybrid_proof(
215    body_protected: Vec<u8>,
216    ed_protected: Vec<u8>,
217    pq_protected: Vec<u8>,
218    payload: Vec<u8>,
219    ed_signature: Vec<u8>,
220    pq_signature: Vec<u8>,
221) -> Result<Vec<u8>> {
222    let cose = CborValue::Array(vec![
223        CborValue::Bytes(body_protected),
224        CborValue::Map(vec![]),
225        CborValue::Bytes(payload),
226        CborValue::Array(vec![
227            signature_entry(ed_protected, ed_signature),
228            signature_entry(pq_protected, pq_signature),
229        ]),
230    ]);
231    encode(&cose)
232}
233
234fn validate_kid(kid: &[u8], name: &str) -> Result<()> {
235    if kid.is_empty() || kid.len() > MAX_KID_BYTES {
236        bail!("request proof: {name} kid must be 1..{MAX_KID_BYTES} bytes");
237    }
238    Ok(())
239}
240
241fn encode_body_protected(ed_kid: &[u8], pq_kid: &[u8]) -> Result<Vec<u8>> {
242    // Key order is RFC 8949 deterministic bytewise order: 2, 16, -70100, -70101.
243    encode(&CborValue::Map(vec![
244        (
245            CborValue::Integer(COSE_HEADER_CRIT.into()),
246            CborValue::Array(vec![
247                CborValue::Integer(HEADER_HS_SIGNATURE_PLAN.into()),
248                CborValue::Integer(HEADER_HS_DOMAIN.into()),
249            ]),
250        ),
251        (
252            CborValue::Integer(COSE_HEADER_TYP.into()),
253            CborValue::Text(PROOF_TYP.into()),
254        ),
255        (
256            CborValue::Integer(HEADER_HS_DOMAIN.into()),
257            CborValue::Text(REQUEST_PROOF_DOMAIN.into()),
258        ),
259        (
260            CborValue::Integer(HEADER_HS_SIGNATURE_PLAN.into()),
261            signature_plan(ed_kid, pq_kid),
262        ),
263    ]))
264}
265
266fn signature_plan(ed_kid: &[u8], pq_kid: &[u8]) -> CborValue {
267    CborValue::Array(vec![CborValue::Map(vec![
268        (CborValue::Integer(1.into()), CborValue::Integer(1.into())),
269        (
270            CborValue::Integer(2.into()),
271            CborValue::Text(SUITE_HYBRID.into()),
272        ),
273        (
274            CborValue::Integer(3.into()),
275            CborValue::Array(vec![
276                component(ALG_ED25519, ed_kid),
277                component(ALG_ML_DSA_65, pq_kid),
278            ]),
279        ),
280    ])])
281}
282
283fn component(alg: i64, kid: &[u8]) -> CborValue {
284    CborValue::Map(vec![
285        (CborValue::Integer(1.into()), CborValue::Integer(alg.into())),
286        (CborValue::Integer(2.into()), CborValue::Bytes(kid.to_vec())),
287    ])
288}
289
290fn encode_signature_protected(alg: i64, kid: &[u8]) -> Result<Vec<u8>> {
291    // Key order is 1, 2, 4, -70102.
292    encode(&CborValue::Map(vec![
293        (
294            CborValue::Integer(COSE_HEADER_ALG.into()),
295            CborValue::Integer(alg.into()),
296        ),
297        (
298            CborValue::Integer(COSE_HEADER_CRIT.into()),
299            CborValue::Array(vec![CborValue::Integer(
300                HEADER_HS_LOGICAL_SIGNER_GROUP.into(),
301            )]),
302        ),
303        (
304            CborValue::Integer(COSE_HEADER_KID.into()),
305            CborValue::Bytes(kid.to_vec()),
306        ),
307        (
308            CborValue::Integer(HEADER_HS_LOGICAL_SIGNER_GROUP.into()),
309            CborValue::Integer(1.into()),
310        ),
311    ]))
312}
313
314fn encode_claims(
315    input: &AuthenticatedRequestProofInput<'_>,
316    credential_hash: CredentialHash,
317    request_id: RequestId,
318) -> Result<Vec<u8>> {
319    // Key order is 3, 4, 6, 7, -70001, -70002, -70003, -70004, -70009.
320    let mut claims = vec![
321        (
322            CborValue::Integer(CWT_CLAIM_AUD.into()),
323            CborValue::Text(input.service_domain.into()),
324        ),
325        (
326            CborValue::Integer(CWT_CLAIM_EXP.into()),
327            CborValue::Integer(input.expires_at.into()),
328        ),
329        (
330            CborValue::Integer(CWT_CLAIM_IAT.into()),
331            CborValue::Integer(input.issued_at.into()),
332        ),
333        (
334            CborValue::Integer(CWT_CLAIM_CTI.into()),
335            CborValue::Bytes(request_id.to_vec()),
336        ),
337        (
338            CborValue::Integer(CLAIM_CREDENTIAL_HASH.into()),
339            CborValue::Bytes(credential_hash.to_vec()),
340        ),
341        (
342            CborValue::Integer(CLAIM_CAPNP_SCHEMA_ID.into()),
343            CborValue::Integer(input.capnp_schema_id.into()),
344        ),
345        (
346            CborValue::Integer(CLAIM_CAPNP_BODY_BYTES.into()),
347            CborValue::Bytes(input.capnp_body.to_vec()),
348        ),
349        (
350            CborValue::Integer(CLAIM_RESPONSE_BINDING.into()),
351            response_binding_value(input.response_binding)?,
352        ),
353    ];
354    if let Some(binding) = input.federate_recipient_binding {
355        claims.push((
356            CborValue::Integer(CLAIM_FEDERATE_RECIPIENT_BINDING.into()),
357            federate_recipient_binding_value(binding),
358        ));
359    }
360    encode(&CborValue::Map(claims))
361}
362
363fn federate_recipient_binding_value(binding: &FederateRecipientBinding) -> CborValue {
364    let commitment_value = |value: &Option<[u8; 32]>| match value {
365        Some(value) => CborValue::Bytes(value.to_vec()),
366        None => CborValue::Null,
367    };
368    CborValue::Map(vec![
369        (
370            CborValue::Integer(1.into()),
371            commitment_value(&binding.response),
372        ),
373        (
374            CborValue::Integer(2.into()),
375            commitment_value(&binding.stream),
376        ),
377        (
378            CborValue::Integer(3.into()),
379            commitment_value(&binding.client_dh_public),
380        ),
381    ])
382}
383
384fn response_binding_value(binding: Option<&ResponseBinding>) -> Result<CborValue> {
385    let Some(binding) = binding else {
386        return Ok(CborValue::Null);
387    };
388    let response_kind = match binding.response_kind {
389        ResponseKind::Unary => 1,
390        ResponseKind::StreamSetup => 2,
391    };
392    let protection_mode = match binding.protection_mode {
393        ProtectionMode::Cleartext => 1,
394        ProtectionMode::Encrypted => 2,
395    };
396    let recipient = match &binding.kem_recipient {
397        None => CborValue::Null,
398        Some(KemRecipient {
399            alg,
400            encapsulation_key,
401            kid,
402        }) => CborValue::Map(vec![
403            (
404                CborValue::Integer(1.into()),
405                CborValue::Integer((*alg).into()),
406            ),
407            (
408                CborValue::Integer(2.into()),
409                CborValue::Bytes(encapsulation_key.clone()),
410            ),
411            (CborValue::Integer(3.into()), CborValue::Bytes(kid.clone())),
412        ]),
413    };
414    let value = CborValue::Map(vec![
415        (
416            CborValue::Integer(1.into()),
417            CborValue::Integer(binding.root_type_id.into()),
418        ),
419        (
420            CborValue::Integer(2.into()),
421            CborValue::Integer(response_kind.into()),
422        ),
423        (
424            CborValue::Integer(3.into()),
425            CborValue::Integer(protection_mode.into()),
426        ),
427        (CborValue::Integer(4.into()), recipient),
428    ]);
429    // Reuse the frozen response-binding validator rather than duplicating its
430    // cross-field rules while emitting a map the parser would reject.
431    ResponseBinding::decode(&value)?;
432    Ok(value)
433}
434
435fn signature_structure(
436    body_protected: &[u8],
437    signer_protected: &[u8],
438    payload: &[u8],
439) -> Result<Vec<u8>> {
440    // RFC 9052 Sig_structure for COSE_Sign; external_aad is explicitly empty
441    // in the frozen profile.
442    encode(&CborValue::Array(vec![
443        CborValue::Text("Signature".into()),
444        CborValue::Bytes(body_protected.to_vec()),
445        CborValue::Bytes(signer_protected.to_vec()),
446        CborValue::Bytes(Vec::new()),
447        CborValue::Bytes(payload.to_vec()),
448    ]))
449}
450
451fn signature_entry(protected: Vec<u8>, signature: Vec<u8>) -> CborValue {
452    CborValue::Array(vec![
453        CborValue::Bytes(protected),
454        CborValue::Map(vec![]),
455        CborValue::Bytes(signature),
456    ])
457}
458
459fn encode(value: &CborValue) -> Result<Vec<u8>> {
460    let mut out = Vec::new();
461    ciborium::ser::into_writer(value, &mut out)
462        .map_err(|e| anyhow::anyhow!("request proof: CBOR encode failed: {e}"))?;
463    super::cbor_audit::audit_deterministic(&out)?;
464    Ok(out)
465}
466
467#[cfg(test)]
468#[allow(clippy::expect_used, clippy::unwrap_used)]
469mod tests {
470    use super::*;
471    use crate::proof::{
472        enrollment::{
473            ComponentKey, EnrolledComponent, InMemoryEnrollmentResolver, SignerRole,
474            SignerSuiteRecord,
475        },
476        parser::ParsedProof,
477        verify::verify_proof_signatures,
478        ProofDisposition,
479    };
480
481    const NOW: u64 = 1_800_000_000;
482    const SCHEMA: u64 = 0xd4d0_f2a1_b3c5_8e67;
483
484    fn fixture() -> (
485        AuthenticatedHybridProofSigner,
486        InMemoryEnrollmentResolver,
487        ed25519_dalek::VerifyingKey,
488    ) {
489        let ed = ed25519_dalek::SigningKey::from_bytes(&[9; 32]);
490        let pq = crate::crypto::pq::ml_dsa_sk_from_seed(&[10; 32]);
491        let cnf = ed.verifying_key();
492        let signer = AuthenticatedHybridProofSigner::new(
493            ed,
494            b"proof-fixture-ed".to_vec(),
495            pq,
496            b"proof-fixture-pq".to_vec(),
497        )
498        .unwrap();
499        let mut resolver = InMemoryEnrollmentResolver::new();
500        resolver
501            .enrol_primary(
502                &cnf,
503                SignerSuiteRecord {
504                    principal: "fixture-direct-self".into(),
505                    suite_id: SUITE_HYBRID.into(),
506                    components: vec![
507                        EnrolledComponent::new(
508                            b"proof-fixture-ed".to_vec(),
509                            ComponentKey::Ed25519(cnf),
510                        ),
511                        EnrolledComponent::new(
512                            b"proof-fixture-pq".to_vec(),
513                            ComponentKey::MlDsa65(Box::new(crate::crypto::pq::ml_dsa_sk_to_vk(
514                                &signer.ml_dsa_65,
515                            ))),
516                        ),
517                    ],
518                    epoch: 7,
519                    role: SignerRole::Primary,
520                    approver_role: None,
521                    enrollment_policy_id: "fixture-proof-only".into(),
522                    not_after: NOW + 600,
523                    revoked: false,
524                },
525            )
526            .unwrap();
527        (signer, resolver, cnf)
528    }
529
530    fn input<'a>(body: &'a [u8]) -> AuthenticatedRequestProofInput<'a> {
531        AuthenticatedRequestProofInput {
532            service_domain: "registry.svc.hyprstream.test",
533            credential: b"fixture.sender.constrained.jwt",
534            issued_at: NOW - 5,
535            expires_at: NOW + 30,
536            capnp_schema_id: SCHEMA,
537            capnp_body: body,
538            response_binding: None,
539            federate_recipient_binding: None,
540        }
541    }
542
543    fn mutate_payload(
544        bytes: &[u8],
545        change: impl FnOnce(&mut Vec<(CborValue, CborValue)>),
546    ) -> Vec<u8> {
547        let mut outer: CborValue =
548            ciborium::de::from_reader(&mut std::io::Cursor::new(bytes)).unwrap();
549        let CborValue::Array(ref mut fields) = outer else {
550            panic!("COSE is array");
551        };
552        let CborValue::Bytes(ref mut payload) = fields[2] else {
553            panic!("payload is bytes");
554        };
555        let mut claims: CborValue =
556            ciborium::de::from_reader(&mut std::io::Cursor::new(&*payload)).unwrap();
557        let CborValue::Map(ref mut map) = claims else {
558            panic!("claims map");
559        };
560        change(map);
561        *payload = encode(&claims).unwrap();
562        encode(&outer).unwrap()
563    }
564
565    #[test]
566    fn producer_round_trips_through_real_parser_verifier_and_envelope_slot() {
567        let (signer, resolver, cnf) = fixture();
568        let body = b"canonical-capnp-request";
569        let bytes = build_authenticated_hybrid_request_proof(&input(body), &signer).unwrap();
570        let proof = ParsedProof::parse(&bytes).unwrap();
571        assert_eq!(proof.disposition, ProofDisposition::Authenticated);
572        assert_eq!(proof.claims.aud, "registry.svc.hyprstream.test");
573        assert_eq!(proof.claims.capnp_schema_id, SCHEMA);
574        assert_eq!(proof.claims.capnp_body_bytes, body);
575        assert_eq!(proof.plan.groups.len(), 1);
576        assert_eq!(proof.plan.groups[0].suite_id, SUITE_HYBRID);
577        assert_eq!(
578            proof.plan.groups[0]
579                .components
580                .iter()
581                .map(|component| component.alg)
582                .collect::<Vec<_>>(),
583            vec![ALG_ED25519, ALG_ML_DSA_65],
584            "WNS component order is frozen: Ed25519 then ML-DSA-65"
585        );
586        assert_eq!(
587            proof.claims.credential_hash,
588            Some(Sha256::digest(input(body).credential).into())
589        );
590        verify_proof_signatures(&proof, Some(&cnf), Some(&resolver), NOW).unwrap();
591
592        let envelope = crate::envelope::RequestEnvelope::new(body.to_vec())
593            .with_service_domain("registry.svc.hyprstream.test")
594            .unwrap()
595            .with_proof_cwt(bytes.clone());
596        assert_eq!(envelope.proof_cwt.as_deref(), Some(bytes.as_slice()));
597    }
598
599    #[test]
600    fn federate_recipient_extension_is_rejected_by_generic_profile_parser() {
601        let (signer, _, _) = fixture();
602        let suite = crate::crypto::hybrid_kem::SuiteId::HyKemX25519MlKem768;
603        let response = crate::crypto::hybrid_kem::generate_recipient(suite).unwrap();
604        let stream = crate::crypto::hybrid_kem::generate_recipient(suite).unwrap();
605        let binding = FederateRecipientBinding::from_recipients(
606            Some(&response.public()),
607            Some(&stream.public()),
608            Some([0x33; 32]),
609        )
610        .unwrap();
611        let mut request = input(b"federate-request");
612        request.federate_recipient_binding = Some(&binding);
613        let bytes = build_authenticated_hybrid_request_proof(&request, &signer).unwrap();
614
615        assert!(
616            ParsedProof::parse(&bytes).is_err(),
617            "generic v16 parsing must keep the frozen closed claim set"
618        );
619        assert!(
620            ParsedProof::parse_deferred_federate_request(&bytes).is_ok(),
621            "only the deferred Federate parser accepts -70009"
622        );
623    }
624
625    #[test]
626    fn federate_signed_proof_vector_is_stable_and_profile_isolated() {
627        use crate::crypto::hybrid_kem::{recipient_from_seeds, SuiteId};
628
629        let (signer, resolver, cnf) = fixture();
630        let suite = SuiteId::HyKemX25519MlKem768;
631        let response = recipient_from_seeds(suite, &[&[7; 32], &[9; 64]])
632            .unwrap()
633            .public();
634        let stream = recipient_from_seeds(suite, &[&[8; 32], &[10; 64]])
635            .unwrap()
636            .public();
637        let binding = FederateRecipientBinding::from_recipients(
638            Some(&response),
639            Some(&stream),
640            Some([0x5a; 32]),
641        )
642        .unwrap();
643        let mut request = input(b"federate-proof-vector-v1");
644        request.federate_recipient_binding = Some(&binding);
645        let bytes = build_authenticated_hybrid_request_proof_with_id(
646            &request,
647            &signer,
648            [0x3c; super::super::REQUEST_ID_SIZE],
649        )
650        .unwrap();
651        let browser_style_signer = crate::signer::LocalSigner::new(signer.ed25519.clone())
652            .with_pq_key(crate::crypto::pq::ml_dsa_sk_from_seed(&[10; 32]));
653        let browser_style_bytes = futures::executor::block_on(
654            build_authenticated_hybrid_request_proof_with_signer_and_id(
655                &request,
656                &browser_style_signer,
657                b"proof-fixture-ed",
658                b"proof-fixture-pq",
659                [0x3c; super::super::REQUEST_ID_SIZE],
660            ),
661        )
662        .unwrap();
663        assert_eq!(
664            browser_style_bytes, bytes,
665            "external browser signer must emit the native COSE bytes"
666        );
667        let proof = ParsedProof::parse_deferred_federate_request(&bytes).unwrap();
668        assert_eq!(proof.claims.federate_recipient_binding, Some(binding));
669        assert!(ParsedProof::parse(&bytes).is_err());
670        verify_proof_signatures(&proof, Some(&cnf), Some(&resolver), NOW).unwrap();
671        assert_eq!(
672            hex::encode(Sha256::digest(&bytes)),
673            "186b33dad6d4b41ed750b0d05e408dcaa78e708c33abac7bf4c2778bcf6826d6"
674        );
675
676        let omitted = mutate_payload(&bytes, |claims| {
677            claims.retain(|(key, _)| {
678                *key != CborValue::Integer(CLAIM_FEDERATE_RECIPIENT_BINDING.into())
679            });
680        });
681        assert!(ParsedProof::parse_deferred_federate_request(&omitted).is_err());
682
683        let substituted = mutate_payload(&bytes, |claims| {
684            let (_, CborValue::Map(fields)) = claims
685                .iter_mut()
686                .find(|(key, _)| {
687                    *key == CborValue::Integer(CLAIM_FEDERATE_RECIPIENT_BINDING.into())
688                })
689                .unwrap()
690            else {
691                panic!("Federate recipient map missing")
692            };
693            fields[0].1 = CborValue::Bytes(vec![0xff; 32]);
694        });
695        let changed = ParsedProof::parse_deferred_federate_request(&substituted).unwrap();
696        assert!(!changed
697            .claims
698            .federate_recipient_binding
699            .as_ref()
700            .unwrap()
701            .matches(Some(&response), Some(&stream), Some([0x5a; 32])));
702        assert!(verify_proof_signatures(&changed, Some(&cnf), Some(&resolver), NOW).is_err());
703    }
704
705    #[cfg(not(target_arch = "wasm32"))]
706    #[test]
707    fn external_signer_rejects_wrong_callback_signature() {
708        struct WrongSigner(crate::signer::LocalSigner);
709
710        #[async_trait::async_trait]
711        impl crate::transport_traits::Signer for WrongSigner {
712            fn pubkey(&self) -> [u8; 32] {
713                self.0.pubkey()
714            }
715
716            async fn sign(&self, _message: &[u8]) -> Result<[u8; 64]> {
717                Ok([0; 64])
718            }
719
720            fn pq_pubkey(&self) -> Option<Vec<u8>> {
721                self.0.pq_pubkey()
722            }
723
724            async fn pq_sign(&self, message: &[u8]) -> Result<Option<Vec<u8>>> {
725                self.0.pq_sign(message).await
726            }
727        }
728
729        let signer = WrongSigner(
730            crate::signer::LocalSigner::new(ed25519_dalek::SigningKey::from_bytes(&[9; 32]))
731                .with_pq_key(crate::crypto::pq::ml_dsa_sk_from_seed(&[10; 32])),
732        );
733        let binding = FederateRecipientBinding {
734            response: None,
735            stream: None,
736            client_dh_public: None,
737        };
738        let mut request = input(b"callback-body");
739        request.federate_recipient_binding = Some(&binding);
740        let result = futures::executor::block_on(
741            build_authenticated_hybrid_request_proof_with_signer_and_id(
742                &request,
743                &signer,
744                b"proof-fixture-ed",
745                b"proof-fixture-pq",
746                [0x3c; super::super::REQUEST_ID_SIZE],
747            ),
748        );
749        assert!(
750            result.is_err(),
751            "a callback that signs other bytes must fail closed"
752        );
753    }
754
755    #[test]
756    fn causal_mutations_are_rejected_by_parser_or_real_verifier() {
757        let (signer, resolver, cnf) = fixture();
758        let bytes = build_authenticated_hybrid_request_proof(&input(b"body"), &signer).unwrap();
759
760        let altered_body = mutate_payload(&bytes, |map| {
761            map.iter_mut()
762                .find(|(k, _)| *k == CborValue::Integer(CLAIM_CAPNP_BODY_BYTES.into()))
763                .unwrap()
764                .1 = CborValue::Bytes(b"other".to_vec());
765        });
766        let altered_credential = mutate_payload(&bytes, |map| {
767            map.iter_mut()
768                .find(|(k, _)| *k == CborValue::Integer(CLAIM_CREDENTIAL_HASH.into()))
769                .unwrap()
770                .1 = CborValue::Bytes([0x42; 32].to_vec());
771        });
772        let altered_audience = mutate_payload(&bytes, |map| {
773            map.iter_mut()
774                .find(|(k, _)| *k == CborValue::Integer(CWT_CLAIM_AUD.into()))
775                .unwrap()
776                .1 = CborValue::Text("policy.svc.hyprstream.test".into());
777        });
778        for altered in [altered_body, altered_credential, altered_audience] {
779            let proof = ParsedProof::parse(&altered).unwrap();
780            assert!(verify_proof_signatures(&proof, Some(&cnf), Some(&resolver), NOW).is_err());
781        }
782
783        let mut stripped: CborValue =
784            ciborium::de::from_reader(&mut std::io::Cursor::new(&bytes)).unwrap();
785        let CborValue::Array(ref mut fields) = stripped else {
786            panic!("COSE array");
787        };
788        let CborValue::Array(ref mut signatures) = fields[3] else {
789            panic!("signatures");
790        };
791        signatures.pop();
792        assert!(ParsedProof::parse(&encode(&stripped).unwrap()).is_err());
793
794        let proof = ParsedProof::parse(&bytes).unwrap();
795        let wrong_key = ed25519_dalek::SigningKey::from_bytes(&[99; 32]).verifying_key();
796        assert!(verify_proof_signatures(&proof, Some(&wrong_key), Some(&resolver), NOW).is_err());
797        assert!(verify_proof_signatures(&proof, Some(&cnf), Some(&resolver), NOW + 31).is_err());
798    }
799
800    #[test]
801    fn producer_rejects_oversize_but_leaves_w1_freshness_to_verifier() {
802        let (signer, _, _) = fixture();
803        let oversized = vec![0; MAX_BODY_BYTES + 1];
804        assert!(build_authenticated_hybrid_request_proof(&input(&oversized), &signer).is_err());
805    }
806
807    #[test]
808    fn producer_parser_verifier_preserve_injected_clock_w1_boundaries() {
809        let cases = [
810            (NOW - 30, NOW + 300, None),
811            (NOW + 30, NOW + 1, None),
812            (NOW, NOW, Some("proof expired:")),
813            (
814                NOW - 31,
815                NOW + 30,
816                Some("proof iat out of verifier-clock skew:"),
817            ),
818            (NOW, NOW + 301, Some("proof over-lifetime:")),
819        ];
820
821        for (issued_at, expires_at, expected_error) in cases {
822            let (signer, resolver, cnf) = fixture();
823            let mut request = input(b"w1-boundary-body");
824            request.issued_at = issued_at;
825            request.expires_at = expires_at;
826            let bytes = build_authenticated_hybrid_request_proof(&request, &signer)
827                .expect("producer accepts caller-supplied timestamps");
828            let proof = ParsedProof::parse(&bytes).expect("parser accepts producer output");
829            let result = verify_proof_signatures(&proof, Some(&cnf), Some(&resolver), NOW);
830
831            match expected_error {
832                None => {
833                    result.expect("verifier accepts W1 boundary");
834                }
835                Some(expected) => {
836                    let error = result
837                        .expect_err("verifier rejects W1 negative")
838                        .to_string();
839                    assert!(
840                        error.contains(expected),
841                        "expected verifier reason {expected:?}, got {error:?}"
842                    );
843                }
844            }
845        }
846    }
847}