Skip to main content

hyprstream_rpc/
envelope.rs

1//! Request envelope for RPC with Ed25519 signatures and E2E integrity.
2//!
3//! Every RPC request is wrapped in a `SignedEnvelope` that carries:
4//! - A unique request ID for correlation
5//! - The serialized inner request payload
6//! - Authorization context (local claims, federated JWT, or ID-JAG)
7//! - Ed25519 signature over the entire RequestEnvelope
8//! - Nonce + timestamp (iat) for replay protection
9//!
10//! # Two-Layer Security
11//!
12//! | Layer | Mechanism | Purpose |
13//! |-------|-----------|---------|
14//! | Transport | CURVE/QUIC-TLS | Encrypts connection, authenticates immediate peer |
15//! | Application | Signed envelope | E2E integrity through brokers, authenticates originator |
16//!
17//! # Envelope Structure
18//!
19//! ```text
20//! SignedEnvelope {
21//!     envelope: RequestEnvelope {
22//!         request_id, payload, iat, nonce,
23//!         authorization, delegation_token, wth
24//!     },
25//!     sig,  // Ed25519 signature over canonical(envelope)
26//!     cnf,  // Ed25519 public key (RFC 7800 confirmation key)
27//! }
28//! ```
29
30use crate::auth::Claims;
31use crate::capnp::{FromCapnp, ToCapnp};
32use crate::common_capnp;
33use crate::crypto::{SigningKey, VerifyingKey};
34use crate::error::{EnvelopeError, EnvelopeResult};
35use anyhow::{anyhow, Result};
36use ed25519_dalek::Signer;
37use std::fmt;
38use std::str::FromStr;
39use std::sync::atomic::{AtomicU64, Ordering};
40#[cfg(not(target_arch = "wasm32"))]
41use std::time::{SystemTime, UNIX_EPOCH};
42use subtle::ConstantTimeEq;
43
44// ============================================================================
45// Authorization (new envelope auth model)
46// ============================================================================
47
48/// Authorization context carried inside a `RequestEnvelope`.
49///
50/// Replaces the legacy `identity` + `jwt_token` + `claims` fields.
51#[derive(Debug, Clone, PartialEq, Eq, Default)]
52pub enum Authorization {
53    /// No authorization context.
54    #[default]
55    None,
56    /// Locally-issued verified token claims.
57    Local(TokenClaims),
58    /// Token from a foreign (federated) issuer.
59    Federated(FederatedToken),
60    /// Opaque identity JAG string.
61    IdJag(String),
62}
63
64/// Verified token claims (local issuer).
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct TokenClaims {
67    pub iss: String,
68    pub sub: String,
69    pub aud: Vec<String>,
70    pub exp: i64,
71    pub iat: i64,
72    pub jti: String,
73    pub scope: Vec<crate::auth::scope::Scope>,
74    pub cnf_jkt: String,
75}
76
77/// Federated token from a foreign issuer.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct FederatedToken {
80    pub raw: String,
81    pub claims: TokenClaims,
82    pub dpop_proof: Option<String>,
83}
84
85// Cap'n Proto impls for new Authorization types
86
87impl ToCapnp for TokenClaims {
88    type Builder<'a> = common_capnp::token_claims::Builder<'a>;
89
90    fn write_to(&self, builder: &mut Self::Builder<'_>) {
91        builder.set_iss(&self.iss);
92        builder.set_sub(&self.sub);
93        {
94            let mut aud_builder = builder.reborrow().init_aud(self.aud.len() as u32);
95            for (i, a) in self.aud.iter().enumerate() {
96                aud_builder.set(i as u32, a);
97            }
98        }
99        builder.set_exp(self.exp);
100        builder.set_iat(self.iat);
101        builder.set_jti(&self.jti);
102        {
103            let mut scope_builder = builder.reborrow().init_scope(self.scope.len() as u32);
104            for (i, s) in self.scope.iter().enumerate() {
105                let mut sb = scope_builder.reborrow().get(i as u32);
106                s.write_to(&mut sb);
107            }
108        }
109        builder.set_cnf_jkt(&self.cnf_jkt);
110    }
111}
112
113impl FromCapnp for TokenClaims {
114    type Reader<'a> = common_capnp::token_claims::Reader<'a>;
115
116    fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
117        let aud_reader = reader.get_aud()?;
118        let mut aud = Vec::with_capacity(aud_reader.len() as usize);
119        for i in 0..aud_reader.len() {
120            aud.push(aud_reader.get(i)?.to_str()?.to_owned());
121        }
122
123        let scope_reader = reader.get_scope()?;
124        let mut scope = Vec::with_capacity(scope_reader.len() as usize);
125        for i in 0..scope_reader.len() {
126            scope.push(crate::auth::scope::Scope::read_from(scope_reader.get(i))?);
127        }
128
129        Ok(Self {
130            iss: reader.get_iss()?.to_str()?.to_owned(),
131            sub: reader.get_sub()?.to_str()?.to_owned(),
132            aud,
133            exp: reader.get_exp(),
134            iat: reader.get_iat(),
135            jti: reader.get_jti()?.to_str()?.to_owned(),
136            scope,
137            cnf_jkt: reader.get_cnf_jkt()?.to_str()?.to_owned(),
138        })
139    }
140}
141
142impl ToCapnp for FederatedToken {
143    type Builder<'a> = common_capnp::federated_token::Builder<'a>;
144
145    fn write_to(&self, builder: &mut Self::Builder<'_>) {
146        builder.set_raw(&self.raw);
147        self.claims.write_to(&mut builder.reborrow().init_claims());
148        if let Some(ref proof) = self.dpop_proof {
149            builder.set_dpop_proof(proof);
150        }
151    }
152}
153
154impl FromCapnp for FederatedToken {
155    type Reader<'a> = common_capnp::federated_token::Reader<'a>;
156
157    fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
158        let dpop_proof = if reader.has_dpop_proof() {
159            let p = reader.get_dpop_proof()?.to_str()?;
160            if p.is_empty() {
161                None
162            } else {
163                Some(p.to_owned())
164            }
165        } else {
166            None
167        };
168        Ok(Self {
169            raw: reader.get_raw()?.to_str()?.to_owned(),
170            claims: TokenClaims::read_from(reader.get_claims()?)?,
171            dpop_proof,
172        })
173    }
174}
175
176impl ToCapnp for Authorization {
177    type Builder<'a> = common_capnp::authorization::Builder<'a>;
178
179    fn write_to(&self, builder: &mut Self::Builder<'_>) {
180        match self {
181            Self::None => builder.set_none(()),
182            Self::Local(claims) => {
183                claims.write_to(&mut builder.reborrow().init_local());
184            }
185            Self::Federated(token) => {
186                token.write_to(&mut builder.reborrow().init_federated());
187            }
188            Self::IdJag(jag) => {
189                builder.set_id_jag(jag);
190            }
191        }
192    }
193}
194
195impl FromCapnp for Authorization {
196    type Reader<'a> = common_capnp::authorization::Reader<'a>;
197
198    fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
199        use common_capnp::authorization::Which;
200        match reader.which()? {
201            Which::None(()) => Ok(Self::None),
202            Which::Local(r) => Ok(Self::Local(TokenClaims::read_from(r?)?)),
203            Which::Federated(r) => Ok(Self::Federated(FederatedToken::read_from(r?)?)),
204            Which::IdJag(r) => {
205                let token = r?;
206                // Type-confusion separation (§4.2, vector N-2): a proof CWT
207                // presented in the credential/authorization slot is refused
208                // here, before any issuer key is resolved, on every transport
209                // that carries this envelope.
210                if crate::proof::is_proof_typed_credential(token.as_bytes()) {
211                    anyhow::bail!("authorization slot carries a proof CWT, not a credential");
212                }
213                Ok(Self::IdJag(token.to_str()?.to_owned()))
214            }
215        }
216    }
217}
218
219/// Cap'n Proto reader options with bounded traversal limits to prevent DoS.
220fn envelope_reader_options() -> capnp::message::ReaderOptions {
221    let mut opts = capnp::message::ReaderOptions::new();
222    opts.traversal_limit_in_words(Some(131_072)); // 1 MiB
223    opts.nesting_limit(64);
224    opts
225}
226
227/// Parse exactly one bounded Cap'n Proto message from an already-buffered
228/// frame without allocating storage based on its unauthenticated segment
229/// table. The no-allocation reader validates declared segment sizes against
230/// both the traversal limit and the supplied slice before exposing a root.
231fn read_exact_envelope_message(
232    bytes: &[u8],
233) -> Result<capnp::message::Reader<capnp::serialize::NoAllocSliceSegments<'_>>> {
234    let mut remaining = bytes;
235    let reader = capnp::serialize::read_message_from_flat_slice_no_alloc(
236        &mut remaining,
237        envelope_reader_options(),
238    )?;
239    if !remaining.is_empty() {
240        return Err(anyhow!(
241            "trailing bytes after Cap'n Proto envelope: {}",
242            remaining.len()
243        ));
244    }
245    Ok(reader)
246}
247
248// ============================================================================
249// Envelope Unwrap Options
250// ============================================================================
251
252/// How to verify the envelope signer.
253pub enum EnvelopeVerification<'a> {
254    /// Require the envelope signer to match this specific verifying key.
255    FixedSigner(&'a VerifyingKey),
256    /// Accept any valid Ed25519 signer (self-signed).
257    AnySigner,
258}
259
260/// Options controlling envelope unwrap, verification, and optional decryption.
261///
262/// # Crypto policy (fail-closed default)
263///
264/// `verify_policy` defaults to [`CryptoPolicy::default()`] which is **Hybrid
265/// ENFORCED**. Under Hybrid the verifier REQUIRES the outer ML-DSA-65 SNS layer
266/// anchored to a [`PqTrustStore`] entry — stripping the outer layer or signing
267/// classical-only is rejected. To verify against a kid-anchored PQ key, callers
268/// MUST supply `pq_store`; under Hybrid with no resolvable anchor the envelope
269/// is **rejected** (fail-closed), never accepted as classical.
270///
271pub struct UnwrapOptions<'a> {
272    /// How to verify the envelope signer.
273    pub verification: EnvelopeVerification<'a>,
274    /// Nonce cache for replay protection.
275    pub nonce_cache: &'a dyn NonceCache,
276    /// Server signing key for decrypting encrypted envelopes.
277    /// When present and the envelope has `encrypted_envelope`, the server's
278    /// Ed25519 key is converted to X25519 for DH decryption.
279    pub decryption_key: Option<&'a crate::crypto::SigningKey>,
280    /// Require the verified wire envelope to carry a non-empty encrypted
281    /// envelope. Enforced after signature verification and before decryption,
282    /// the final replay commit, or any claims/application processing.
283    pub require_encrypted: bool,
284    /// kid-anchored ML-DSA-65 trust store used to resolve the PQ verifying key
285    /// for the envelope's EdDSA signer. Required under Hybrid policy.
286    pub pq_store: Option<&'a dyn PqTrustStore>,
287    /// Verification policy enforced at this site. Defaults to Hybrid (enforced).
288    pub verify_policy: crate::crypto::CryptoPolicy,
289}
290
291impl<'a> UnwrapOptions<'a> {
292    /// Fixed-signer verification under the default (Hybrid-enforced) policy.
293    pub fn fixed_signer(pubkey: &'a VerifyingKey, nonce_cache: &'a dyn NonceCache) -> Self {
294        Self {
295            verification: EnvelopeVerification::FixedSigner(pubkey),
296            nonce_cache,
297            decryption_key: None,
298            require_encrypted: false,
299            pq_store: None,
300            verify_policy: crate::crypto::CryptoPolicy::default(),
301        }
302    }
303
304    /// Any-signer verification under the default (Hybrid-enforced) policy.
305    pub fn any_signer(nonce_cache: &'a dyn NonceCache) -> Self {
306        Self {
307            verification: EnvelopeVerification::AnySigner,
308            nonce_cache,
309            decryption_key: None,
310            require_encrypted: false,
311            pq_store: None,
312            verify_policy: crate::crypto::CryptoPolicy::default(),
313        }
314    }
315
316    pub fn with_decryption_key(mut self, key: &'a crate::crypto::SigningKey) -> Self {
317        self.decryption_key = Some(key);
318        self
319    }
320
321    /// Require request encryption after authenticating the wire envelope.
322    pub fn require_encrypted(mut self, required: bool) -> Self {
323        self.require_encrypted = required;
324        self
325    }
326
327    /// Attach a kid-anchored ML-DSA-65 trust store (required under Hybrid).
328    pub fn with_pq_store(mut self, store: &'a dyn PqTrustStore) -> Self {
329        self.pq_store = Some(store);
330        self
331    }
332
333    /// Set the verification policy explicitly.
334    pub fn with_verify_policy(mut self, policy: crate::crypto::CryptoPolicy) -> Self {
335        self.verify_policy = policy;
336        self
337    }
338}
339
340/// Global request ID counter for unique IDs
341static REQUEST_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
342
343/// Generate a unique request ID
344pub fn next_request_id() -> u64 {
345    REQUEST_ID_COUNTER.fetch_add(1, Ordering::Relaxed)
346}
347
348/// Get current Unix timestamp in milliseconds.
349/// Used for envelope timestamp validation.
350pub fn current_timestamp() -> i64 {
351    #[cfg(target_arch = "wasm32")]
352    {
353        // In WASM, SystemTime::now() is not available.
354        // Use js_sys::Date::now() which returns milliseconds as f64.
355        js_sys::Date::now() as i64
356    }
357    #[cfg(not(target_arch = "wasm32"))]
358    {
359        // SAFETY: Only fails if system time is before Unix epoch (1970)
360        // Cap at i64::MAX (won't overflow for ~292 million years)
361        SystemTime::now()
362            .duration_since(UNIX_EPOCH)
363            .map(|d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
364            .unwrap_or(0)
365    }
366}
367
368/// Generate a random 16-byte nonce for replay protection.
369///
370/// Retained for the active legacy envelope path. Will be removed when the
371/// v16 proof-CWT `cti` replay admission fully replaces it.
372pub fn generate_nonce() -> [u8; 16] {
373    use rand::Rng;
374    rand::rngs::OsRng.gen()
375}
376
377/// Authorization subject for Casbin policy checks and resource isolation.
378///
379/// A simple newtype over `Option<String>`:
380/// - `Some(name)` = authenticated user with bare username
381/// - `None` = anonymous (unauthenticated)
382///
383/// All identity types (Local, ApiToken, Peer, Claims) produce bare usernames.
384/// There are no namespace prefixes — a user named "alice" is just "alice"
385/// regardless of how they authenticated.
386///
387/// # Display
388///
389/// `Subject::new("alice")` displays as `"alice"`, used directly
390/// as the Casbin subject string. Anonymous displays as `"anonymous"`.
391///
392/// # Validation
393///
394/// `validate()` ensures names contain only `[a-zA-Z0-9._-]`.
395#[derive(Debug, Clone, PartialEq, Eq, Hash)]
396pub struct Subject(Option<String>);
397
398impl Subject {
399    /// Create an authenticated subject with the given username.
400    pub fn new(name: impl Into<String>) -> Self {
401        Self(Some(name.into()))
402    }
403
404    /// Create an anonymous (unauthenticated) subject.
405    pub fn anonymous() -> Self {
406        Self(None)
407    }
408
409    /// Get the username, if authenticated.
410    pub fn name(&self) -> Option<&str> {
411        self.0.as_deref()
412    }
413
414    /// Check if this subject is anonymous.
415    pub fn is_anonymous(&self) -> bool {
416        self.0.is_none()
417    }
418
419    /// Validate that the name contains only safe characters `[a-zA-Z0-9._-]`.
420    ///
421    /// This prevents path traversal and other injection attacks when the
422    /// subject is used in filesystem paths or policy strings.
423    ///
424    /// Note: federated subjects (containing `://`) intentionally bypass this
425    /// validation — call `validate()` only for local subjects.
426    pub fn validate(&self) -> Result<()> {
427        if self.is_federated() {
428            return Ok(()); // federated subjects are validated at JWT decode time
429        }
430
431        let name = match &self.0 {
432            Some(n) => n.as_str(),
433            None => return Ok(()),
434        };
435
436        if name.is_empty() {
437            return Err(anyhow!("Subject name must not be empty"));
438        }
439
440        for c in name.chars() {
441            if !c.is_ascii_alphanumeric() && c != '.' && c != '_' && c != '-' {
442                return Err(anyhow!(
443                    "Subject name contains invalid character '{}': only [a-zA-Z0-9._-] allowed",
444                    c
445                ));
446            }
447        }
448
449        Ok(())
450    }
451
452    /// Create a federated subject for a principal from a foreign issuer.
453    ///
454    /// Format: `"{issuer_url}:{local_sub}"` — for example
455    /// `"https://node-a:alice"`. The `://` in the URL makes federated subjects
456    /// unambiguously distinguishable from local bare usernames.
457    ///
458    /// The resulting subject is used directly as the Casbin subject string so
459    /// federation-aware policies can match on the issuer prefix.
460    pub fn federated(iss: &str, sub: &str) -> Self {
461        Subject(Some(format!("{iss}:{sub}")))
462    }
463
464    /// Returns `true` if this subject originated from a foreign issuer.
465    ///
466    /// Federated subjects contain `"://"` (from the issuer URL); local bare
467    /// usernames never do.
468    pub fn is_federated(&self) -> bool {
469        self.0
470            .as_deref()
471            .map(|s| s.contains("://"))
472            .unwrap_or(false)
473    }
474}
475
476impl fmt::Display for Subject {
477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478        match &self.0 {
479            Some(name) => write!(f, "{name}"),
480            None => write!(f, "anonymous"),
481        }
482    }
483}
484
485impl FromStr for Subject {
486    type Err = anyhow::Error;
487
488    fn from_str(s: &str) -> Result<Self> {
489        if s == "anonymous" {
490            return Ok(Self::anonymous());
491        }
492
493        // Legacy compatibility: strip known prefixes
494        if let Some((prefix, name)) = s.split_once(':') {
495            if matches!(prefix, "local" | "token" | "peer" | "user") {
496                return Ok(Self::new(name));
497            }
498        }
499
500        Ok(Self::new(s))
501    }
502}
503
504impl From<&Claims> for Subject {
505    fn from(claims: &Claims) -> Self {
506        // Keep every claims→subject entry point on Claims::subject(), including
507        // its reserved unauthenticated-sentinel handling. With no configured
508        // local issuers, empty `iss` remains local and non-empty `iss` remains
509        // federated, preserving this conversion's prior routing behavior.
510        claims.subject(&[])
511    }
512}
513
514// Cap'n Proto implementation for Subject (simple text field)
515impl ToCapnp for Subject {
516    type Builder<'a> = common_capnp::subject::Builder<'a>;
517
518    fn write_to(&self, builder: &mut Self::Builder<'_>) {
519        builder.set_name(self.to_string());
520    }
521}
522
523impl FromCapnp for Subject {
524    type Reader<'a> = common_capnp::subject::Reader<'a>;
525
526    fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
527        let name = reader.get_name()?.to_str()?;
528        name.parse()
529    }
530}
531
532/// Unsigned envelope wrapping an RPC request.
533///
534/// This struct contains all request metadata and is signed by `SignedEnvelope`.
535/// The entire serialized RequestEnvelope is covered by the signature.
536///
537/// # Replay Protection
538///
539/// Legacy: `nonce` + `iat` nonce-cache replay. Superseded by v16 proof CWT
540/// `cti`-based replay admission (§4.5). Retained for dual-read wire compat;
541/// the proof-CWT path is fail-closed when present.
542#[derive(Debug, Clone)]
543pub struct RequestEnvelope {
544    /// DEPRECATED: replaced by proof CWT `cti`. Retained for wire compat.
545    pub request_id: u64,
546
547    /// Serialized inner request (e.g., RegistryRequest, InferenceRequest)
548    pub payload: Vec<u8>,
549
550    /// Unix timestamp in milliseconds for expiration check
551    pub iat: i64,
552
553    /// DEPRECATED: replaced by proof CWT `cti` replay admission.
554    pub nonce: [u8; 16],
555
556    /// Authorization context
557    pub authorization: Authorization,
558
559    /// Delegation token relayed by a trusted service (e.g., OAI, MCP adapter).
560    ///
561    /// **Reserved.** Serialized in the envelope and covered by the signature,
562    /// but not yet consumed server-side. Intended for bearer delegation flows
563    /// where a gateway service forwards a user's JWT on their behalf.
564    /// Server-side extraction will be added when the delegation trust model
565    /// is finalized.
566    pub delegation_token: Option<String>,
567
568    /// DEPRECATED: replaced by proof CWT `credential_hash` (-70001).
569    pub wth: Option<[u8; 32]>,
570
571    /// Client's ephemeral DH public key for stream key derivation.
572    /// Present on streaming requests; the server uses this with its own
573    /// ephemeral keypair to derive the shared secret for HMAC chain keys.
574    pub client_dh_public: Option<[u8; 32]>,
575
576    /// Fresh, suite-complete HyKEM recipient for identified stream setup.
577    ///
578    /// This is authenticated inside the request envelope and is distinct from
579    /// both the legacy classical DH field and the one-shot unary-response
580    /// recipient.  The server must bind it into an [`IdentifiedStreamBinding`]
581    /// before deriving or releasing stream epoch keys.
582    pub client_kem_public: Option<crate::crypto::hybrid_kem::RecipientPublic>,
583
584    /// Fresh per-call hybrid-KEM recipient for the unary response. This is
585    /// distinct from both legacy `client_dh_public` and stream-plane
586    /// `clientKemPublic`, and is carried only inside a sealed network request.
587    pub response_kem_recipient: Option<crate::crypto::hybrid_kem::RecipientPublic>,
588
589    /// Canonical destination service. On untrusted carriers this is required,
590    /// carried only in the signed+sealed request, and checked by dispatch.
591    pub service_domain: Option<String>,
592
593    /// v16 proof CWT (`application/vnd.hyprstream.proof+cwt`). When present,
594    /// carries the canonical request body, credential hash, response binding,
595    /// and one 128-bit request_id replacing requestId+nonce. Servers verify
596    /// this in the dispatch pipeline; the legacy nonce-based replay cache is
597    /// the fallback during dual-read migration.
598    pub proof_cwt: Option<Vec<u8>>,
599    /// Read-only mediated-authorization proof, never a dispatch credential.
600    pub authorization_witness: Option<crate::sensitive::SensitiveBytes>,
601}
602
603impl RequestEnvelope {
604    /// Create a new request envelope with fresh request ID, nonce, and timestamp.
605    pub fn new(payload: Vec<u8>) -> Self {
606        Self {
607            request_id: next_request_id(),
608            payload,
609            iat: current_timestamp(),
610            nonce: generate_nonce(),
611            authorization: Authorization::None,
612            delegation_token: None,
613            wth: None,
614            client_dh_public: None,
615            client_kem_public: None,
616            response_kem_recipient: None,
617            service_domain: None,
618            proof_cwt: None,
619            authorization_witness: None,
620        }
621    }
622
623    /// Set authorization context.
624    pub fn with_authorization(mut self, auth: Authorization) -> Self {
625        self.authorization = auth;
626        self
627    }
628
629    /// Set opaque JWT token as IdJag authorization.
630    pub fn with_jwt_token(mut self, token: String) -> Self {
631        self.authorization = Authorization::IdJag(token);
632        self
633    }
634
635    /// Set delegation token for relay by a trusted service.
636    pub fn with_delegation_token(mut self, token: String) -> Self {
637        self.delegation_token = Some(token);
638        self
639    }
640
641    /// Bind this proof to a specific WIT by storing SHA-256(jwt).
642    /// Call this on cached-identity requests where jwtToken is omitted.
643    pub fn with_wth_of(mut self, jwt: &str) -> Self {
644        use sha2::{Digest, Sha256};
645        self.wth = Some(Sha256::digest(jwt.as_bytes()).into());
646        self
647    }
648
649    /// Set the client's ephemeral DH public key for stream key derivation.
650    pub fn with_client_dh_public(mut self, key: [u8; 32]) -> Self {
651        self.client_dh_public = Some(key);
652        self
653    }
654
655    /// Set the identified stream's ephemeral, pinned-suite HyKEM recipient.
656    pub fn with_client_kem_public(
657        mut self,
658        recipient: crate::crypto::hybrid_kem::RecipientPublic,
659    ) -> EnvelopeResult<Self> {
660        recipient
661            .validate()
662            .map_err(|error| EnvelopeError::KeyExchange(error.to_string()))?;
663        if recipient.suite_id != crate::stream_epoch::IDENTIFIED_STREAM_SUITE {
664            return Err(EnvelopeError::KeyExchange(
665                "identified streams require the pinned X25519+ML-KEM-768 suite".into(),
666            ));
667        }
668        self.client_kem_public = Some(recipient);
669        Ok(self)
670    }
671
672    /// Set the one-shot HyKEM recipient for the corresponding unary response.
673    pub fn with_response_kem_recipient(
674        mut self,
675        recipient: crate::crypto::hybrid_kem::RecipientPublic,
676    ) -> Self {
677        self.response_kem_recipient = Some(recipient);
678        self
679    }
680
681    /// Bind the request to one canonical destination service.
682    pub fn with_service_domain(mut self, service_domain: impl Into<String>) -> Result<Self> {
683        let service_domain = service_domain.into();
684        validate_service_domain(&service_domain)?;
685        self.service_domain = Some(service_domain);
686        Ok(self)
687    }
688
689    /// Attach a v16 proof CWT to this envelope.
690    pub fn with_proof_cwt(mut self, proof_cwt: Vec<u8>) -> Self {
691        self.proof_cwt = Some(proof_cwt);
692        self
693    }
694
695    /// Create an envelope for an anonymous request.
696    pub fn anonymous(payload: Vec<u8>) -> Self {
697        Self::new(payload)
698    }
699
700    /// Extract the JWT string from authorization, if it's an IdJag.
701    pub fn jwt_token(&self) -> Option<&str> {
702        match &self.authorization {
703            Authorization::IdJag(s) => Some(s.as_str()),
704            _ => None,
705        }
706    }
707
708    /// Serialize this envelope to canonical Cap'n Proto bytes for signing.
709    ///
710    /// SECURITY: This method MUST produce deterministic output for cryptographic
711    /// signatures to work correctly. We use Cap'n Proto's canonical form as
712    /// specified in the encoding spec:
713    /// https://capnproto.org/encoding.html#canonicalization
714    ///
715    /// Canonical form guarantees:
716    /// - Same logical data → identical bytes (always)
717    /// - Preorder encoding (deterministic pointer ordering)
718    /// - Single segment (no segment boundary ambiguity)
719    /// - Truncated trailing zeros (no padding differences)
720    /// - No packing (binary format is deterministic)
721    /// - No segment table framing (redundant for signing)
722    ///
723    /// These bytes are what gets signed in a SignedEnvelope.
724    pub fn to_bytes(&self) -> Vec<u8> {
725        use capnp::message::Builder;
726        use capnp::Word;
727
728        // Build the message.
729        let mut message = Builder::new_default();
730        {
731            let mut builder = message.init_root::<common_capnp::request_envelope::Builder>();
732            self.write_to(&mut builder);
733        }
734
735        // Canonicalize directly from the builder (#178). Cap'n Proto is
736        // zero-copy; the previous implementation defeated that on the signing
737        // hot path by serializing to a temp Vec and reparsing it just to obtain
738        // a Reader. `Builder::into_reader()` reads the builder's own segments in
739        // place — no temp serialize, no reparse. Canonicalization is still
740        // REQUIRED: capnp messages aren't canonical by default, and signatures
741        // must be over deterministic bytes for cross-platform verification.
742        //
743        // `into_reader()` uses unlimited traversal, which is correct here: the
744        // message is self-produced (not untrusted input), and it removes a
745        // latent bug where the old 1-MiB-limited reader silently returned empty
746        // bytes — breaking signing — for envelopes larger than 1 MiB.
747        let canonical_words = match message.into_reader().canonicalize() {
748            Ok(words) => words,
749            Err(_e) => {
750                #[cfg(not(target_arch = "wasm32"))]
751                tracing::error!("Envelope canonicalization failed: {}", _e);
752                return Vec::new();
753            }
754        };
755
756        // Convert Words to bytes (raw segment data, NO stream framing).
757        Word::words_to_bytes(&canonical_words).to_vec()
758    }
759}
760
761/// Signed envelope wrapping a RequestEnvelope with Ed25519 signature.
762///
763/// The signature covers the **serialized bytes** of the inner `RequestEnvelope`,
764/// making the signing scope structurally explicit.
765///
766/// # Security
767///
768/// - Signature survives message forwarding (unlike transport-layer auth)
769/// - Nonce + timestamp prevent replay attacks
770/// - Signer pubkey included for verification without key lookup
771///
772/// # Example
773///
774/// ```ignore
775/// use hyprstream_rpc::envelope::{RequestEnvelope, SignedEnvelope};
776/// use hyprstream_rpc::crypto::SigningKey;
777///
778/// // Create and sign
779/// let envelope = RequestEnvelope::anonymous(payload);
780/// let signed = SignedEnvelope::new_signed(envelope, &signing_key);
781///
782/// // Verify
783/// signed.verify(&expected_pubkey, &nonce_cache)?;
784/// ```
785#[derive(Debug, Clone)]
786pub struct SignedEnvelope {
787    /// The unsigned envelope (cleartext path, or decrypted from encrypted_envelope)
788    pub envelope: RequestEnvelope,
789
790    /// Ed25519 signature (64 bytes)
791    pub sig: [u8; 64],
792
793    /// Ed25519 public key of the signer (32 bytes)
794    pub cnf: [u8; 32],
795
796    /// AES-256-GCM-SIV ciphertext of serialized RequestEnvelope (None = cleartext mode)
797    pub encrypted_envelope: Option<Vec<u8>>,
798
799    /// X25519 ephemeral public key for DH key agreement (present when encrypted)
800    pub client_ephemeral_public: Option<[u8; 32]>,
801
802    /// M3 (#152): CBOR-encoded COSE_Sign composite signature (detached).
803    ///
804    /// Authoritative authentication mechanism. Production envelopes carry the
805    /// pinned EdDSA + ML-DSA-65 composite over the canonical signing-data.
806    /// EdDSA-only encoding remains available only to test fixtures. The
807    /// ML-DSA-65 verifying key is NOT embedded; it is
808    /// resolved by kid from a trust store (kid-anchored), which fixes the
809    /// prior self-certification weakness.
810    ///
811    /// `sig`/`cnf` remain populated with the raw EdDSA signature + signer
812    /// public key for backward compatibility and for the JWT `cnf` key-binding
813    /// path, but the COSE composite is what `verify*` enforces.
814    pub cose: Vec<u8>,
815
816    /// Signature suite marker. Production construction always uses `Hybrid`.
817    pub policy: crate::crypto::CryptoPolicy,
818
819    /// ML-KEM-768 ciphertext (1088 bytes, present when hybrid encryption is used)
820    pub pq_kem_ciphertext: Option<Vec<u8>>,
821}
822
823/// Cap'n Proto file id of `common.capnp` (the envelope schema). Used as the
824/// first component of the COSE `external_aad` schema-binding.
825pub const ENVELOPE_SCHEMA_ID: u64 = 0xb3e9_f4a1_c7d8_2056;
826
827/// Stable inner-type id for `RequestEnvelope` in the COSE `external_aad`.
828/// Distinct from any payload schema id; binds the COSE signature to the
829/// envelope structure to prevent schema-confusion / cross-protocol replay.
830pub const REQUEST_ENVELOPE_TYPE_ID: u64 = 0x5265_7145_6e76_3031; // "ReqEnv01"
831
832/// Stable inner-type id for `ResponseEnvelope`, distinct from
833/// [`REQUEST_ENVELOPE_TYPE_ID`]. The `ResponseEnvelope` COSE composite (#275)
834/// binds this type-id into its `external_aad` via
835/// [`response_envelope_external_aad`], so a response COSE signature can NEVER
836/// verify as a request signature (or vice-versa) — the request↔response domain
837/// separation is cryptographically enforced, not merely documented.
838pub const RESPONSE_ENVELOPE_TYPE_ID: u64 = 0x5265_7350_456e_7631; // "RsPEnv1"
839
840/// Build the COSE external_aad used for all REQUEST envelope signatures.
841pub(crate) fn envelope_external_aad() -> Vec<u8> {
842    crate::crypto::cose_sign1::build_external_aad(ENVELOPE_SCHEMA_ID, REQUEST_ENVELOPE_TYPE_ID)
843}
844
845/// Build the external_aad for an ENCRYPTED (`#mesh-kem` COSE_Encrypt0) request
846/// envelope, binding the outer replay metadata (`request_id`, `iat`, `nonce`)
847/// into the AEAD.
848///
849/// # Why this is security-critical
850///
851/// The encrypted request path serializes a *redacted* outer `RequestEnvelope`
852/// (replay metadata only) beside the ciphertext, and the server runs its replay
853/// check on those OUTER fields *before* decapsulating the KEM (a deliberate DoS
854/// pre-filter). Those outer fields are not individually signed — the COSE
855/// composite signature covers only the ciphertext bytes. Unless they are folded
856/// into the AEAD's `external_aad`, a network attacker can capture an encrypted
857/// envelope and replay it with a mutated outer `nonce`/`iat`: the signature
858/// still validates (ciphertext unchanged), the replay check passes (fresh outer
859/// nonce), and a static AAD still decrypts — a full replay bypass.
860///
861/// Binding them here means any mutation of the outer fields changes the AAD the
862/// server recomputes from the received outer envelope, so `open_from_recipient`
863/// fails the AEAD tag; an unmutated replay is caught by the nonce cache. The
864/// encoding is a self-contained canonical CBOR array with a domain tag so it
865/// can never collide with the plain-signature AAD.
866///
867/// # Fail-closed
868///
869/// Serialization of this fixed integer/bytes shape into an unbounded `Vec` is
870/// infallible in practice, but on the off chance it errors this returns `Err`
871/// rather than substituting the weaker plain signing AAD — a silent downgrade
872/// there would reintroduce the exact replay bypass this binding closes. Both the
873/// seal and open callers propagate the error, so the request simply fails.
874pub(crate) fn encrypted_envelope_external_aad(
875    request_id: u64,
876    iat: i64,
877    nonce: &[u8; 16],
878) -> EnvelopeResult<Vec<u8>> {
879    use ciborium::value::Value as CborValue;
880    let value = CborValue::Array(vec![
881        CborValue::Integer(ENVELOPE_SCHEMA_ID.into()),
882        CborValue::Integer(REQUEST_ENVELOPE_TYPE_ID.into()),
883        CborValue::Text("hykem-req-aad-v1".to_owned()),
884        CborValue::Integer(request_id.into()),
885        CborValue::Integer(iat.into()),
886        CborValue::Bytes(nonce.to_vec()),
887    ]);
888    let mut buf = Vec::new();
889    ciborium::ser::into_writer(&value, &mut buf).map_err(|e| {
890        EnvelopeError::Encryption(format!("encode replay-bound #mesh-kem AAD: {e}"))
891    })?;
892    Ok(buf)
893}
894
895/// Serialize `envelope` in stream framing and seal it to `recipient` as a
896/// `#mesh-kem` COSE_Encrypt0 with the replay-bound external AAD.
897///
898/// Single source of truth for both client-side sealing paths
899/// ([`RpcClientImpl::sign_envelope`](crate::rpc_client) and
900/// [`SignedEnvelope::new_signed_encrypted_mesh_kem`]) so the Cap'n Proto
901/// framing and the AAD can never drift between them.
902pub(crate) fn seal_request_envelope(
903    envelope: &RequestEnvelope,
904    recipient: &crate::crypto::hybrid_kem::RecipientPublic,
905) -> EnvelopeResult<Vec<u8>> {
906    // Standard stream framing (NOT the canonical `to_bytes()` signing form,
907    // which omits the segment table) so the decrypt side can `read_message`.
908    let mut plaintext = Vec::new();
909    {
910        let mut message = capnp::message::Builder::new_default();
911        {
912            let mut builder = message.init_root::<crate::common_capnp::request_envelope::Builder>();
913            envelope.write_to(&mut builder);
914        }
915        capnp::serialize::write_message(&mut plaintext, &message).map_err(|e| {
916            EnvelopeError::Encryption(format!("serialize envelope for encryption: {e}"))
917        })?;
918    }
919    let aad = encrypted_envelope_external_aad(envelope.request_id, envelope.iat, &envelope.nonce)?;
920    // One-shot: `seal_to_recipient` performs a FRESH encapsulation per call, so
921    // a fixed (epoch=0, seq=0) nonce is safe — the content key is unique per call.
922    crate::crypto::cose_encrypt::seal_to_recipient(recipient, &plaintext, &aad, 0, 0)
923        .map_err(|e| EnvelopeError::Encryption(format!("#mesh-kem envelope seal failed: {e}")))
924}
925
926/// Build the COSE external_aad used for all RESPONSE envelope signatures (#275).
927///
928/// Bound to [`RESPONSE_ENVELOPE_TYPE_ID`] (≠ [`REQUEST_ENVELOPE_TYPE_ID`]), this
929/// is the load-bearing domain separation: a COSE composite produced for a
930/// response cannot verify against the request AAD, and vice-versa.
931fn response_envelope_external_aad() -> Vec<u8> {
932    crate::crypto::cose_sign1::build_external_aad(ENVELOPE_SCHEMA_ID, RESPONSE_ENVELOPE_TYPE_ID)
933}
934
935const MAX_RESPONSE_KEM_RECIPIENT_BYTES: usize = 2 * 1024;
936const MAX_ENCRYPTED_RESPONSE_BYTES: usize = 1024 * 1024;
937pub const MAX_SERVICE_DOMAIN_BYTES: usize = 128;
938
939/// Validate the one canonical RPC service/destination identifier.
940///
941/// Domains are compared byte-for-byte and never normalized at a trust
942/// boundary, avoiding aliases between the client and dispatcher.
943pub fn validate_service_domain(service_domain: &str) -> Result<()> {
944    let bytes = service_domain.as_bytes();
945    if bytes.is_empty() || bytes.len() > MAX_SERVICE_DOMAIN_BYTES {
946        anyhow::bail!(
947            "service domain must contain 1..={} bytes",
948            MAX_SERVICE_DOMAIN_BYTES
949        );
950    }
951    if !bytes[0].is_ascii_lowercase() && !bytes[0].is_ascii_digit() {
952        anyhow::bail!("service domain must begin with a lowercase ASCII letter or digit");
953    }
954    if !bytes.iter().all(|byte| {
955        byte.is_ascii_lowercase()
956            || byte.is_ascii_digit()
957            || matches!(byte, b'.' | b'_' | b'-' | b'/')
958    }) {
959        anyhow::bail!(
960            "service domain must use only lowercase ASCII letters, digits, '.', '_', '-', or '/'"
961        );
962    }
963    Ok(())
964}
965
966/// Transcript-bound external AAD for the response HyKEM COSE_Encrypt0.
967pub(crate) fn encrypted_response_external_aad(
968    request_id: u64,
969    request_iat: i64,
970    request_nonce: &[u8; 16],
971    server_identity: &[u8; 32],
972    recipient: &crate::crypto::hybrid_kem::RecipientPublic,
973    service_domain: &str,
974) -> EnvelopeResult<Vec<u8>> {
975    use ciborium::value::Value as CborValue;
976    use sha2::{Digest, Sha256};
977
978    let recipient_hash = Sha256::digest(recipient.encode());
979    let value = CborValue::Array(vec![
980        CborValue::Integer(ENVELOPE_SCHEMA_ID.into()),
981        CborValue::Integer(RESPONSE_ENVELOPE_TYPE_ID.into()),
982        CborValue::Text("hykem-rpc-response-v1".to_owned()),
983        CborValue::Integer(request_id.into()),
984        CborValue::Integer(request_iat.into()),
985        CborValue::Bytes(request_nonce.to_vec()),
986        CborValue::Bytes(server_identity.to_vec()),
987        CborValue::Bytes(recipient_hash.to_vec()),
988        CborValue::Text(service_domain.to_owned()),
989    ]);
990    let mut buf = Vec::new();
991    ciborium::ser::into_writer(&value, &mut buf)
992        .map_err(|e| EnvelopeError::Encryption(format!("encode response HyKEM AAD: {e}")))?;
993    Ok(buf)
994}
995
996/// Resolves the anchored ML-DSA-65 verifying key for an EdDSA signer identity.
997///
998/// kid-anchoring: the envelope's EdDSA signer key (`cnf`, 32 bytes) is the
999/// identity. A `PqTrustStore` maps that identity to its trusted ML-DSA-65 key.
1000/// The COSE ML-DSA-65 entry must verify against this anchored key (and its kid
1001/// must match), so an attacker cannot strip + re-sign with their own PQ key.
1002pub trait PqTrustStore: Send + Sync {
1003    /// Return the trusted ML-DSA-65 verifying key bound to the given Ed25519
1004    /// signer public key, or `None` if no binding is known.
1005    fn ml_dsa_key_for(
1006        &self,
1007        ed25519_pubkey: &[u8; 32],
1008    ) -> Option<crate::crypto::pq::MlDsaVerifyingKey>;
1009}
1010
1011/// The ML-DSA-65 key an envelope's signature is checked against, plus how it
1012/// was obtained.
1013///
1014/// The distinction exists so the commit step can tell "already trusted for this
1015/// identity" from "asserted by this very envelope and not yet recorded". The
1016/// second kind must not be written down until the composite has verified
1017/// against it.
1018enum PqAnchor {
1019    /// Resolved from the admin-anchored store or from an already-established
1020    /// overlay binding.
1021    Anchored(crate::crypto::pq::MlDsaVerifyingKey),
1022    /// Asserted by this envelope for an identity with no binding on file.
1023    #[cfg(not(target_arch = "wasm32"))]
1024    FirstContact(crate::crypto::pq::MlDsaVerifyingKey),
1025    /// This identity has a binding on file and the envelope asserts a
1026    /// different key. The request is rejected either way; the key is carried
1027    /// so the event can be raised once the EdDSA layer proves who sent it.
1028    #[cfg(not(target_arch = "wasm32"))]
1029    Rebind {
1030        established: crate::crypto::pq::MlDsaVerifyingKey,
1031        presented: crate::crypto::pq::MlDsaVerifyingKey,
1032    },
1033}
1034
1035impl PqAnchor {
1036    fn key(&self) -> &crate::crypto::pq::MlDsaVerifyingKey {
1037        match self {
1038            PqAnchor::Anchored(k) => k,
1039            #[cfg(not(target_arch = "wasm32"))]
1040            PqAnchor::FirstContact(k) => k,
1041            // The established key, so the composite check fails on the kid
1042            // mismatch rather than on a key the envelope chose.
1043            #[cfg(not(target_arch = "wasm32"))]
1044            PqAnchor::Rebind { established, .. } => established,
1045        }
1046    }
1047}
1048
1049/// In-memory kid-anchored ML-DSA-65 trust store mapping an Ed25519 signer
1050/// identity to its trusted ML-DSA-65 verifying key.
1051///
1052/// This is the authoritative anchor for the mesh/streaming/browser SNS
1053/// composite. Bindings come from the node's own hybrid identity and from
1054/// attested peer identities. Entries MUST be established out-of-band (peer
1055/// attestation / trust-store), never from the self-asserted COSE object.
1056#[derive(Default)]
1057pub struct KeyedPqTrustStore {
1058    bindings: std::collections::HashMap<[u8; 32], Vec<u8>>,
1059}
1060
1061impl KeyedPqTrustStore {
1062    /// Create an empty store.
1063    pub fn new() -> Self {
1064        Self {
1065            bindings: std::collections::HashMap::new(),
1066        }
1067    }
1068
1069    /// Bind an Ed25519 signer identity to its trusted ML-DSA-65 verifying key
1070    /// (stored as raw vk bytes; re-decoded on lookup).
1071    ///
1072    /// Anchoring is **monotonic and conflict-resistant**: once an identity is
1073    /// bound to a specific ML-DSA-65 key, a subsequent attempt to bind it to a
1074    /// *different* key is refused (not silently overwritten). The same key
1075    /// re-registered is an idempotent no-op. This prevents a stale or hostile
1076    /// seeding source from silently substituting a different PQ identity for an
1077    /// already-anchored peer — the last writer does not win.
1078    pub fn bind(
1079        &mut self,
1080        ed25519_pubkey: [u8; 32],
1081        ml_dsa_vk: &crate::crypto::pq::MlDsaVerifyingKey,
1082    ) {
1083        let new_bytes = crate::crypto::pq::ml_dsa_vk_bytes(ml_dsa_vk);
1084        if let Some(existing) = self.bindings.get(&ed25519_pubkey) {
1085            if existing == &new_bytes {
1086                return; // idempotent re-registration of the same key
1087            }
1088            #[cfg(not(target_arch = "wasm32"))]
1089            tracing::error!(
1090                ed25519 = %hex::encode(ed25519_pubkey),
1091                "PQ anchor conflict: identity is already bound to a different \
1092                 ML-DSA-65 key; refusing to rebind. The existing anchor is \
1093                 retained — investigate if this is unexpected."
1094            );
1095            return;
1096        }
1097        self.bindings.insert(ed25519_pubkey, new_bytes);
1098    }
1099
1100    /// Register an identity that may or may not carry a bound ML-DSA-65 key.
1101    ///
1102    /// Anchoring is **monotonic**: a `None` key never clears or replaces an
1103    /// anchor already established for that identity. Re-registering a
1104    /// previously hybrid identity from a classical-only source (a legacy
1105    /// bootstrap file, a re-enrollment that omitted the PQ half) therefore
1106    /// cannot silently downgrade the peer back to classical.
1107    ///
1108    /// Equally, a `Some` registration with a *different* PQ key than the one
1109    /// already anchored is refused (see [`bind`]) — a rebind is not silent.
1110    ///
1111    /// Returns whether the identity is anchored after the call.
1112    pub fn register(
1113        &mut self,
1114        ed25519_pubkey: [u8; 32],
1115        ml_dsa_vk: Option<&crate::crypto::pq::MlDsaVerifyingKey>,
1116    ) -> bool {
1117        match ml_dsa_vk {
1118            Some(vk) => {
1119                self.bind(ed25519_pubkey, vk);
1120                true
1121            }
1122            None => self.bindings.contains_key(&ed25519_pubkey),
1123        }
1124    }
1125
1126    /// Whether this identity has an anchored ML-DSA-65 key.
1127    pub fn is_anchored(&self, ed25519_pubkey: &[u8; 32]) -> bool {
1128        self.bindings.contains_key(ed25519_pubkey)
1129    }
1130
1131    /// Number of bindings.
1132    pub fn len(&self) -> usize {
1133        self.bindings.len()
1134    }
1135
1136    /// Whether the store has no bindings.
1137    pub fn is_empty(&self) -> bool {
1138        self.bindings.is_empty()
1139    }
1140}
1141
1142impl PqTrustStore for KeyedPqTrustStore {
1143    fn ml_dsa_key_for(
1144        &self,
1145        ed25519_pubkey: &[u8; 32],
1146    ) -> Option<crate::crypto::pq::MlDsaVerifyingKey> {
1147        self.bindings
1148            .get(ed25519_pubkey)
1149            .and_then(|bytes| crate::crypto::pq::ml_dsa_vk_from_bytes(bytes).ok())
1150    }
1151}
1152
1153// ============================================================================
1154// Process-global envelope verify configuration (closes the fail-open).
1155// ============================================================================
1156
1157/// Process-wide envelope verification configuration shared by all production
1158/// verify sites (`process_request` / `RequestLoop`, `StreamService` register).
1159///
1160/// Holds the enforced [`CryptoPolicy`] and the kid-anchored [`PqTrustStore`].
1161/// The daemon installs this at startup with `Hybrid` + a real store wired from
1162/// the node's hybrid identity (see `key_rotation`). When unset, verification
1163/// still enforces `Hybrid`; production code MUST call [`install_verify_config`]
1164/// to provide the trust anchors needed for successful admission.
1165pub struct EnvelopeVerifyConfig {
1166    pub policy: crate::crypto::CryptoPolicy,
1167    pub pq_store: Option<std::sync::Arc<dyn PqTrustStore>>,
1168}
1169
1170#[cfg(not(target_arch = "wasm32"))]
1171static VERIFY_CONFIG: std::sync::OnceLock<EnvelopeVerifyConfig> = std::sync::OnceLock::new();
1172
1173/// Install the process-global envelope verify configuration. First write wins.
1174///
1175/// Returns `Err` if a configuration was already installed.
1176#[cfg(not(target_arch = "wasm32"))]
1177pub fn install_verify_config(config: EnvelopeVerifyConfig) -> Result<()> {
1178    VERIFY_CONFIG
1179        .set(config)
1180        .map_err(|_| anyhow!("envelope verify config already installed"))
1181}
1182
1183/// Whether a process-global verify configuration has been installed.
1184#[cfg(not(target_arch = "wasm32"))]
1185pub fn verify_config_installed() -> bool {
1186    VERIFY_CONFIG.get().is_some()
1187}
1188
1189/// The enforced verify policy.
1190///
1191/// When a config has been installed, its policy is returned verbatim.
1192///
1193/// When **uninstalled**, the default is **fail-closed**: production builds
1194/// default to [`CryptoPolicy::Hybrid`] so that any verify site reached before
1195/// `install_verify_config` (subprocess-spawner services, early init) rejects
1196/// classical-only envelopes rather than silently accepting EdDSA-only ones
1197/// (#160 — this previously defaulted `Classical`, re-opening the M3 fail-open).
1198///
1199#[cfg(not(target_arch = "wasm32"))]
1200pub fn global_verify_policy() -> crate::crypto::CryptoPolicy {
1201    if let Some(c) = VERIFY_CONFIG.get() {
1202        return c.policy;
1203    }
1204    // Fail-closed default. Loud once because reaching a verification site with
1205    // no installed config is a production wiring bug (#160).
1206    static WARNED: std::sync::Once = std::sync::Once::new();
1207    WARNED.call_once(|| {
1208        tracing::warn!(
1209            "envelope verify config not installed; enforcing the pinned Hybrid suite. \
1210             Production code MUST call install_verify_config() at startup."
1211        );
1212    });
1213    crate::crypto::CryptoPolicy::Hybrid
1214}
1215
1216/// The installed kid-anchored PQ trust store, if any.
1217#[cfg(not(target_arch = "wasm32"))]
1218pub fn global_pq_store() -> Option<std::sync::Arc<dyn PqTrustStore>> {
1219    VERIFY_CONFIG.get().and_then(|c| c.pq_store.clone())
1220}
1221
1222#[cfg(not(target_arch = "wasm32"))]
1223static BROWSER_CURRENTNESS_VERIFIER: std::sync::OnceLock<
1224    std::sync::Arc<dyn crate::browser_provisioning::BrowserCurrentnessVerifier>,
1225> = std::sync::OnceLock::new();
1226
1227/// Install the checkpoint-backed authority used at WebTransport dispatch.
1228/// First write wins; there is deliberately no test/global fallback.
1229#[cfg(not(target_arch = "wasm32"))]
1230pub fn install_browser_currentness_verifier(
1231    verifier: std::sync::Arc<dyn crate::browser_provisioning::BrowserCurrentnessVerifier>,
1232) -> Result<()> {
1233    BROWSER_CURRENTNESS_VERIFIER
1234        .set(verifier)
1235        .map_err(|_| anyhow!("browser currentness verifier already installed"))
1236}
1237
1238#[cfg(not(target_arch = "wasm32"))]
1239pub fn global_browser_currentness_verifier(
1240) -> Option<std::sync::Arc<dyn crate::browser_provisioning::BrowserCurrentnessVerifier>> {
1241    BROWSER_CURRENTNESS_VERIFIER.get().cloned()
1242}
1243
1244/// Apply the mandatory process-global policy and trust store to an
1245/// `UnwrapOptions`.
1246#[cfg(not(target_arch = "wasm32"))]
1247pub fn apply_global_verify_config<'a>(
1248    mut opts: UnwrapOptions<'a>,
1249    store_holder: &'a Option<std::sync::Arc<dyn PqTrustStore>>,
1250) -> UnwrapOptions<'a> {
1251    opts.verify_policy = global_verify_policy();
1252    opts.pq_store = store_holder.as_deref();
1253    opts
1254}
1255
1256/// The production policy-selected pinned suite. There is deliberately no
1257/// environment or wire input: peers either support it fully or admission fails.
1258pub const fn mandatory_envelope_policy() -> crate::crypto::CryptoPolicy {
1259    crate::crypto::CryptoPolicy::Hybrid
1260}
1261
1262// ============================================================================
1263// Process-global RESPONSE-envelope verify configuration (#277).
1264//
1265// Symmetric to the request-side `EnvelopeVerifyConfig`/`global_verify_policy`
1266// above, but for the client-side `ResponseEnvelope` verify path. The daemon /
1267// native RPC client construction installs this at startup with `Hybrid` + the
1268// admin-anchored mesh PQ trust store (#157), so server-asserted `StreamInfo`
1269// (dhPublic anchoring + QoS contract) is PQ-attested in production. When
1270// uninstalled, the default is fail-closed `Hybrid` (mirroring the request side):
1271// a classical-only / stripped response is rejected rather than silently
1272// accepted.
1273//
1274// This REUSES the same `CryptoPolicy`, `PqTrustStore`, and `KeyedPqTrustStore`
1275// machinery as the request side — it is a second arm of the same system, not a
1276// parallel one.
1277// ============================================================================
1278
1279/// Process-wide RESPONSE-envelope verify configuration consulted by clients that
1280/// did not explicitly set a per-client response policy / PQ store (#277).
1281pub struct ResponseVerifyConfig {
1282    pub policy: crate::crypto::CryptoPolicy,
1283    pub pq_store: Option<std::sync::Arc<dyn PqTrustStore>>,
1284}
1285
1286#[cfg(not(target_arch = "wasm32"))]
1287static RESPONSE_VERIFY_CONFIG: std::sync::OnceLock<ResponseVerifyConfig> =
1288    std::sync::OnceLock::new();
1289
1290/// Install the process-global RESPONSE verify configuration. First write wins.
1291///
1292/// Returns `Err` if a configuration was already installed.
1293#[cfg(not(target_arch = "wasm32"))]
1294pub fn install_response_verify_config(config: ResponseVerifyConfig) -> Result<()> {
1295    RESPONSE_VERIFY_CONFIG
1296        .set(config)
1297        .map_err(|_| anyhow!("response verify config already installed"))
1298}
1299
1300/// Whether a process-global RESPONSE verify configuration has been installed.
1301#[cfg(not(target_arch = "wasm32"))]
1302pub fn response_verify_config_installed() -> bool {
1303    RESPONSE_VERIFY_CONFIG.get().is_some()
1304}
1305
1306/// The enforced RESPONSE-verify policy (consulted when a client did not set one).
1307///
1308/// When a config has been installed, its policy is returned verbatim.
1309///
1310/// When **uninstalled**, the default is **fail-closed**, symmetric to the
1311/// request side ([`global_verify_policy`]): production builds default to
1312/// [`CryptoPolicy::Hybrid`] so a client that reaches the response-verify path
1313/// before `install_response_verify_config` rejects classical-only responses
1314/// rather than silently accepting EdDSA-only ones (#277).
1315#[cfg(not(target_arch = "wasm32"))]
1316pub fn global_response_verify_policy() -> crate::crypto::CryptoPolicy {
1317    if let Some(c) = RESPONSE_VERIFY_CONFIG.get() {
1318        return c.policy;
1319    }
1320    static WARNED: std::sync::Once = std::sync::Once::new();
1321    WARNED.call_once(|| {
1322        tracing::warn!(
1323            "response verify config not installed; enforcing the pinned Hybrid suite. \
1324             Production code MUST call install_response_verify_config() at startup."
1325        );
1326    });
1327    mandatory_envelope_policy()
1328}
1329
1330/// The installed RESPONSE-side kid-anchored PQ trust store, if any.
1331#[cfg(not(target_arch = "wasm32"))]
1332pub fn global_response_pq_store() -> Option<std::sync::Arc<dyn PqTrustStore>> {
1333    RESPONSE_VERIFY_CONFIG
1334        .get()
1335        .and_then(|c| c.pq_store.clone())
1336}
1337
1338/// Replay protection cache interface.
1339///
1340/// Implementations should maintain a cache of recently seen nonces
1341/// to prevent replay attacks.
1342pub trait NonceCache: Send + Sync {
1343    /// Check if a nonce has been seen before, and if not, mark it as seen.
1344    ///
1345    /// Returns `true` if the nonce is fresh (not seen before).
1346    /// Returns `false` if the nonce has already been used.
1347    fn check_and_insert(&self, nonce: &[u8; 16]) -> bool;
1348}
1349
1350/// Simple in-memory nonce cache with time-based expiration.
1351///
1352/// This implementation uses a `HashMap` with timestamps to track seen nonces.
1353/// Old entries are cleaned up periodically during insertions.
1354///
1355/// # Thread Safety
1356///
1357/// Uses `parking_lot::RwLock` for concurrent access (non-poisoning).
1358/// Suitable for moderate load.
1359/// For high-throughput scenarios, consider a lock-free or sharded implementation.
1360///
1361/// # Memory Usage
1362///
1363/// At most `max_entries` nonces are stored. Oldest entries are evicted
1364/// when the limit is reached.
1365pub struct InMemoryNonceCache {
1366    /// Map of nonce -> timestamp when it was first seen
1367    #[cfg(not(target_arch = "wasm32"))]
1368    seen: parking_lot::RwLock<std::collections::HashMap<[u8; 16], i64>>,
1369    #[cfg(target_arch = "wasm32")]
1370    seen: std::sync::RwLock<std::collections::HashMap<[u8; 16], i64>>,
1371    /// Maximum age for entries (in milliseconds)
1372    max_age_ms: i64,
1373    /// Maximum number of entries before cleanup
1374    max_entries: usize,
1375}
1376
1377impl Default for InMemoryNonceCache {
1378    fn default() -> Self {
1379        Self::new()
1380    }
1381}
1382
1383impl InMemoryNonceCache {
1384    /// Create a new cache with default settings.
1385    ///
1386    /// Defaults:
1387    /// - Max age: 5 minutes (matches `MAX_TIMESTAMP_AGE_MS`)
1388    /// - Max entries: 100,000
1389    pub fn new() -> Self {
1390        Self {
1391            seen: Default::default(),
1392            max_age_ms: MAX_TIMESTAMP_AGE_MS,
1393            max_entries: 100_000,
1394        }
1395    }
1396
1397    /// Create a new cache with custom settings.
1398    pub fn with_config(max_age_ms: i64, max_entries: usize) -> Self {
1399        Self {
1400            seen: Default::default(),
1401            max_age_ms,
1402            max_entries,
1403        }
1404    }
1405
1406    #[cfg(not(target_arch = "wasm32"))]
1407    fn read_lock(
1408        &self,
1409    ) -> parking_lot::RwLockReadGuard<'_, std::collections::HashMap<[u8; 16], i64>> {
1410        self.seen.read()
1411    }
1412
1413    #[cfg(target_arch = "wasm32")]
1414    fn read_lock(
1415        &self,
1416    ) -> std::sync::RwLockReadGuard<'_, std::collections::HashMap<[u8; 16], i64>> {
1417        self.seen.read().expect("nonce cache lock poisoned")
1418    }
1419
1420    #[cfg(not(target_arch = "wasm32"))]
1421    fn write_lock(
1422        &self,
1423    ) -> parking_lot::RwLockWriteGuard<'_, std::collections::HashMap<[u8; 16], i64>> {
1424        self.seen.write()
1425    }
1426
1427    #[cfg(target_arch = "wasm32")]
1428    fn write_lock(
1429        &self,
1430    ) -> std::sync::RwLockWriteGuard<'_, std::collections::HashMap<[u8; 16], i64>> {
1431        self.seen.write().expect("nonce cache lock poisoned")
1432    }
1433
1434    /// Remove expired entries.
1435    fn cleanup(&self, now: i64) {
1436        let mut seen = self.write_lock();
1437
1438        // Remove entries older than max_age
1439        seen.retain(|_, timestamp| now - *timestamp <= self.max_age_ms);
1440
1441        // If still too many entries, remove oldest
1442        if seen.len() > self.max_entries {
1443            let mut entries: Vec<_> = seen.iter().map(|(k, v)| (*k, *v)).collect();
1444            entries.sort_by_key(|(_, ts)| *ts);
1445
1446            // Keep only the newest max_entries/2 entries
1447            let to_keep = self.max_entries / 2;
1448            for (key, _) in entries.iter().take(entries.len().saturating_sub(to_keep)) {
1449                seen.remove(key);
1450            }
1451        }
1452    }
1453}
1454
1455impl NonceCache for InMemoryNonceCache {
1456    fn check_and_insert(&self, nonce: &[u8; 16]) -> bool {
1457        let now = current_timestamp();
1458
1459        // Fast path: check if already seen (read lock)
1460        {
1461            let seen = self.read_lock();
1462            if seen.contains_key(nonce) {
1463                return false;
1464            }
1465        }
1466
1467        // Slow path: insert (write lock)
1468        let mut seen = self.write_lock();
1469
1470        // Double-check after acquiring write lock
1471        if seen.contains_key(nonce) {
1472            return false;
1473        }
1474
1475        // Insert the nonce
1476        seen.insert(*nonce, now);
1477
1478        // Cleanup if we have too many entries
1479        if seen.len() > self.max_entries {
1480            drop(seen); // Release lock before cleanup
1481            self.cleanup(now);
1482        }
1483
1484        true
1485    }
1486}
1487
1488/// Maximum age for a valid request timestamp (5 minutes).
1489pub const MAX_TIMESTAMP_AGE_MS: i64 = 5 * 60 * 1000;
1490
1491/// Maximum clock skew tolerance (30 seconds into the future).
1492pub const MAX_CLOCK_SKEW_MS: i64 = 30 * 1000;
1493
1494impl SignedEnvelope {
1495    /// Create and sign a new envelope.
1496    ///
1497    /// The signature covers the Cap'n Proto serialized bytes of the envelope.
1498    /// If the authorization is `IdJag` and `wth` is not already set, `wth`
1499    /// is auto-populated as SHA-256(jwt) per the WIMSE wth binding.
1500    #[cfg(any(test, feature = "test-classical-policy"))]
1501    pub fn new_signed(envelope: RequestEnvelope, signing_key: &SigningKey) -> Self {
1502        // Default policy is Classical for the bare Ed25519-only constructor so
1503        // that callers that don't supply a PQ key produce verifiable envelopes.
1504        // Infallible: Classical never requires a PQ key, so the only failure
1505        // left is a CBOR-encoding error over fixed-shape COSE structures —
1506        // fail loud rather than emit a fail-open empty composite.
1507        #[allow(clippy::expect_used)]
1508        Self::new_signed_with_policy(
1509            envelope,
1510            signing_key,
1511            None,
1512            crate::crypto::CryptoPolicy::Classical,
1513        )
1514        .expect("COSE composite signing must not fail for valid keys")
1515    }
1516
1517    /// Create and dual-sign a new envelope with Ed25519 + ML-DSA-65 (Hybrid).
1518    pub fn new_signed_hybrid(
1519        envelope: RequestEnvelope,
1520        signing_key: &SigningKey,
1521        pq_signing_key: &crate::crypto::pq::MlDsaSigningKey,
1522    ) -> Self {
1523        // Infallible: the PQ key is statically present, so the only failure
1524        // left is a CBOR-encoding error over fixed-shape COSE structures —
1525        // fail loud rather than emit a fail-open empty composite.
1526        #[allow(clippy::expect_used)]
1527        Self::new_signed_with_policy(
1528            envelope,
1529            signing_key,
1530            Some(pq_signing_key),
1531            crate::crypto::CryptoPolicy::Hybrid,
1532        )
1533        .expect("COSE composite signing must not fail for valid keys")
1534    }
1535
1536    /// Create and sign a new envelope under an explicit [`CryptoPolicy`].
1537    ///
1538    /// - `Hybrid`: emits an EdDSA + ML-DSA-65 COSE composite. `pq_signing_key`
1539    ///   MUST be `Some`; absence is a fail-closed construction error.
1540    ///
1541    /// `sig`/`cnf` are always populated with the raw EdDSA signature + signer
1542    /// public key for the cnf key-binding path.
1543    pub fn new_signed_with_policy(
1544        mut envelope: RequestEnvelope,
1545        signing_key: &SigningKey,
1546        pq_signing_key: Option<&crate::crypto::pq::MlDsaSigningKey>,
1547        policy: crate::crypto::CryptoPolicy,
1548    ) -> Result<Self> {
1549        if envelope.wth.is_none() {
1550            if let Some(jwt) = envelope.jwt_token() {
1551                use sha2::{Digest, Sha256};
1552                envelope.wth = Some(Sha256::digest(jwt.as_bytes()).into());
1553            }
1554        }
1555
1556        let envelope_bytes = envelope.to_bytes();
1557        let signature = signing_key.sign(&envelope_bytes);
1558        // SECURITY: no empty-cose fallback. A missing mandatory PQ key or a
1559        // COSE encoding error is a fail-closed construction error propagated
1560        // to the caller — never substitute an empty (and thus potentially
1561        // fail-open) composite, never downgrade to classical.
1562        let cose = Self::build_cose(signing_key, pq_signing_key, policy, &envelope_bytes)?;
1563
1564        Ok(Self {
1565            envelope,
1566            sig: signature.to_bytes(),
1567            cnf: signing_key.verifying_key().to_bytes(),
1568            encrypted_envelope: None,
1569            client_ephemeral_public: None,
1570            cose,
1571            policy,
1572            pq_kem_ciphertext: None,
1573        })
1574    }
1575
1576    /// Build the nested COSE composite signature for the given signing-data per
1577    /// policy. Returns `Err` on encoding failure — callers MUST NOT substitute
1578    /// an empty cose (that would fail open at verify time).
1579    fn build_cose(
1580        signing_key: &SigningKey,
1581        pq_signing_key: Option<&crate::crypto::pq::MlDsaSigningKey>,
1582        policy: crate::crypto::CryptoPolicy,
1583        signing_data: &[u8],
1584    ) -> Result<Vec<u8>> {
1585        let pq = if policy.uses_pq() {
1586            Some(pq_signing_key.ok_or_else(|| {
1587                anyhow!("mandatory Hybrid suite requires an ML-DSA-65 signing key")
1588            })?)
1589        } else {
1590            None
1591        };
1592        let aad = envelope_external_aad();
1593        // PQ-bound: the inner EdDSA layer commits to the ML-DSA-65 key above it.
1594        // Request envelopes are the one composite whose ML-DSA-65 key a verifier
1595        // may RECORD (first contact) rather than resolve from a trust store, so
1596        // the Ed25519 signature has to cover which PQ key is being claimed.
1597        // Without that, a captured envelope's inner layer can be re-used under a
1598        // different outer key by someone who never held the Ed25519 secret.
1599        crate::crypto::cose_sign::sign_composite_pq_bound(signing_key, pq, signing_data, &aad)
1600    }
1601
1602    /// Create, hybrid-encrypt (HyKEM `#mesh-kem` → COSE_Encrypt0), and dual-sign
1603    /// (EdDSA + ML-DSA-65) a new envelope — the fail-closed hybrid-PQ path (#555 / S4).
1604    ///
1605    /// The serialized `RequestEnvelope` is sealed with
1606    /// [`crate::crypto::cose_encrypt::seal_to_recipient`] to the server's anchored
1607    /// `#mesh-kem` [`crate::crypto::hybrid_kem::RecipientPublic`] (resolved
1608    /// out-of-band via a [`crate::crypto::hybrid_kem::KemTrustStore`], NEVER
1609    /// self-asserted). The KEM material rides inside the COSE_Encrypt0 (`ek`
1610    /// header), so the COSE composite signature simply covers the COSE_Encrypt0
1611    /// bytes.
1612    ///
1613    /// This replaces the retired `envelope_crypto` X25519-static scheme, which
1614    /// reused the Ed25519 *signing* key as a *static* X25519 KEX key (key-reuse +
1615    /// no forward secrecy + fixed-zero-nonce AEAD). Forward secrecy now comes from
1616    /// the ephemeral X25519 leg of HyKEM and from rotated `#mesh-kem` prekeys
1617    /// (S1 `KemPrekey`).
1618    pub fn new_signed_encrypted_mesh_kem(
1619        mut envelope: RequestEnvelope,
1620        signing_key: &SigningKey,
1621        pq_signing_key: &crate::crypto::pq::MlDsaSigningKey,
1622        server_kem_public: &crate::crypto::hybrid_kem::RecipientPublic,
1623    ) -> EnvelopeResult<Self> {
1624        if envelope.wth.is_none() {
1625            if let Some(jwt) = envelope.jwt_token() {
1626                use sha2::{Digest, Sha256};
1627                envelope.wth = Some(Sha256::digest(jwt.as_bytes()).into());
1628            }
1629        }
1630        // Serialize + seal via the shared helper so the framing and the
1631        // replay-bound external AAD stay identical to the client path.
1632        let cose_ct = seal_request_envelope(&envelope, server_kem_public)?;
1633
1634        // The COSE_Encrypt0 bytes are the signing data — the KEM ciphertexts and
1635        // suite id are self-described inside the COSE object.
1636        let signature = signing_key.sign(&cose_ct);
1637        let cose = Self::build_cose(
1638            signing_key,
1639            Some(pq_signing_key),
1640            crate::crypto::CryptoPolicy::Hybrid,
1641            &cose_ct,
1642        )
1643        .map_err(|e| EnvelopeError::Encryption(format!("COSE composite signing failed: {e}")))?;
1644
1645        Ok(Self {
1646            envelope,
1647            sig: signature.to_bytes(),
1648            cnf: signing_key.verifying_key().to_bytes(),
1649            encrypted_envelope: Some(cose_ct),
1650            // reserved — KEM material lives in the COSE_Encrypt0 `ek` header now.
1651            client_ephemeral_public: None,
1652            cose,
1653            policy: crate::crypto::CryptoPolicy::Hybrid,
1654            pq_kem_ciphertext: None,
1655        })
1656    }
1657
1658    /// Returns true if this envelope uses the encrypted path.
1659    pub fn is_encrypted(&self) -> bool {
1660        self.encrypted_envelope.is_some()
1661    }
1662
1663    /// Outer placeholder serialized beside `encrypted_envelope`.
1664    ///
1665    /// The outer envelope keeps only non-secret replay metadata until
1666    /// authenticated decryption succeeds. Payload, JWT authorization,
1667    /// delegation bearer, WTH, and streaming DH material live only inside the
1668    /// COSE_Encrypt0 plaintext and replace this placeholder after decrypt.
1669    fn redacted_encrypted_envelope(&self) -> RequestEnvelope {
1670        RequestEnvelope {
1671            request_id: self.envelope.request_id,
1672            payload: Vec::new(),
1673            iat: self.envelope.iat,
1674            nonce: self.envelope.nonce,
1675            authorization: Authorization::None,
1676            delegation_token: None,
1677            wth: None,
1678            client_dh_public: None,
1679            client_kem_public: None,
1680            response_kem_recipient: None,
1681            service_domain: None,
1682            proof_cwt: None,
1683            authorization_witness: None,
1684        }
1685    }
1686
1687    /// Verify the signature, then atomically commit replay protection.
1688    ///
1689    /// # Verification Steps
1690    ///
1691    /// 1. Check timestamp is within the acceptable window without mutation
1692    /// 2. Verify signer pubkey matches expected key
1693    /// 3. Verify Ed25519 signature
1694    /// 4. Atomically check and record the nonce
1695    ///
1696    /// # Errors
1697    ///
1698    /// - `EnvelopeError::InvalidPublicKey` if signer doesn't match expected
1699    /// - `EnvelopeError::ReplayAttack` if timestamp or nonce check fails
1700    /// - `EnvelopeError::InvalidSignature` if signature verification fails
1701    #[cfg(any(test, feature = "test-classical-policy"))]
1702    pub fn verify(
1703        &self,
1704        expected_pubkey: &VerifyingKey,
1705        nonce_cache: &dyn NonceCache,
1706    ) -> EnvelopeResult<()> {
1707        self.verify_with(
1708            expected_pubkey,
1709            nonce_cache,
1710            None,
1711            crate::crypto::CryptoPolicy::Classical,
1712        )
1713    }
1714
1715    /// Verify with an explicit kid-anchored PQ trust store and verify policy.
1716    ///
1717    /// - `pq_store`: when `Some`, resolves the trust-anchored ML-DSA-65 key for
1718    ///   the envelope's EdDSA signer (`cnf`). The COSE ML-DSA-65 entry must
1719    ///   verify against this key and its kid must match (kid-anchoring) —
1720    ///   fixing the self-certification weakness.
1721    /// - `verify_policy`: production pins `Hybrid`, which requires an anchored
1722    ///   ML-DSA-65 key and enforces the outer layer. Missing anchors, stripped
1723    ///   outers, forged keys, and self-asserted PQ keys all fail closed.
1724    pub fn verify_with(
1725        &self,
1726        expected_pubkey: &VerifyingKey,
1727        nonce_cache: &dyn NonceCache,
1728        pq_store: Option<&dyn PqTrustStore>,
1729        verify_policy: crate::crypto::CryptoPolicy,
1730    ) -> EnvelopeResult<()> {
1731        self.validate_timestamp()?;
1732        // 1. Verify signer matches expected (constant-time comparison)
1733        if !bool::from(self.cnf.ct_eq(&expected_pubkey.to_bytes())) {
1734            return Err(EnvelopeError::SignerMismatch {
1735                expected: hex::encode(expected_pubkey.to_bytes()),
1736                actual: hex::encode(self.cnf),
1737            });
1738        }
1739
1740        self.verify_cose(expected_pubkey, pq_store, verify_policy)?;
1741        self.check_replay(nonce_cache)
1742    }
1743
1744    /// Verify signature only (skip replay protection).
1745    ///
1746    /// Use this for testing or when replay protection is handled elsewhere.
1747    #[cfg(any(test, feature = "test-classical-policy"))]
1748    pub fn verify_signature_only(&self, expected_pubkey: &VerifyingKey) -> EnvelopeResult<()> {
1749        if !bool::from(self.cnf.ct_eq(&expected_pubkey.to_bytes())) {
1750            return Err(EnvelopeError::SignerMismatch {
1751                expected: hex::encode(expected_pubkey.to_bytes()),
1752                actual: hex::encode(self.cnf),
1753            });
1754        }
1755        self.verify_cose(
1756            expected_pubkey,
1757            None,
1758            crate::crypto::CryptoPolicy::Classical,
1759        )
1760    }
1761
1762    /// Verify signature only under an explicit policy + PQ trust store.
1763    pub fn verify_signature_only_with(
1764        &self,
1765        expected_pubkey: &VerifyingKey,
1766        pq_store: Option<&dyn PqTrustStore>,
1767        verify_policy: crate::crypto::CryptoPolicy,
1768    ) -> EnvelopeResult<()> {
1769        if !bool::from(self.cnf.ct_eq(&expected_pubkey.to_bytes())) {
1770            return Err(EnvelopeError::SignerMismatch {
1771                expected: hex::encode(expected_pubkey.to_bytes()),
1772                actual: hex::encode(self.cnf),
1773            });
1774        }
1775        self.verify_cose(expected_pubkey, pq_store, verify_policy)
1776    }
1777
1778    /// Verify against the envelope's own embedded signer pubkey.
1779    ///
1780    /// For WebTransport clients that sign with their own keypair rather than
1781    /// a shared server key. Still checks timestamp and nonce for replay protection.
1782    #[cfg(any(test, feature = "test-classical-policy"))]
1783    pub fn verify_any_signer(&self, nonce_cache: &dyn NonceCache) -> EnvelopeResult<()> {
1784        self.verify_any_signer_with(nonce_cache, None, crate::crypto::CryptoPolicy::Classical)
1785    }
1786
1787    /// `verify_any_signer` with an explicit kid-anchored PQ trust store + policy.
1788    pub fn verify_any_signer_with(
1789        &self,
1790        nonce_cache: &dyn NonceCache,
1791        pq_store: Option<&dyn PqTrustStore>,
1792        verify_policy: crate::crypto::CryptoPolicy,
1793    ) -> EnvelopeResult<()> {
1794        self.validate_timestamp()?;
1795        let verifying_key =
1796            VerifyingKey::from_bytes(&self.cnf).map_err(|_| EnvelopeError::InvalidPublicKey {
1797                expected: 32,
1798                actual: 0,
1799            })?;
1800        self.verify_cose(&verifying_key, pq_store, verify_policy)?;
1801        self.check_replay(nonce_cache)
1802    }
1803
1804    /// Non-mutating timestamp-window validation for early rejection before
1805    /// signature verification, KEM decapsulation, or decryption.
1806    fn validate_timestamp(&self) -> EnvelopeResult<()> {
1807        Self::validate_timestamp_at(self.envelope.iat, current_timestamp())
1808    }
1809
1810    /// Validate `iat` against an explicit clock reading.
1811    ///
1812    /// Widen both wire-controlled timestamps before subtracting so every `i64`
1813    /// input, including the two extremes, has defined fail-closed behavior.
1814    /// Both limits are inclusive: an age exactly equal to the past window or a
1815    /// future distance exactly equal to the clock-skew allowance is accepted.
1816    fn validate_timestamp_at(iat: i64, now: i64) -> EnvelopeResult<()> {
1817        let age = i128::from(now) - i128::from(iat);
1818        let max_age = i128::from(MAX_TIMESTAMP_AGE_MS);
1819        if age > max_age {
1820            return Err(EnvelopeError::ReplayAttack(format!(
1821                "timestamp too old: {age}ms > {MAX_TIMESTAMP_AGE_MS}ms"
1822            )));
1823        }
1824
1825        let future_distance = i128::from(iat) - i128::from(now);
1826        let max_future = i128::from(MAX_CLOCK_SKEW_MS);
1827        if future_distance > max_future {
1828            let excess = future_distance - max_future;
1829            return Err(EnvelopeError::ReplayAttack(format!(
1830                "timestamp in future: {excess}ms beyond clock skew tolerance"
1831            )));
1832        }
1833        Ok(())
1834    }
1835
1836    /// Revalidate the timestamp, then atomically check and record the nonce.
1837    fn check_replay(&self, nonce_cache: &dyn NonceCache) -> EnvelopeResult<()> {
1838        // Recheck at commit time so work performed near a timestamp-window
1839        // boundary cannot admit an entry after it expires.
1840        self.validate_timestamp()?;
1841        if !nonce_cache.check_and_insert(&self.envelope.nonce) {
1842            return Err(EnvelopeError::ReplayAttack("nonce already seen".to_owned()));
1843        }
1844        Ok(())
1845    }
1846
1847    /// Verify the COSE composite signature (authoritative auth check).
1848    ///
1849    /// The raw EdDSA `sig`/`cnf` advertisement is NOT trusted on its own; this
1850    /// re-verifies the EdDSA component inside the COSE composite against
1851    /// `ed_vk`, and (under Hybrid policy) the kid-anchored ML-DSA-65 component.
1852    fn verify_cose(
1853        &self,
1854        ed_vk: &VerifyingKey,
1855        pq_store: Option<&dyn PqTrustStore>,
1856        verify_policy: crate::crypto::CryptoPolicy,
1857    ) -> EnvelopeResult<()> {
1858        let signing_data = self.signed_bytes();
1859        let aad = envelope_external_aad();
1860
1861        // The PQ requirement is per identity on top of the global policy.
1862        // Under a PQ-bearing policy the anchor is resolved as before (store,
1863        // then session overlay, then first contact). Under a classical policy
1864        // an identity with an anchored ML-DSA-65 key STILL requires a
1865        // verifying outer PQ layer — anchoring a peer is what turns PQ on for
1866        // that peer — while an identity with no anchor keeps the classical
1867        // floor, so a deployment holding no hybrid material behaves exactly
1868        // as before.
1869        //
1870        // The unanchored branch is DELIBERATE INTEROP POLICY, not laxity, and
1871        // must not be tightened here. It is the only place a signer this node
1872        // does not itself provision — an external client, or a federated peer
1873        // whose key comes from its own published document — can be admitted on
1874        // terms other than our own. This node's own service identities are
1875        // always provisioned hybrid and therefore always anchored, so making
1876        // them mandatorily hybrid is achieved entirely by what gets anchored,
1877        // and needs no change on this line. Deciding what the unanchored
1878        // branch may admit is a separate, interop-facing question; do not
1879        // settle it as a side effect of an internal-identity change.
1880        let anchor = if verify_policy.uses_pq() {
1881            Some(self.resolve_pq_anchor(pq_store)?)
1882        } else {
1883            pq_store
1884                .and_then(|store| store.ml_dsa_key_for(&self.cnf))
1885                .map(PqAnchor::Anchored)
1886        };
1887        let require_pq = anchor.is_some();
1888
1889        // A rebinding attempt is rejected without ever consulting the key the
1890        // envelope chose. It is raised as an event only if the EdDSA layer
1891        // verifies — otherwise anyone who merely knows an identity's public
1892        // key could inject alarms about it, and a security-event channel that
1893        // unauthenticated senders can drive is worse than none.
1894        #[cfg(not(target_arch = "wasm32"))]
1895        if let Some(PqAnchor::Rebind { presented, .. }) = &anchor {
1896            let sender_holds_identity = crate::crypto::cose_sign::verify_composite(
1897                &self.cose,
1898                ed_vk,
1899                None,
1900                &signing_data,
1901                &aad,
1902                false,
1903            )
1904            .is_ok();
1905            if sender_holds_identity {
1906                if let Some(overlay) = crate::session_pq_overlay::global_session_pq_overlay() {
1907                    // Publish-only: this key has NOT been proven, so it must not
1908                    // reach a code path that could record it.
1909                    overlay.surface_rebind(self.cnf, presented);
1910                }
1911            }
1912
1913            return Err(EnvelopeError::PqSignatureInvalid(
1914                "presented ML-DSA-65 key differs from this identity's established binding; \
1915                 rebinding requires explicit approval"
1916                    .to_owned(),
1917            ));
1918        }
1919
1920        let verified = crate::crypto::cose_sign::verify_composite(
1921            &self.cose,
1922            ed_vk,
1923            anchor.as_ref().map(PqAnchor::key),
1924            &signing_data,
1925            &aad,
1926            require_pq,
1927        )
1928        .map_err(|e| EnvelopeError::PqSignatureInvalid(e.to_string()))?;
1929
1930        // Commit a first-contact observation only now, and only if the composite
1931        // proved possession of the Ed25519 private key *alongside* the ML-DSA-65
1932        // one.
1933        //
1934        // `verified.pq_bound` is exactly that proof. The nesting alone is not:
1935        // it binds inner→outer, so an unbound composite can be rebuilt by anyone
1936        // holding a COPY of the inner layer — they discard the outer, re-sign
1937        // `payload ‖ inner_signature` with an ML-DSA key of their own, and the
1938        // result verifies with their PQ key under the captured identity. Only
1939        // the inner layer's commitment to the outer key rules that out, because
1940        // that commitment sits inside the Ed25519 signature.
1941        //
1942        // An unbound composite still verifies (it may be a peer resolved from
1943        // the anchored store, or an older client); it simply cannot establish a
1944        // binding.
1945        #[cfg(not(target_arch = "wasm32"))]
1946        if let Some(PqAnchor::FirstContact(key)) = &anchor {
1947            if !verified.pq_bound {
1948                return Err(EnvelopeError::PqSignatureInvalid(
1949                    "first contact requires the inner EdDSA layer to commit to its ML-DSA-65 \
1950                     key; an uncommitted composite cannot establish a binding"
1951                        .to_owned(),
1952                ));
1953            }
1954            if let Some(overlay) = crate::session_pq_overlay::global_session_pq_overlay() {
1955                let outcome = overlay.observe_first_contact(self.cnf, key);
1956                if !matches!(
1957                    outcome,
1958                    crate::session_pq_overlay::FirstContactOutcome::Recorded
1959                        | crate::session_pq_overlay::FirstContactOutcome::AlreadyBound(_)
1960                ) {
1961                    // A racing contact took the slot. Fail closed rather than
1962                    // serve a request whose signer this node did not end up
1963                    // remembering.
1964                    return Err(EnvelopeError::PqSignatureInvalid(
1965                        "first-contact ML-DSA-65 binding was not recorded".to_owned(),
1966                    ));
1967                }
1968            }
1969        }
1970
1971        Ok(())
1972    }
1973
1974    /// Resolve the ML-DSA-65 key this envelope's signature is checked against.
1975    ///
1976    /// Order, and why:
1977    ///
1978    /// 1. The admin-anchored [`PqTrustStore`]. Operator-enrolled bindings are
1979    ///    the strongest anchor and are never displaced by anything below.
1980    /// 2. An established overlay binding. If the envelope presents a different
1981    ///    key than the one on file, this reports a rebinding attempt and the
1982    ///    caller rejects the request; the binding on file is left untouched — a
1983    ///    rotation is applied only through the overlay's explicit approval
1984    ///    path.
1985    /// 3. First contact. The key the composite asserts for itself becomes a
1986    ///    *candidate* only; it is trusted for nothing until the whole composite
1987    ///    verifies against it, and even then it is recorded at a provenance
1988    ///    that cannot raise MAC assurance.
1989    ///
1990    /// With no overlay installed, only step 1 exists and the behavior is
1991    /// unchanged: an unanchored identity fails closed.
1992    fn resolve_pq_anchor(&self, pq_store: Option<&dyn PqTrustStore>) -> EnvelopeResult<PqAnchor> {
1993        if let Some(key) = pq_store.and_then(|store| store.ml_dsa_key_for(&self.cnf)) {
1994            return Ok(PqAnchor::Anchored(key));
1995        }
1996
1997        #[cfg(not(target_arch = "wasm32"))]
1998        if let Some(overlay) = crate::session_pq_overlay::global_session_pq_overlay() {
1999            let presented = crate::crypto::cose_sign::self_asserted_outer_pq_key(&self.cose)
2000                .map_err(|e| EnvelopeError::PqSignatureInvalid(e.to_string()))?;
2001
2002            if let Some(established) = overlay.verifying_key_for(&self.cnf) {
2003                let Some(presented) = presented else {
2004                    // No outer layer to compare. The binding stands: a
2005                    // PQ-less envelope from a bound identity is rejected by
2006                    // the composite check below, and clears nothing.
2007                    return Ok(PqAnchor::Anchored(established));
2008                };
2009                if crate::crypto::pq::ml_dsa_vk_bytes(&presented)
2010                    != crate::crypto::pq::ml_dsa_vk_bytes(&established)
2011                {
2012                    return Ok(PqAnchor::Rebind {
2013                        established,
2014                        presented,
2015                    });
2016                }
2017                return Ok(PqAnchor::Anchored(established));
2018            }
2019
2020            if let Some(candidate) = presented {
2021                return Ok(PqAnchor::FirstContact(candidate));
2022            }
2023        }
2024
2025        Err(EnvelopeError::PqSignatureInvalid(
2026            "mandatory Hybrid suite requires an anchored ML-DSA-65 signer key".to_owned(),
2027        ))
2028    }
2029
2030    /// Compute the bytes that were signed.
2031    ///
2032    /// Encrypted mode: the COSE_Encrypt0 bytes (`encrypted_envelope`) — the KEM
2033    /// ciphertexts and suite id are self-described inside that object.
2034    /// Cleartext mode: `canonical(envelope)`.
2035    fn signed_bytes(&self) -> Vec<u8> {
2036        match &self.encrypted_envelope {
2037            Some(ct) => ct.clone(),
2038            None => self.envelope.to_bytes(),
2039        }
2040    }
2041
2042    /// Decrypt a `#mesh-kem`-encrypted envelope in-place, replacing `envelope`.
2043    ///
2044    /// Opens the COSE_Encrypt0 in `encrypted_envelope` with the node's `#mesh-kem`
2045    /// [`crate::crypto::hybrid_kem::RecipientKeypair`] (deterministically derived
2046    /// from the node Ed25519 key — see
2047    /// [`crate::node_identity::derive_mesh_kem_recipient`]). The encrypted bytes
2048    /// remain for signature verification.
2049    pub fn decrypt_in_place_mesh_kem(
2050        &mut self,
2051        node_kem_keypair: &crate::crypto::hybrid_kem::RecipientKeypair,
2052    ) -> EnvelopeResult<()> {
2053        let ct = self
2054            .encrypted_envelope
2055            .as_ref()
2056            .ok_or_else(|| EnvelopeError::Decryption("no encrypted envelope present".into()))?;
2057        // Recompute the AAD from the OUTER replay metadata that the server will
2058        // commit only after this method succeeds. This binds those unsigned
2059        // fields into the AEAD: a network attacker that mutates the outer
2060        // nonce/iat changes this AAD and the open fails before replay commit.
2061        let aad = encrypted_envelope_external_aad(
2062            self.envelope.request_id,
2063            self.envelope.iat,
2064            &self.envelope.nonce,
2065        )?;
2066
2067        let plaintext =
2068            crate::crypto::cose_encrypt::open_from_recipient(node_kem_keypair, ct, &aad, 0, 0)
2069                .map_err(|e| {
2070                    EnvelopeError::Decryption(format!("#mesh-kem envelope open failed: {e}"))
2071                })?;
2072
2073        let reader = read_exact_envelope_message(&plaintext)
2074            .map_err(|e| EnvelopeError::Decryption(format!("capnp parse after decrypt: {e}")))?;
2075        let env_reader = reader
2076            .get_root::<crate::common_capnp::request_envelope::Reader>()
2077            .map_err(|e| EnvelopeError::Decryption(format!("envelope read after decrypt: {e}")))?;
2078        let inner = RequestEnvelope::read_from(env_reader).map_err(|e| {
2079            EnvelopeError::Decryption(format!("envelope decode after decrypt: {e}"))
2080        })?;
2081
2082        // Defense in depth: the replay metadata the server verified (outer) MUST
2083        // equal the authenticated inner metadata, so the request that gets
2084        // authorized is the same one whose nonce/timestamp will be replay-checked.
2085        // The AAD binding above guarantees outer == what-was-sealed on success;
2086        // this additionally rejects a sender that sealed inner fields diverging
2087        // from the outer envelope it presented for replay admission.
2088        if inner.request_id != self.envelope.request_id
2089            || inner.iat != self.envelope.iat
2090            || inner.nonce != self.envelope.nonce
2091        {
2092            return Err(EnvelopeError::Decryption(
2093                "inner/outer replay metadata mismatch after #mesh-kem decrypt".into(),
2094            ));
2095        }
2096        self.envelope = inner;
2097
2098        Ok(())
2099    }
2100
2101    /// Get the request ID from the inner envelope.
2102    pub fn request_id(&self) -> u64 {
2103        self.envelope.request_id
2104    }
2105
2106    /// Get the payload from the inner envelope.
2107    pub fn payload(&self) -> &[u8] {
2108        &self.envelope.payload
2109    }
2110
2111    /// Get the authorization context.
2112    pub fn authorization(&self) -> &Authorization {
2113        &self.envelope.authorization
2114    }
2115}
2116
2117impl ToCapnp for RequestEnvelope {
2118    type Builder<'a> = common_capnp::request_envelope::Builder<'a>;
2119
2120    fn write_to(&self, builder: &mut Self::Builder<'_>) {
2121        builder.set_request_id(self.request_id);
2122        builder.set_payload(&self.payload);
2123        builder.set_iat(self.iat);
2124        builder.set_nonce(&self.nonce);
2125        self.authorization
2126            .write_to(&mut builder.reborrow().init_authorization());
2127        if let Some(ref token) = self.delegation_token {
2128            builder.set_delegation_token(token);
2129        }
2130        if let Some(ref hash) = self.wth {
2131            builder.set_wth(hash);
2132        }
2133        if let Some(ref key) = self.client_dh_public {
2134            builder.set_client_dh_public(key);
2135        }
2136        if let Some(ref recipient) = self.client_kem_public {
2137            builder.set_client_kem_public(&recipient.encode());
2138        }
2139        if let Some(ref recipient) = self.response_kem_recipient {
2140            builder.set_response_kem_recipient(&recipient.encode());
2141        }
2142        if let Some(ref service_domain) = self.service_domain {
2143            builder.set_service_domain(service_domain);
2144        }
2145        if let Some(ref proof_cwt) = self.proof_cwt {
2146            builder.set_proof_cwt(proof_cwt);
2147        }
2148        if let Some(ref witness) = self.authorization_witness {
2149            builder.set_authorization_witness(witness);
2150        }
2151    }
2152}
2153
2154impl FromCapnp for RequestEnvelope {
2155    type Reader<'a> = common_capnp::request_envelope::Reader<'a>;
2156
2157    fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
2158        let nonce = {
2159            let data = reader.get_nonce()?;
2160            if data.len() != 16 {
2161                return Err(anyhow!(
2162                    "Invalid nonce length: expected 16, got {}",
2163                    data.len()
2164                ));
2165            }
2166            let mut arr = [0u8; 16];
2167            arr.copy_from_slice(data);
2168            arr
2169        };
2170
2171        let authorization = Authorization::read_from(reader.get_authorization()?)?;
2172
2173        let delegation_token = {
2174            if reader.has_delegation_token() {
2175                let t = reader.get_delegation_token()?.to_str()?;
2176                if t.is_empty() {
2177                    None
2178                } else {
2179                    Some(t.to_owned())
2180                }
2181            } else {
2182                None
2183            }
2184        };
2185
2186        let wth = {
2187            let data = reader.get_wth()?;
2188            if data.is_empty() {
2189                None
2190            } else if data.len() == 32 {
2191                let mut arr = [0u8; 32];
2192                arr.copy_from_slice(data);
2193                Some(arr)
2194            } else {
2195                return Err(anyhow!(
2196                    "Invalid wth length: expected 32, got {}",
2197                    data.len()
2198                ));
2199            }
2200        };
2201
2202        let client_dh_public = {
2203            let data = reader.get_client_dh_public()?;
2204            if data.is_empty() {
2205                None
2206            } else if data.len() == 32 {
2207                let mut arr = [0u8; 32];
2208                arr.copy_from_slice(data);
2209                Some(arr)
2210            } else {
2211                return Err(anyhow!(
2212                    "Invalid clientDhPublic length: expected 32, got {}",
2213                    data.len()
2214                ));
2215            }
2216        };
2217
2218        let client_kem_public = {
2219            let data = reader.get_client_kem_public()?;
2220            if data.is_empty() {
2221                None
2222            } else {
2223                if data.len() > MAX_RESPONSE_KEM_RECIPIENT_BYTES {
2224                    return Err(anyhow!(
2225                        "clientKemPublic exceeds {} byte limit",
2226                        MAX_RESPONSE_KEM_RECIPIENT_BYTES
2227                    ));
2228                }
2229                let recipient = crate::crypto::hybrid_kem::RecipientPublic::decode(data)
2230                    .map_err(|e| anyhow!("invalid clientKemPublic: {e}"))?;
2231                if recipient.suite_id != crate::stream_epoch::IDENTIFIED_STREAM_SUITE {
2232                    return Err(anyhow!(
2233                        "clientKemPublic does not use the pinned identified-stream suite"
2234                    ));
2235                }
2236                Some(recipient)
2237            }
2238        };
2239
2240        let response_kem_recipient = {
2241            let data = reader.get_response_kem_recipient()?;
2242            if data.is_empty() {
2243                None
2244            } else {
2245                if data.len() > MAX_RESPONSE_KEM_RECIPIENT_BYTES {
2246                    return Err(anyhow!(
2247                        "responseKemRecipient exceeds {} byte limit",
2248                        MAX_RESPONSE_KEM_RECIPIENT_BYTES
2249                    ));
2250                }
2251                Some(
2252                    crate::crypto::hybrid_kem::RecipientPublic::decode(data)
2253                        .map_err(|e| anyhow!("invalid responseKemRecipient: {e}"))?,
2254                )
2255            }
2256        };
2257
2258        let service_domain = if reader.has_service_domain() {
2259            let value = reader.get_service_domain()?.to_str()?.to_owned();
2260            validate_service_domain(&value)?;
2261            Some(value)
2262        } else {
2263            None
2264        };
2265
2266        Ok(Self {
2267            request_id: reader.get_request_id(),
2268            payload: reader.get_payload()?.to_vec(),
2269            iat: reader.get_iat(),
2270            nonce,
2271            authorization,
2272            delegation_token,
2273            wth,
2274            client_dh_public,
2275            client_kem_public,
2276            response_kem_recipient,
2277            service_domain,
2278            authorization_witness: if reader.has_authorization_witness() {
2279                let value = reader.get_authorization_witness()?;
2280                anyhow::ensure!(
2281                    value.len() <= crate::authorization_witness::MAX_WITNESS_BYTES,
2282                    "authorization witness too large"
2283                );
2284                Some(value.to_vec().into())
2285            } else {
2286                None
2287            },
2288            proof_cwt: {
2289                let has = reader.reborrow().has_proof_cwt();
2290                if !has {
2291                    None
2292                } else {
2293                    let data = reader.get_proof_cwt()?;
2294                    // Enforce the proof-v1 total-object cap before allocation
2295                    // to prevent oversized proofs from consuming memory.
2296                    if data.len() > crate::proof::MAX_COSE_OBJECT_BYTES {
2297                        anyhow::bail!(
2298                            "proofCwt size {} exceeds max {} bytes",
2299                            data.len(),
2300                            crate::proof::MAX_COSE_OBJECT_BYTES
2301                        );
2302                    }
2303                    Some(data.to_vec())
2304                }
2305            },
2306        })
2307    }
2308}
2309
2310impl ToCapnp for SignedEnvelope {
2311    type Builder<'a> = common_capnp::signed_envelope::Builder<'a>;
2312
2313    fn write_to(&self, builder: &mut Self::Builder<'_>) {
2314        if self.encrypted_envelope.is_some() {
2315            self.redacted_encrypted_envelope()
2316                .write_to(&mut builder.reborrow().init_envelope());
2317        } else {
2318            self.envelope
2319                .write_to(&mut builder.reborrow().init_envelope());
2320        }
2321        builder.set_sig(&self.sig);
2322        builder.set_cnf(&self.cnf);
2323        if let Some(ref ct) = self.encrypted_envelope {
2324            builder.set_encrypted_envelope(ct);
2325        }
2326        if let Some(ref eph) = self.client_ephemeral_public {
2327            builder.set_client_ephemeral_public(eph);
2328        }
2329        builder.set_cose(&self.cose);
2330        if let Some(ref kem_ct) = self.pq_kem_ciphertext {
2331            builder.set_pq_kem_ciphertext(kem_ct);
2332        }
2333    }
2334}
2335
2336/// Hard wire-size cap for original-holder authorization-query evidence.
2337pub const MAX_MEDIATED_EVIDENCE_BYTES: usize = 64 * 1024;
2338
2339/// Bound variable request data before copying it into mediation evidence.
2340/// The final serialized frame is capped separately, including framing overhead.
2341#[cfg(not(target_arch = "wasm32"))]
2342pub(crate) fn mediated_request_fits(request: &RequestEnvelope) -> bool {
2343    // Only the holder's own IdJag binds a mediated query. Relayed
2344    // (delegated) service credentials carry no holder consent here and are
2345    // denied (3c72353b6 relay-vouching exception removed per scoped repair).
2346    let Some(credential) = request.jwt_token() else {
2347        return false;
2348    };
2349    if request.delegation_token.is_some() {
2350        return false;
2351    }
2352    let mut remaining = MAX_MEDIATED_EVIDENCE_BYTES;
2353    let lengths = [
2354        request.payload.len(),
2355        credential.len(),
2356        request.service_domain.as_ref().map_or(0, String::len),
2357        request.proof_cwt.as_ref().map_or(0, Vec::len),
2358        request
2359            .authorization_witness
2360            .as_ref()
2361            .map_or(0, |bytes| bytes.len()),
2362    ];
2363    for length in lengths {
2364        let Some(next) = remaining.checked_sub(length) else {
2365            return false;
2366        };
2367        remaining = next;
2368    }
2369    for recipient in [&request.client_kem_public, &request.response_kem_recipient]
2370        .into_iter()
2371        .flatten()
2372    {
2373        // Validation bounds the component count and each key length before
2374        // encode() allocates its wire representation.
2375        if recipient.validate().is_err() {
2376            return false;
2377        }
2378        for key in &recipient.eks {
2379            let Some(next) = remaining.checked_sub(key.len()) else {
2380                return false;
2381            };
2382            remaining = next;
2383        }
2384    }
2385    true
2386}
2387
2388#[cfg(all(test, not(target_arch = "wasm32")))]
2389#[test]
2390fn mediated_capture_bounds_all_variable_fields_before_serializing() {
2391    let request = RequestEnvelope::new(vec![1; 32]).with_jwt_token("holder-token".into());
2392    assert!(mediated_request_fits(&request));
2393    let mut oversized = request.clone();
2394    oversized.proof_cwt = Some(vec![0; MAX_MEDIATED_EVIDENCE_BYTES]);
2395    assert!(!mediated_request_fits(&oversized));
2396    oversized = request.clone();
2397    oversized.authorization_witness = Some(vec![0; MAX_MEDIATED_EVIDENCE_BYTES].into());
2398    assert!(!mediated_request_fits(&oversized));
2399    oversized = request
2400        .clone()
2401        .with_jwt_token("x".repeat(MAX_MEDIATED_EVIDENCE_BYTES));
2402    assert!(!mediated_request_fits(&oversized));
2403    oversized = request.clone();
2404    oversized.service_domain = Some("x".repeat(MAX_MEDIATED_EVIDENCE_BYTES));
2405    assert!(!mediated_request_fits(&oversized));
2406    oversized = request.clone();
2407    oversized.delegation_token = Some("nested-bearer".into());
2408    assert!(!mediated_request_fits(&oversized));
2409    oversized = request;
2410    oversized.authorization = Authorization::None;
2411    assert!(!mediated_request_fits(&oversized));
2412}
2413
2414/// Decode and authenticate a bounded original request for a mediated policy
2415/// query. This proves the signed transcript only: callers must separately
2416/// verify the credential, method/operation binding and query replay admission.
2417/// It must never be used to install an identity on the mediator's context.
2418#[cfg(not(target_arch = "wasm32"))]
2419pub fn verify_mediated_envelope_evidence(
2420    evidence: &[u8],
2421    mediator_service: &str,
2422) -> Result<SignedEnvelope> {
2423    anyhow::ensure!(
2424        !evidence.is_empty() && evidence.len() <= MAX_MEDIATED_EVIDENCE_BYTES,
2425        "invalid mediated evidence size"
2426    );
2427    validate_service_domain(mediator_service)?;
2428    let mut options = capnp::message::ReaderOptions::new();
2429    options.traversal_limit_in_words(Some(64 * 1024 / 8));
2430    options.nesting_limit(16);
2431    let mut remaining = evidence;
2432    let message = capnp::serialize::read_message_from_flat_slice(&mut remaining, options)?;
2433    anyhow::ensure!(remaining.is_empty(), "trailing mediated evidence bytes");
2434    let signed = SignedEnvelope::read_from(
2435        message.get_root::<common_capnp::signed_envelope::Reader<'_>>()?,
2436    )?;
2437    anyhow::ensure!(
2438        signed.encrypted_envelope.is_none(),
2439        "encrypted outer evidence requires the proof path"
2440    );
2441    anyhow::ensure!(
2442        signed.envelope.service_domain.as_deref() == Some(mediator_service),
2443        "mediated evidence target mismatch"
2444    );
2445    anyhow::ensure!(
2446        signed.envelope.delegation_token.is_none(),
2447        "nested delegated evidence denied"
2448    );
2449    anyhow::ensure!(
2450        signed.envelope.jwt_token().is_some(),
2451        "mediated evidence requires a holder credential"
2452    );
2453    signed.validate_timestamp()?;
2454    let holder = VerifyingKey::from_bytes(&signed.cnf)?;
2455    let trust = global_pq_store();
2456    signed.verify_signature_only_with(&holder, trust.as_deref(), mandatory_envelope_policy())?;
2457    Ok(signed)
2458}
2459
2460impl FromCapnp for SignedEnvelope {
2461    type Reader<'a> = common_capnp::signed_envelope::Reader<'a>;
2462
2463    fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
2464        let sig = {
2465            let data = reader.get_sig()?;
2466            if data.len() != 64 {
2467                return Err(anyhow!(
2468                    "Invalid sig length: expected 64, got {}",
2469                    data.len()
2470                ));
2471            }
2472            let mut arr = [0u8; 64];
2473            arr.copy_from_slice(data);
2474            arr
2475        };
2476
2477        let cnf = {
2478            let data = reader.get_cnf()?;
2479            if data.len() != 32 {
2480                return Err(anyhow!(
2481                    "Invalid cnf length: expected 32, got {}",
2482                    data.len()
2483                ));
2484            }
2485            let mut arr = [0u8; 32];
2486            arr.copy_from_slice(data);
2487            arr
2488        };
2489
2490        let encrypted_envelope = {
2491            let data = reader.get_encrypted_envelope()?;
2492            if data.is_empty() {
2493                None
2494            } else {
2495                Some(data.to_vec())
2496            }
2497        };
2498
2499        let client_ephemeral_public = {
2500            let data = reader.get_client_ephemeral_public()?;
2501            if data.is_empty() {
2502                None
2503            } else if data.len() == 32 {
2504                let mut arr = [0u8; 32];
2505                arr.copy_from_slice(data);
2506                Some(arr)
2507            } else {
2508                return Err(anyhow!(
2509                    "Invalid clientEphemeralPublic length: expected 32, got {}",
2510                    data.len()
2511                ));
2512            }
2513        };
2514
2515        let cose = reader.get_cose()?.to_vec();
2516
2517        let pq_kem_ciphertext = {
2518            let data = reader.get_pq_kem_ciphertext()?;
2519            if data.is_empty() {
2520                None
2521            } else {
2522                Some(data.to_vec())
2523            }
2524        };
2525
2526        // `policy` is a signing-time concept; the verifier supplies the verify
2527        // policy explicitly, so decode to the default here.
2528        Ok(Self {
2529            envelope: RequestEnvelope::read_from(reader.get_envelope()?)?,
2530            sig,
2531            cnf,
2532            encrypted_envelope,
2533            client_ephemeral_public,
2534            cose,
2535            policy: crate::crypto::CryptoPolicy::default(),
2536            pq_kem_ciphertext,
2537        })
2538    }
2539}
2540
2541/// Signed response envelope for E2E authenticated responses.
2542///
2543/// All RPC responses are signed to prevent MITM attacks on response data
2544/// (e.g., server's DH public key in StreamInfo).
2545///
2546/// # Security (#275 — Hybrid parity with `SignedEnvelope`)
2547///
2548/// The signing-data is `request_id || payload`, binding the response to a
2549/// specific request and ensuring the payload hasn't been tampered with. The
2550/// authoritative authentication mechanism is the COSE composite [`cose`] —
2551/// the pinned EdDSA + ML-DSA-65 composite over that signing-data, bound to
2552/// [`RESPONSE_ENVELOPE_TYPE_ID`] via the COSE
2553/// `external_aad` so it can NEVER verify as a request signature.
2554///
2555/// `sig`/`cnf` remain populated with the raw EdDSA signature + signer public
2556/// key for backward compatibility and signer-pubkey advertisement, but the
2557/// COSE composite is what `verify*` enforces.
2558///
2559/// [`cose`]: ResponseEnvelope::cose
2560#[derive(Debug, Clone)]
2561pub struct ResponseEnvelope {
2562    /// Request ID this response corresponds to
2563    pub request_id: u64,
2564
2565    /// Serialized inner response
2566    pub payload: Vec<u8>,
2567
2568    /// HyKEM COSE_Encrypt0 carrying a `ResponsePlaintext`. When present the
2569    /// outer payload is empty and the hybrid signature covers these bytes.
2570    pub encrypted_response: Option<Vec<u8>>,
2571
2572    /// Ed25519 signature (64 bytes) over request_id || payload
2573    pub sig: [u8; 64],
2574
2575    /// Ed25519 public key of the signer (32 bytes)
2576    pub cnf: [u8; 32],
2577
2578    /// #275: CBOR-encoded nested COSE composite signature (detached).
2579    ///
2580    /// Authoritative authentication mechanism, mirroring [`SignedEnvelope::cose`].
2581    /// Production carries the pinned EdDSA + ML-DSA-65 composite over the
2582    /// response signing-data (`request_id || payload`), bound to the
2583    /// distinct [`RESPONSE_ENVELOPE_TYPE_ID`] domain. The ML-DSA-65 verifying key
2584    /// is resolved by kid from a [`PqTrustStore`] (kid-anchored), not embedded.
2585    pub cose: Vec<u8>,
2586
2587    /// Signature suite marker. Production construction always uses `Hybrid`.
2588    pub policy: crate::crypto::CryptoPolicy,
2589
2590    /// v16 §4.7: the server's current unattributed-proof challenge, carried
2591    /// uniformly on every pre-handler denial.
2592    ///
2593    /// Bound into the signing transcript when present (see
2594    /// [`ResponseEnvelope::bind_server_challenge`]), so it can neither be
2595    /// stripped nor substituted in flight. Absent on ordinary responses, where
2596    /// the transcript is unchanged.
2597    pub server_challenge: Option<Vec<u8>>,
2598}
2599
2600impl ResponseEnvelope {
2601    /// Response signing-data: `request_id (8 bytes LE) || payload`.
2602    fn signing_data(request_id: u64, payload: &[u8]) -> Vec<u8> {
2603        let mut data = Vec::with_capacity(8 + payload.len());
2604        data.extend_from_slice(&request_id.to_le_bytes());
2605        data.extend_from_slice(payload);
2606        data
2607    }
2608
2609    /// Append the advertised server challenge to a response transcript.
2610    ///
2611    /// Domain-separated and length-prefixed, so no `(payload, challenge)` pair
2612    /// can be re-cut into a different one. When no challenge is advertised the
2613    /// transcript is returned byte-identical, so ordinary responses are
2614    /// unaffected. Applied to both the cleartext and the sealed transcript, so
2615    /// the guarantee does not depend on the carrier.
2616    fn bind_server_challenge(mut data: Vec<u8>, challenge: Option<&[u8]>) -> Vec<u8> {
2617        if let Some(challenge) = challenge {
2618            data.extend_from_slice(b"hs-rpc-server-challenge-v1\0");
2619            data.extend_from_slice(&(challenge.len() as u64).to_le_bytes());
2620            data.extend_from_slice(challenge);
2621        }
2622        data
2623    }
2624
2625    /// Signature transcript for a sealed response. The expected service is
2626    /// retained by the pending call rather than trusted from response bytes.
2627    fn encrypted_signing_data(
2628        request_id: u64,
2629        ciphertext: &[u8],
2630        service_domain: &str,
2631    ) -> EnvelopeResult<Vec<u8>> {
2632        validate_service_domain(service_domain)
2633            .map_err(|e| EnvelopeError::Encryption(e.to_string()))?;
2634        let mut data = Vec::with_capacity(40 + service_domain.len() + ciphertext.len());
2635        data.extend_from_slice(b"hykem-rpc-response-signature-v2\0");
2636        data.extend_from_slice(&request_id.to_le_bytes());
2637        data.extend_from_slice(&(service_domain.len() as u16).to_le_bytes());
2638        data.extend_from_slice(service_domain.as_bytes());
2639        data.extend_from_slice(ciphertext);
2640        Ok(data)
2641    }
2642
2643    /// Create an EdDSA-only response for compatibility tests.
2644    ///
2645    /// This constructor is absent from production builds.
2646    #[cfg(any(test, feature = "test-classical-policy"))]
2647    pub fn new_signed(request_id: u64, payload: Vec<u8>, signing_key: &SigningKey) -> Self {
2648        // Infallible: Classical never requires a PQ key, so the only failure
2649        // left is a CBOR-encoding error over fixed-shape COSE structures —
2650        // fail loud rather than emit a fail-open empty composite.
2651        #[allow(clippy::expect_used)]
2652        Self::new_signed_with_policy(
2653            request_id,
2654            payload,
2655            signing_key,
2656            None,
2657            crate::crypto::CryptoPolicy::Classical,
2658        )
2659        .expect("COSE composite signing must not fail for valid keys")
2660    }
2661
2662    /// Create and dual-sign a response with Ed25519 + ML-DSA-65 (Hybrid).
2663    pub fn new_signed_hybrid(
2664        request_id: u64,
2665        payload: Vec<u8>,
2666        signing_key: &SigningKey,
2667        pq_signing_key: &crate::crypto::pq::MlDsaSigningKey,
2668    ) -> Self {
2669        // Infallible: the PQ key is statically present, so the only failure
2670        // left is a CBOR-encoding error over fixed-shape COSE structures —
2671        // fail loud rather than emit a fail-open empty composite.
2672        #[allow(clippy::expect_used)]
2673        Self::new_signed_with_policy(
2674            request_id,
2675            payload,
2676            signing_key,
2677            Some(pq_signing_key),
2678            crate::crypto::CryptoPolicy::Hybrid,
2679        )
2680        .expect("COSE composite signing must not fail for valid keys")
2681    }
2682
2683    /// Create and sign a response under an explicit [`CryptoPolicy`].
2684    ///
2685    /// Mirrors [`SignedEnvelope::new_signed_with_policy`]:
2686    /// - `Hybrid`: EdDSA + ML-DSA-65 nested composite; `pq_signing_key` MUST be
2687    ///   `Some`; absence is a fail-closed construction error returned as `Err`.
2688    ///
2689    /// `sig`/`cnf` are always populated with the raw EdDSA signature + signer
2690    /// public key. The COSE build is **fail-closed**: a missing mandatory PQ
2691    /// key or a COSE encoding error is propagated as `Err` rather than
2692    /// silently emitting an empty (fail-open) composite, matching the request
2693    /// side.
2694    pub fn new_signed_with_policy(
2695        request_id: u64,
2696        payload: Vec<u8>,
2697        signing_key: &SigningKey,
2698        pq_signing_key: Option<&crate::crypto::pq::MlDsaSigningKey>,
2699        policy: crate::crypto::CryptoPolicy,
2700    ) -> Result<Self> {
2701        Self::new_signed_with_challenge(
2702            request_id,
2703            payload,
2704            None,
2705            signing_key,
2706            pq_signing_key,
2707            policy,
2708        )
2709    }
2710
2711    /// Create and sign a response that also advertises the server's current
2712    /// challenge in the fixed response slot (§4.7).
2713    ///
2714    /// The challenge is part of the signed transcript, so a denial's challenge
2715    /// is as authentic as its payload.
2716    pub fn new_signed_with_challenge(
2717        request_id: u64,
2718        payload: Vec<u8>,
2719        server_challenge: Option<Vec<u8>>,
2720        signing_key: &SigningKey,
2721        pq_signing_key: Option<&crate::crypto::pq::MlDsaSigningKey>,
2722        policy: crate::crypto::CryptoPolicy,
2723    ) -> Result<Self> {
2724        let signing_data = Self::bind_server_challenge(
2725            Self::signing_data(request_id, &payload),
2726            server_challenge.as_deref(),
2727        );
2728
2729        let signature_obj = signing_key.sign(&signing_data);
2730        let sig: [u8; 64] = signature_obj.to_bytes();
2731        let cnf: [u8; 32] = signing_key.verifying_key().to_bytes();
2732
2733        // SECURITY: no empty-cose fallback (mirrors SignedEnvelope). A missing
2734        // mandatory PQ key or a COSE encoding error is a fail-closed
2735        // construction error propagated to the caller — never substitute an
2736        // empty (fail-open) composite, never downgrade to classical.
2737        let cose = Self::build_cose(signing_key, pq_signing_key, policy, &signing_data)?;
2738
2739        Ok(Self {
2740            request_id,
2741            payload,
2742            encrypted_response: None,
2743            sig,
2744            cnf,
2745            cose,
2746            policy,
2747            server_challenge,
2748        })
2749    }
2750
2751    /// Seal a unary response to the request's one-shot recipient, then
2752    /// hybrid-sign the ciphertext in the response signature domain.
2753    pub fn new_signed_encrypted(
2754        request_id: u64,
2755        payload: Vec<u8>,
2756        signing_key: &SigningKey,
2757        pq_signing_key: &crate::crypto::pq::MlDsaSigningKey,
2758        recipient: &crate::crypto::hybrid_kem::RecipientPublic,
2759        request_iat: i64,
2760        request_nonce: &[u8; 16],
2761        service_domain: &str,
2762    ) -> EnvelopeResult<Self> {
2763        Self::new_signed_encrypted_with_challenge(
2764            request_id,
2765            payload,
2766            None,
2767            signing_key,
2768            pq_signing_key,
2769            recipient,
2770            request_iat,
2771            request_nonce,
2772            service_domain,
2773        )
2774    }
2775
2776    /// Seal a unary response that also advertises the server's current
2777    /// challenge, so a denial on a confidential carrier carries one too.
2778    ///
2779    /// The challenge is a public server value and rides in the cleartext slot
2780    /// — a client that cannot yet form an admissible proof must be able to
2781    /// read it — but it is bound into the sealed response's signature
2782    /// transcript, so it can be neither stripped nor substituted.
2783    #[allow(clippy::too_many_arguments)]
2784    pub fn new_signed_encrypted_with_challenge(
2785        request_id: u64,
2786        payload: Vec<u8>,
2787        server_challenge: Option<Vec<u8>>,
2788        signing_key: &SigningKey,
2789        pq_signing_key: &crate::crypto::pq::MlDsaSigningKey,
2790        recipient: &crate::crypto::hybrid_kem::RecipientPublic,
2791        request_iat: i64,
2792        request_nonce: &[u8; 16],
2793        service_domain: &str,
2794    ) -> EnvelopeResult<Self> {
2795        validate_service_domain(service_domain)
2796            .map_err(|e| EnvelopeError::Encryption(e.to_string()))?;
2797        let mut plaintext = Vec::new();
2798        {
2799            let mut message = capnp::message::Builder::new_default();
2800            let mut builder =
2801                message.init_root::<crate::common_capnp::response_plaintext::Builder>();
2802            builder.set_request_id(request_id);
2803            builder.set_payload(&payload);
2804            capnp::serialize::write_message(&mut plaintext, &message).map_err(|e| {
2805                EnvelopeError::Encryption(format!("serialize response plaintext: {e}"))
2806            })?;
2807        }
2808        let server_identity = signing_key.verifying_key().to_bytes();
2809        let aad = encrypted_response_external_aad(
2810            request_id,
2811            request_iat,
2812            request_nonce,
2813            &server_identity,
2814            recipient,
2815            service_domain,
2816        )?;
2817        let ciphertext =
2818            crate::crypto::cose_encrypt::seal_to_recipient(recipient, &plaintext, &aad, 0, 0)
2819                .map_err(|e| {
2820                    EnvelopeError::Encryption(format!("response HyKEM seal failed: {e}"))
2821                })?;
2822        if ciphertext.len() > MAX_ENCRYPTED_RESPONSE_BYTES {
2823            return Err(EnvelopeError::Encryption(
2824                "encrypted response exceeds envelope limit".into(),
2825            ));
2826        }
2827        let signing_data = Self::bind_server_challenge(
2828            Self::encrypted_signing_data(request_id, &ciphertext, service_domain)?,
2829            server_challenge.as_deref(),
2830        );
2831        let signature_obj = signing_key.sign(&signing_data);
2832        let cose = Self::build_cose(
2833            signing_key,
2834            Some(pq_signing_key),
2835            crate::crypto::CryptoPolicy::Hybrid,
2836            &signing_data,
2837        )
2838        .map_err(|e| EnvelopeError::Encryption(format!("sign sealed response: {e}")))?;
2839        Ok(Self {
2840            request_id,
2841            payload: Vec::new(),
2842            encrypted_response: Some(ciphertext),
2843            sig: signature_obj.to_bytes(),
2844            cnf: server_identity,
2845            cose,
2846            policy: crate::crypto::CryptoPolicy::Hybrid,
2847            server_challenge,
2848        })
2849    }
2850
2851    /// Open a previously verified sealed response with the client's one-shot
2852    /// recipient and the transcript retained by the pending call.
2853    pub(crate) fn open_encrypted(
2854        &self,
2855        recipient_keypair: &crate::crypto::hybrid_kem::RecipientKeypair,
2856        recipient_public: &crate::crypto::hybrid_kem::RecipientPublic,
2857        request_iat: i64,
2858        request_nonce: &[u8; 16],
2859        expected_server_identity: &[u8; 32],
2860        service_domain: &str,
2861    ) -> Result<Vec<u8>> {
2862        let ciphertext = self
2863            .encrypted_response
2864            .as_deref()
2865            .ok_or_else(|| anyhow!("cleartext response rejected: sealed response required"))?;
2866        if &self.cnf != expected_server_identity {
2867            anyhow::bail!("sealed response server identity does not match pending call");
2868        }
2869        let aad = encrypted_response_external_aad(
2870            self.request_id,
2871            request_iat,
2872            request_nonce,
2873            expected_server_identity,
2874            recipient_public,
2875            service_domain,
2876        )?;
2877        let plaintext = crate::crypto::cose_encrypt::open_from_recipient(
2878            recipient_keypair,
2879            ciphertext,
2880            &aad,
2881            0,
2882            0,
2883        )
2884        .map_err(|e| anyhow!("response HyKEM open failed: {e}"))?;
2885        let reader = read_exact_envelope_message(&plaintext)?;
2886        let inner = reader.get_root::<crate::common_capnp::response_plaintext::Reader>()?;
2887        let inner_request_id = inner.get_request_id();
2888        if inner_request_id != self.request_id {
2889            anyhow::bail!(
2890                "inner/outer response request id mismatch: {} != {}",
2891                inner_request_id,
2892                self.request_id
2893            );
2894        }
2895        Ok(inner.get_payload()?.to_vec())
2896    }
2897
2898    /// Build the nested COSE composite over the response signing-data per policy.
2899    /// Returns `Err` on encoding failure — callers MUST NOT substitute an empty
2900    /// cose (that would fail open at verify time). Bound to the RESPONSE domain.
2901    fn build_cose(
2902        signing_key: &SigningKey,
2903        pq_signing_key: Option<&crate::crypto::pq::MlDsaSigningKey>,
2904        policy: crate::crypto::CryptoPolicy,
2905        signing_data: &[u8],
2906    ) -> Result<Vec<u8>> {
2907        let pq = if policy.uses_pq() {
2908            Some(pq_signing_key.ok_or_else(|| {
2909                anyhow!("mandatory Hybrid suite requires an ML-DSA-65 response signing key")
2910            })?)
2911        } else {
2912            None
2913        };
2914        let aad = response_envelope_external_aad();
2915        crate::crypto::cose_sign::sign_composite(signing_key, pq, signing_data, &aad)
2916    }
2917
2918    /// Verify an EdDSA-only response in compatibility tests.
2919    ///
2920    /// Convenience wrapper mirroring [`SignedEnvelope::verify`]: uses the
2921    /// `Classical` policy and no PQ trust store. For Hybrid enforcement use
2922    /// [`Self::verify_with`].
2923    #[cfg(any(test, feature = "test-classical-policy"))]
2924    pub fn verify(&self, expected_pubkey: Option<&VerifyingKey>) -> Result<()> {
2925        self.verify_with(
2926            expected_pubkey,
2927            None,
2928            crate::crypto::CryptoPolicy::Classical,
2929        )
2930    }
2931
2932    /// Verify with an explicit kid-anchored PQ trust store and verify policy.
2933    ///
2934    /// Mirrors [`SignedEnvelope::verify_with`]'s mandatory-hybrid semantics:
2935    /// - `pq_store`: when `Some`, resolves the trust-anchored ML-DSA-65 key for
2936    ///   the response's EdDSA signer (`cnf`); the outer COSE entry must verify
2937    ///   against it and its kid must match (kid-anchoring).
2938    /// - `verify_policy = Hybrid` requires an anchored ML-DSA-65 key and the
2939    ///   intact outer signature. Unanchored and classical-only responses fail.
2940    pub fn verify_with(
2941        &self,
2942        expected_pubkey: Option<&VerifyingKey>,
2943        pq_store: Option<&dyn PqTrustStore>,
2944        verify_policy: crate::crypto::CryptoPolicy,
2945    ) -> Result<()> {
2946        let verifying_key = VerifyingKey::from_bytes(&self.cnf)
2947            .map_err(|_| anyhow::anyhow!("Invalid signer public key"))?;
2948
2949        if let Some(expected) = expected_pubkey {
2950            if !bool::from(verifying_key.to_bytes().ct_eq(&expected.to_bytes())) {
2951                anyhow::bail!("Response signed by unexpected key");
2952            }
2953        }
2954
2955        self.verify_cose(&verifying_key, pq_store, verify_policy, None)
2956    }
2957
2958    /// Verify a sealed response against the destination retained by the
2959    /// pending call. Generic verification deliberately cannot authenticate an
2960    /// encrypted response because it has no expected service domain.
2961    pub(crate) fn verify_encrypted_with_service_domain(
2962        &self,
2963        expected_pubkey: &VerifyingKey,
2964        pq_store: &dyn PqTrustStore,
2965        service_domain: &str,
2966    ) -> Result<()> {
2967        validate_service_domain(service_domain)?;
2968        if self.encrypted_response.is_none() {
2969            anyhow::bail!("cleartext response rejected: sealed response required");
2970        }
2971        let verifying_key = VerifyingKey::from_bytes(&self.cnf)
2972            .map_err(|_| anyhow::anyhow!("Invalid signer public key"))?;
2973        if !bool::from(verifying_key.to_bytes().ct_eq(&expected_pubkey.to_bytes())) {
2974            anyhow::bail!("Response signed by unexpected key");
2975        }
2976        self.verify_cose(
2977            &verifying_key,
2978            Some(pq_store),
2979            crate::crypto::CryptoPolicy::Hybrid,
2980            Some(service_domain),
2981        )
2982    }
2983
2984    /// Verify the COSE composite signature (authoritative auth check).
2985    ///
2986    /// Mirrors [`SignedEnvelope::verify_cose`]: the raw EdDSA `sig`/`cnf` is not
2987    /// trusted on its own; this re-verifies the EdDSA component inside the COSE
2988    /// composite and (under Hybrid policy) the kid-anchored ML-DSA-65 component.
2989    fn verify_cose(
2990        &self,
2991        ed_vk: &VerifyingKey,
2992        pq_store: Option<&dyn PqTrustStore>,
2993        verify_policy: crate::crypto::CryptoPolicy,
2994        service_domain: Option<&str>,
2995    ) -> Result<()> {
2996        let signing_bytes = self.encrypted_response.as_deref().unwrap_or(&self.payload);
2997        let signing_data = if self.encrypted_response.is_some() {
2998            let service_domain = service_domain.ok_or_else(|| {
2999                anyhow!("encrypted response verification requires the pending service domain")
3000            })?;
3001            Self::encrypted_signing_data(self.request_id, signing_bytes, service_domain)?
3002        } else {
3003            Self::signing_data(self.request_id, signing_bytes)
3004        };
3005        let signing_data =
3006            Self::bind_server_challenge(signing_data, self.server_challenge.as_deref());
3007        let aad = response_envelope_external_aad();
3008
3009        // Per-identity PQ requirement, mirroring the request side: an anchored
3010        // responder MUST present a verifying outer PQ layer regardless of the
3011        // global policy; an unanchored responder falls back to that policy.
3012        let anchored_pq = pq_store.and_then(|store| store.ml_dsa_key_for(&self.cnf));
3013        if anchored_pq.is_none() && verify_policy.uses_pq() {
3014            return Err(anyhow!(
3015                "mandatory Hybrid suite requires an anchored ML-DSA-65 response key"
3016            ));
3017        }
3018        let require_pq = anchored_pq.is_some();
3019
3020        crate::crypto::cose_sign::verify_composite(
3021            &self.cose,
3022            ed_vk,
3023            anchored_pq.as_ref(),
3024            &signing_data,
3025            &aad,
3026            require_pq,
3027        )
3028        .map_err(|e| anyhow::anyhow!("Response signature verification failed: {e}"))?;
3029
3030        Ok(())
3031    }
3032
3033    /// Get the signer's public key.
3034    pub fn cnf_key(&self) -> Result<VerifyingKey> {
3035        VerifyingKey::from_bytes(&self.cnf)
3036            .map_err(|_| anyhow::anyhow!("Invalid signer public key"))
3037    }
3038}
3039
3040impl ToCapnp for ResponseEnvelope {
3041    type Builder<'a> = common_capnp::response_envelope::Builder<'a>;
3042
3043    fn write_to(&self, builder: &mut Self::Builder<'_>) {
3044        builder.set_request_id(self.request_id);
3045        builder.set_payload(&self.payload);
3046        if let Some(ref ciphertext) = self.encrypted_response {
3047            builder.set_encrypted_response(ciphertext);
3048        }
3049        builder.set_sig(&self.sig);
3050        builder.set_cnf(&self.cnf);
3051        builder.set_cose(&self.cose);
3052        if let Some(ref challenge) = self.server_challenge {
3053            builder.set_server_challenge(challenge);
3054        }
3055    }
3056}
3057
3058impl FromCapnp for ResponseEnvelope {
3059    type Reader<'a> = common_capnp::response_envelope::Reader<'a>;
3060
3061    fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
3062        let sig_data = reader.get_sig()?;
3063        if sig_data.len() != 64 {
3064            anyhow::bail!("Invalid sig length: {}", sig_data.len());
3065        }
3066        let mut sig = [0u8; 64];
3067        sig.copy_from_slice(sig_data);
3068
3069        let cnf_data = reader.get_cnf()?;
3070        if cnf_data.len() != 32 {
3071            anyhow::bail!("Invalid cnf length: {}", cnf_data.len());
3072        }
3073        let mut cnf = [0u8; 32];
3074        cnf.copy_from_slice(cnf_data);
3075
3076        let cose = reader.get_cose()?.to_vec();
3077        let encrypted_data = reader.get_encrypted_response()?;
3078        let payload_data = reader.get_payload()?;
3079        if !encrypted_data.is_empty() && !payload_data.is_empty() {
3080            anyhow::bail!("encrypted response carries a non-empty cleartext payload");
3081        }
3082        let payload = payload_data.to_vec();
3083        let encrypted_response = {
3084            let data = encrypted_data;
3085            if data.is_empty() {
3086                None
3087            } else {
3088                if data.len() > MAX_ENCRYPTED_RESPONSE_BYTES {
3089                    anyhow::bail!("encryptedResponse exceeds envelope limit");
3090                }
3091                Some(data.to_vec())
3092            }
3093        };
3094
3095        // `policy` is a signing-time concept; the verifier supplies the verify
3096        // policy explicitly, so decode to the default here (mirrors SignedEnvelope).
3097        // The advertised challenge is bounded by the profile's own limits: a
3098        // value outside 16..64 bytes is not a challenge this profile can ever
3099        // have issued, so it is rejected here rather than carried onward.
3100        let challenge_data = reader.get_server_challenge()?;
3101        let server_challenge = if challenge_data.is_empty() {
3102            None
3103        } else {
3104            if challenge_data.len() < crate::proof::MIN_CHALLENGE_BYTES
3105                || challenge_data.len() > crate::proof::MAX_CHALLENGE_BYTES
3106            {
3107                anyhow::bail!(
3108                    "serverChallenge length {} outside the profile's {}..{} bounds",
3109                    challenge_data.len(),
3110                    crate::proof::MIN_CHALLENGE_BYTES,
3111                    crate::proof::MAX_CHALLENGE_BYTES
3112                );
3113            }
3114            Some(challenge_data.to_vec())
3115        };
3116
3117        Ok(Self {
3118            request_id: reader.get_request_id(),
3119            payload,
3120            encrypted_response,
3121            sig,
3122            cnf,
3123            cose,
3124            policy: crate::crypto::CryptoPolicy::default(),
3125            server_challenge,
3126        })
3127    }
3128}
3129
3130/// Unwrap and verify a SignedEnvelope from wire bytes.
3131///
3132/// Dispatches on `opts.verification` to select FixedSigner or AnySigner mode.
3133/// If `opts.decryption_key` is set and the envelope is encrypted, decrypts
3134/// the envelope after signature verification.
3135pub fn unwrap_and_verify(
3136    request: &[u8],
3137    opts: &UnwrapOptions<'_>,
3138) -> Result<(SignedEnvelope, Vec<u8>)> {
3139    let reader = read_exact_envelope_message(request)?;
3140    let signed_reader = reader.get_root::<crate::common_capnp::signed_envelope::Reader>()?;
3141    let mut signed = SignedEnvelope::read_from(signed_reader)?;
3142
3143    // Reject stale or future requests before signature or KEM work without
3144    // mutating replay state. The timestamp is revalidated at final commit.
3145    signed.validate_timestamp()?;
3146
3147    // Authenticate first without mutating replay state. The lifecycle commits
3148    // the nonce only after canonical COSE parsing, external-
3149    // AAD authentication, decryption, and inner/outer equality all succeed.
3150    match &opts.verification {
3151        EnvelopeVerification::FixedSigner(pubkey) => {
3152            if !bool::from(signed.cnf.ct_eq(&pubkey.to_bytes())) {
3153                return Err(EnvelopeError::SignerMismatch {
3154                    expected: hex::encode(pubkey.to_bytes()),
3155                    actual: hex::encode(signed.cnf),
3156                }
3157                .into());
3158            }
3159            signed.verify_cose(pubkey, opts.pq_store, opts.verify_policy)?;
3160        }
3161        EnvelopeVerification::AnySigner => {
3162            let verifying_key = VerifyingKey::from_bytes(&signed.cnf).map_err(|_| {
3163                EnvelopeError::InvalidPublicKey {
3164                    expected: 32,
3165                    actual: 0,
3166                }
3167            })?;
3168            signed.verify_cose(&verifying_key, opts.pq_store, opts.verify_policy)?;
3169        }
3170    }
3171
3172    // INV-2 receive-side policy (#1042): the carrier requirement is supplied
3173    // by the accept boundary, never by request bytes. Check it only after the
3174    // signature above, so unauthenticated input cannot
3175    // select or exercise a signed policy-error path. A non-empty marker alone
3176    // is not sufficient: encrypted envelopes continue through canonical KEM
3177    // open below before any claims or handler sees their payload.
3178    if opts.require_encrypted && !signed.is_encrypted() {
3179        return Err(anyhow!(
3180            "cleartext request envelope rejected: carrier requires #mesh-kem encryption (INV-2)"
3181        ));
3182    }
3183
3184    if signed.is_encrypted() {
3185        if let Some(decryption_key) = opts.decryption_key {
3186            // The node's #mesh-kem keypair is deterministically derived from its
3187            // Ed25519 identity key (S1), so the decryption seam keeps taking the
3188            // signing key and derives the KEM keypair here.
3189            let kem_keypair = crate::node_identity::derive_mesh_kem_recipient(decryption_key)
3190                .map_err(|e| anyhow!("derive #mesh-kem keypair for decryption: {e}"))?;
3191            signed.decrypt_in_place_mesh_kem(&kem_keypair)?;
3192        } else {
3193            return Err(anyhow!(
3194                "encrypted envelope but no decryption key configured"
3195            ));
3196        }
3197    }
3198
3199    // This is the single atomic replay commit for the public compatibility
3200    // lifecycle. Invalid signatures, non-canonical ciphertext, wrong AAD,
3201    // failed decryption, and inner/outer mismatch cannot consume or evict cache
3202    // capacity; concurrent identical valid inputs race here and only one wins.
3203    signed.check_replay(opts.nonce_cache)?;
3204
3205    let payload = signed.payload().to_vec();
3206    Ok((signed, payload))
3207}
3208
3209/// Unwrap, verify, and build an `EnvelopeContext` from wire bytes.
3210///
3211/// Context construction depends on verification mode:
3212/// - `FixedSigner` → `key_derived_subject = "system"` (inproc/IPC callers)
3213/// - `AnySigner` → `key_derived_subject = anonymous` (WebTransport, identity from JWT)
3214#[cfg(not(target_arch = "wasm32"))]
3215pub fn unwrap_envelope(
3216    request: &[u8],
3217    opts: &UnwrapOptions<'_>,
3218) -> Result<(crate::service::EnvelopeContext, Vec<u8>)> {
3219    let (signed, payload) = unwrap_and_verify(request, opts)?;
3220
3221    let ctx = match &opts.verification {
3222        EnvelopeVerification::FixedSigner(_) => {
3223            crate::service::EnvelopeContext::from_verified_as_system(&signed)
3224        }
3225        EnvelopeVerification::AnySigner => crate::service::EnvelopeContext::from_verified(&signed),
3226    };
3227
3228    Ok((ctx, payload))
3229}
3230
3231/// Unwrap an EdDSA-only response in compatibility tests.
3232///
3233/// Convenience wrapper over [`unwrap_response_with`] using the `Classical`
3234/// policy and no PQ trust store. Mirrors [`SignedEnvelope::verify`]; for Hybrid
3235/// enforcement use [`unwrap_response_with`].
3236///
3237/// # Arguments
3238///
3239/// * `response` - Raw bytes containing a serialized ResponseEnvelope
3240/// * `expected_pubkey` - Optional expected signer public key
3241///
3242/// # Returns
3243///
3244/// On success, returns `(request_id, payload)` where:
3245/// - `request_id` correlates with the original request
3246/// - `payload` is the inner response bytes
3247///
3248/// # Errors
3249///
3250/// Returns error if:
3251/// - Deserialization fails
3252/// - Signature verification fails
3253/// - Signer doesn't match expected_pubkey (if provided)
3254#[cfg(any(test, feature = "test-classical-policy"))]
3255pub fn unwrap_response(
3256    response: &[u8],
3257    expected_pubkey: Option<&VerifyingKey>,
3258) -> Result<(u64, Vec<u8>)> {
3259    unwrap_response_with(
3260        response,
3261        expected_pubkey,
3262        None,
3263        crate::crypto::CryptoPolicy::Classical,
3264    )
3265}
3266
3267/// Unwrap and verify a ResponseEnvelope under an explicit kid-anchored PQ trust
3268/// store + verify policy (#275).
3269///
3270/// Enforces the same mandatory-hybrid semantics as [`unwrap_and_verify`]: the
3271/// signer must have an anchored ML-DSA-65 key and the outer signature must
3272/// verify. Missing anchors and classical-only responses fail closed.
3273pub fn unwrap_response_with(
3274    response: &[u8],
3275    expected_pubkey: Option<&VerifyingKey>,
3276    pq_store: Option<&dyn PqTrustStore>,
3277    verify_policy: crate::crypto::CryptoPolicy,
3278) -> Result<(u64, Vec<u8>)> {
3279    let envelope = read_response_envelope(response, false)?;
3280
3281    if envelope.encrypted_response.is_some() {
3282        anyhow::bail!("encrypted response requires one-shot pending decapsulation material");
3283    }
3284
3285    // Verify the COSE composite under the supplied policy + anchor.
3286    envelope.verify_with(expected_pubkey, pq_store, verify_policy)?;
3287
3288    Ok((envelope.request_id, envelope.payload))
3289}
3290
3291/// Bounded response parse with an early encrypted-field gate. When encryption
3292/// is required, the cleartext payload is never copied or surfaced.
3293pub(crate) fn read_response_envelope(
3294    response: &[u8],
3295    require_encrypted: bool,
3296) -> Result<ResponseEnvelope> {
3297    let reader = read_exact_envelope_message(response)?;
3298    let response_reader = reader.get_root::<crate::common_capnp::response_envelope::Reader>()?;
3299    if require_encrypted && response_reader.get_encrypted_response()?.is_empty() {
3300        anyhow::bail!("cleartext response rejected before payload use (INV-2)");
3301    }
3302    ResponseEnvelope::read_from(response_reader)
3303}
3304
3305#[cfg(test)]
3306#[allow(clippy::expect_used, clippy::unwrap_used)]
3307mod tests {
3308    use super::*;
3309    use crate::crypto::signing::generate_signing_keypair;
3310    use parking_lot::Mutex;
3311    use std::collections::HashSet;
3312
3313    /// Simple in-memory nonce cache for testing.
3314    struct TestNonceCache {
3315        seen: Mutex<HashSet<[u8; 16]>>,
3316    }
3317
3318    impl TestNonceCache {
3319        fn new() -> Self {
3320            Self {
3321                seen: Mutex::new(HashSet::new()),
3322            }
3323        }
3324    }
3325
3326    impl NonceCache for TestNonceCache {
3327        fn check_and_insert(&self, nonce: &[u8; 16]) -> bool {
3328            self.seen.lock().insert(*nonce)
3329        }
3330    }
3331
3332    /// Test envelopes default to Classical signing; the existing tests exercise
3333    /// the EdDSA path. Hybrid/cross-compat is covered by the dedicated M3 tests
3334    /// below.
3335    fn test_new_signed(envelope: RequestEnvelope, signing_key: &SigningKey) -> SignedEnvelope {
3336        SignedEnvelope::new_signed(envelope, signing_key)
3337    }
3338
3339    /// Fresh, OsRng-backed 16-byte nonce for tests.
3340    /// Derive a nonce that is guaranteed to differ from `original` in every byte
3341    /// via bitwise complement.
3342    #[allow(dead_code)]
3343    fn distinct_test_nonce(original: &[u8; 16]) -> [u8; 16] {
3344        let mut out = *original;
3345        for b in out.iter_mut() {
3346            *b = !*b;
3347        }
3348        out
3349    }
3350
3351    fn signed_envelope_to_wire(envelope: &SignedEnvelope) -> Vec<u8> {
3352        let mut message = capnp::message::Builder::new_default();
3353        {
3354            let mut builder = message.init_root::<common_capnp::signed_envelope::Builder>();
3355            envelope.write_to(&mut builder);
3356        }
3357        let mut wire = Vec::new();
3358        capnp::serialize::write_message(&mut wire, &message).expect("serialize signed envelope");
3359        wire
3360    }
3361
3362    /// In-memory kid-anchored PQ trust store for tests.
3363    struct TestPqStore {
3364        bindings: Vec<([u8; 32], crate::crypto::pq::MlDsaVerifyingKey)>,
3365    }
3366    impl PqTrustStore for TestPqStore {
3367        fn ml_dsa_key_for(
3368            &self,
3369            ed25519_pubkey: &[u8; 32],
3370        ) -> Option<crate::crypto::pq::MlDsaVerifyingKey> {
3371            self.bindings
3372                .iter()
3373                .find(|(k, _)| k == ed25519_pubkey)
3374                .map(|(_, vk)| {
3375                    crate::crypto::pq::ml_dsa_vk_from_bytes(&crate::crypto::pq::ml_dsa_vk_bytes(vk))
3376                        .expect("re-decode pq vk")
3377                })
3378        }
3379    }
3380
3381    #[test]
3382    fn test_request_envelope() {
3383        let envelope = RequestEnvelope::anonymous(vec![1, 2, 3]);
3384        assert_eq!(envelope.payload, vec![1, 2, 3]);
3385        assert!(envelope.request_id > 0);
3386        assert!(envelope.iat > 0);
3387        assert!(envelope.nonce.iter().any(|&b| b != 0)); // Not all zeros
3388    }
3389
3390    #[test]
3391    fn test_request_id_increments() {
3392        let e1 = RequestEnvelope::anonymous(vec![]);
3393        let e2 = RequestEnvelope::anonymous(vec![]);
3394        assert!(e2.request_id > e1.request_id);
3395    }
3396
3397    #[test]
3398    fn test_signed_envelope_sign_verify() -> crate::EnvelopeResult<()> {
3399        let (signing_key, verifying_key) = generate_signing_keypair();
3400        let nonce_cache = TestNonceCache::new();
3401
3402        let envelope = RequestEnvelope::anonymous(vec![1, 2, 3, 4]);
3403        let signed = test_new_signed(envelope, &signing_key);
3404
3405        // Verify should succeed
3406        signed.verify(&verifying_key, &nonce_cache)?;
3407        Ok(())
3408    }
3409
3410    #[test]
3411    fn test_signed_envelope_wrong_key_fails() {
3412        let (signing_key, _) = generate_signing_keypair();
3413        let (_, wrong_verifying_key) = generate_signing_keypair();
3414        let nonce_cache = TestNonceCache::new();
3415
3416        let envelope = RequestEnvelope::anonymous(vec![1, 2, 3, 4]);
3417        let signed = test_new_signed(envelope, &signing_key);
3418
3419        // Verify with wrong key should fail
3420        let result = signed.verify(&wrong_verifying_key, &nonce_cache);
3421        assert!(matches!(result, Err(EnvelopeError::SignerMismatch { .. })));
3422    }
3423
3424    #[test]
3425    fn test_signed_envelope_replay_fails() -> crate::EnvelopeResult<()> {
3426        let (signing_key, verifying_key) = generate_signing_keypair();
3427        let nonce_cache = TestNonceCache::new();
3428
3429        let envelope = RequestEnvelope::anonymous(vec![1, 2, 3, 4]);
3430        let signed = test_new_signed(envelope, &signing_key);
3431
3432        // First verify succeeds
3433        signed.verify(&verifying_key, &nonce_cache)?;
3434
3435        // Replay (same nonce) should fail
3436        let result = signed.verify(&verifying_key, &nonce_cache);
3437        assert!(matches!(result, Err(EnvelopeError::ReplayAttack(_))));
3438        Ok(())
3439    }
3440
3441    #[test]
3442    fn test_signed_envelope_accessors() {
3443        let (signing_key, _) = generate_signing_keypair();
3444
3445        let envelope = RequestEnvelope::anonymous(vec![5, 6, 7]);
3446        let signed = test_new_signed(envelope, &signing_key);
3447
3448        assert!(signed.request_id() > 0);
3449        assert_eq!(signed.payload(), &[5, 6, 7]);
3450    }
3451
3452    #[test]
3453    fn test_capnp_roundtrip_envelope() -> anyhow::Result<()> {
3454        use capnp::message::Builder;
3455
3456        let envelope = RequestEnvelope::anonymous(vec![1, 2, 3, 4]);
3457
3458        let mut message = Builder::new_default();
3459        let mut builder = message.init_root::<common_capnp::request_envelope::Builder>();
3460        envelope.write_to(&mut builder);
3461
3462        let reader = builder.into_reader();
3463        let decoded = RequestEnvelope::read_from(reader)?;
3464
3465        assert_eq!(envelope.request_id, decoded.request_id);
3466        assert_eq!(envelope.payload, decoded.payload);
3467        assert_eq!(envelope.nonce, decoded.nonce);
3468        assert_eq!(envelope.iat, decoded.iat);
3469        assert_eq!(envelope.authorization, decoded.authorization);
3470        assert_eq!(envelope.delegation_token, decoded.delegation_token);
3471        assert_eq!(envelope.wth, decoded.wth);
3472        assert_eq!(envelope.client_dh_public, decoded.client_dh_public);
3473        Ok(())
3474    }
3475
3476    #[test]
3477    fn test_capnp_roundtrip_signed_envelope() -> Result<(), Box<dyn std::error::Error>> {
3478        use capnp::message::Builder;
3479
3480        let (signing_key, verifying_key) = generate_signing_keypair();
3481        let envelope = RequestEnvelope::anonymous(vec![1, 2, 3]);
3482        let signed = test_new_signed(envelope, &signing_key);
3483
3484        let mut message = Builder::new_default();
3485        let mut builder = message.init_root::<common_capnp::signed_envelope::Builder>();
3486        signed.write_to(&mut builder);
3487
3488        let reader = builder.into_reader();
3489        let decoded = SignedEnvelope::read_from(reader)?;
3490
3491        assert_eq!(signed.envelope.request_id, decoded.envelope.request_id);
3492        assert_eq!(signed.envelope.payload, decoded.envelope.payload);
3493        assert_eq!(signed.sig, decoded.sig);
3494        assert_eq!(signed.cnf, decoded.cnf);
3495
3496        // Verify the decoded envelope still has valid signature
3497        decoded.verify_signature_only(&verifying_key)?;
3498        Ok(())
3499    }
3500
3501    // =========================================================================
3502    // Subject tests
3503    // =========================================================================
3504
3505    #[test]
3506    fn test_subject_display_roundtrip() {
3507        let cases = vec![
3508            Subject::new("alice"),
3509            Subject::new("bob"),
3510            Subject::new("gpu-1"),
3511            Subject::new("charlie"),
3512            Subject::anonymous(),
3513        ];
3514
3515        for subject in cases {
3516            let s = subject.to_string();
3517            let parsed: Subject = s.parse().expect("parse subject roundtrip");
3518            assert_eq!(subject, parsed, "Roundtrip failed for {s}");
3519        }
3520    }
3521
3522    #[test]
3523    fn test_subject_display_format() {
3524        assert_eq!(Subject::new("alice").to_string(), "alice");
3525        assert_eq!(Subject::new("bob").to_string(), "bob");
3526        assert_eq!(Subject::anonymous().to_string(), "anonymous");
3527    }
3528
3529    #[test]
3530    fn test_subject_legacy_prefix_parsing() {
3531        assert_eq!(
3532            "local:alice".parse::<Subject>().expect("parse local:alice"),
3533            Subject::new("alice")
3534        );
3535        assert_eq!(
3536            "token:bob".parse::<Subject>().expect("parse token:bob"),
3537            Subject::new("bob")
3538        );
3539        assert_eq!(
3540            "peer:gpu-1".parse::<Subject>().expect("parse peer:gpu-1"),
3541            Subject::new("gpu-1")
3542        );
3543        assert_eq!(
3544            "user:charlie"
3545                .parse::<Subject>()
3546                .expect("parse user:charlie"),
3547            Subject::new("charlie")
3548        );
3549        assert_eq!(
3550            "alice".parse::<Subject>().expect("parse alice"),
3551            Subject::new("alice")
3552        );
3553        assert_eq!(
3554            "unknown:foo".parse::<Subject>().expect("parse unknown:foo"),
3555            Subject::new("unknown:foo")
3556        );
3557    }
3558
3559    #[test]
3560    fn test_subject_validate() {
3561        assert!(Subject::new("alice").validate().is_ok());
3562        assert!(Subject::new("bob_123").validate().is_ok());
3563        assert!(Subject::new("gpu-server.1").validate().is_ok());
3564        assert!(Subject::anonymous().validate().is_ok());
3565        assert!(Subject::new("../evil").validate().is_err());
3566        assert!(Subject::new("bob/root").validate().is_err());
3567        assert!(Subject::new("").validate().is_err());
3568        assert!(Subject::new("alice:bob").validate().is_err());
3569    }
3570
3571    #[test]
3572    fn test_subject_hash_eq() {
3573        use std::collections::HashSet;
3574        let mut set = HashSet::new();
3575        set.insert(Subject::new("alice"));
3576        set.insert(Subject::new("alice")); // duplicate
3577        set.insert(Subject::new("bob"));
3578        assert_eq!(set.len(), 2);
3579    }
3580
3581    #[test]
3582    fn test_subject_capnp_roundtrip() -> anyhow::Result<()> {
3583        use capnp::message::Builder;
3584
3585        let cases = vec![
3586            Subject::new("alice"),
3587            Subject::new("bob"),
3588            Subject::new("gpu-1"),
3589            Subject::anonymous(),
3590        ];
3591
3592        for subject in cases {
3593            let mut message = Builder::new_default();
3594            let mut builder = message.init_root::<common_capnp::subject::Builder>();
3595            subject.write_to(&mut builder);
3596
3597            let reader = builder.into_reader();
3598            let decoded = Subject::read_from(reader)?;
3599            assert_eq!(subject, decoded, "Cap'n Proto roundtrip failed");
3600        }
3601        Ok(())
3602    }
3603
3604    #[test]
3605    fn test_subject_from_claims() {
3606        let claims = crate::auth::Claims::new("charlie".to_owned(), 1000, 2000);
3607        assert_eq!(Subject::from(&claims), Subject::new("charlie"));
3608    }
3609
3610    #[test]
3611    fn test_subject_federated_format() {
3612        let s = Subject::federated("https://node-a", "alice");
3613        assert_eq!(s.to_string(), "https://node-a:alice");
3614        assert!(s.is_federated());
3615        assert!(!s.is_anonymous());
3616    }
3617
3618    #[test]
3619    fn test_subject_local_is_not_federated() {
3620        let s = Subject::new("alice");
3621        assert!(!s.is_federated());
3622    }
3623
3624    #[test]
3625    fn test_subject_anonymous_is_not_federated() {
3626        let s = Subject::anonymous();
3627        assert!(!s.is_federated());
3628    }
3629
3630    #[test]
3631    fn test_subject_federated_two_node_scenario() {
3632        use crate::auth::{jwt, Claims};
3633        use ed25519_dalek::SigningKey;
3634
3635        let key_a = SigningKey::from_bytes(&[0xAAu8; 32]);
3636        let vk_a = key_a.verifying_key();
3637        let claims = Claims::new("alice".to_owned(), 0, 9_999_999_999)
3638            .with_issuer("https://node-a".to_owned());
3639        let token = jwt::encode(&claims, &key_a);
3640
3641        let decoded = jwt::decode_with_key(&token, &vk_a, None)
3642            .expect("federated token must verify with issuer key");
3643        assert_eq!(decoded.iss, "https://node-a");
3644        assert_eq!(decoded.sub, "alice");
3645
3646        let subject = Subject::federated(&decoded.iss, &decoded.sub);
3647        assert_eq!(subject.to_string(), "https://node-a:alice");
3648        assert!(subject.is_federated());
3649
3650        let local = Subject::new(&decoded.sub);
3651        assert!(!local.is_federated());
3652    }
3653
3654    #[test]
3655    fn test_authorization_capnp_roundtrip() -> anyhow::Result<()> {
3656        use capnp::message::Builder;
3657
3658        // Test None variant
3659        let auth = Authorization::None;
3660        let mut msg = Builder::new_default();
3661        let mut builder = msg.init_root::<common_capnp::authorization::Builder>();
3662        auth.write_to(&mut builder);
3663        let reader = builder.into_reader();
3664        let decoded = Authorization::read_from(reader)?;
3665        assert_eq!(auth, decoded);
3666
3667        // Test IdJag variant
3668        let auth = Authorization::IdJag("test-token".to_owned());
3669        let mut msg = Builder::new_default();
3670        let mut builder = msg.init_root::<common_capnp::authorization::Builder>();
3671        auth.write_to(&mut builder);
3672        let reader = builder.into_reader();
3673        let decoded = Authorization::read_from(reader)?;
3674        assert_eq!(auth, decoded);
3675
3676        // Test Local variant
3677        let auth = Authorization::Local(TokenClaims {
3678            iss: "https://hyprstream.local".to_owned(),
3679            sub: "alice".to_owned(),
3680            aud: vec!["inference".to_owned(), "registry".to_owned()],
3681            exp: 1700000000,
3682            iat: 1699999000,
3683            jti: "unique-id-123".to_owned(),
3684            scope: vec![],
3685            cnf_jkt: "thumbprint-abc".to_owned(),
3686        });
3687        let mut msg = Builder::new_default();
3688        let mut builder = msg.init_root::<common_capnp::authorization::Builder>();
3689        auth.write_to(&mut builder);
3690        let reader = builder.into_reader();
3691        let decoded = Authorization::read_from(reader)?;
3692        assert_eq!(auth, decoded);
3693
3694        // Test Federated variant
3695        let auth = Authorization::Federated(FederatedToken {
3696            raw: "eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.test".to_owned(),
3697            claims: TokenClaims {
3698                iss: "https://node-a".to_owned(),
3699                sub: "bob".to_owned(),
3700                aud: vec!["https://node-b".to_owned()],
3701                exp: 1700000000,
3702                iat: 1699999000,
3703                jti: "fed-id-456".to_owned(),
3704                scope: vec![],
3705                cnf_jkt: "fed-thumbprint".to_owned(),
3706            },
3707            dpop_proof: Some("dpop-proof-xyz".to_owned()),
3708        });
3709        let mut msg = Builder::new_default();
3710        let mut builder = msg.init_root::<common_capnp::authorization::Builder>();
3711        auth.write_to(&mut builder);
3712        let reader = builder.into_reader();
3713        let decoded = Authorization::read_from(reader)?;
3714        assert_eq!(auth, decoded);
3715
3716        // Test Federated without DPoP proof
3717        let auth = Authorization::Federated(FederatedToken {
3718            raw: "raw-jwt".to_owned(),
3719            claims: TokenClaims {
3720                iss: "https://node-c".to_owned(),
3721                sub: "carol".to_owned(),
3722                aud: vec![],
3723                exp: 0,
3724                iat: 0,
3725                jti: String::new(),
3726                scope: vec![],
3727                cnf_jkt: String::new(),
3728            },
3729            dpop_proof: None,
3730        });
3731        let mut msg = Builder::new_default();
3732        let mut builder = msg.init_root::<common_capnp::authorization::Builder>();
3733        auth.write_to(&mut builder);
3734        let reader = builder.into_reader();
3735        let decoded = Authorization::read_from(reader)?;
3736        assert_eq!(auth, decoded);
3737
3738        Ok(())
3739    }
3740
3741    #[test]
3742    fn test_capnp_roundtrip_envelope_with_authorization() -> anyhow::Result<()> {
3743        use capnp::message::Builder;
3744
3745        let envelope = RequestEnvelope {
3746            request_id: 42,
3747            payload: vec![1, 2, 3],
3748            nonce: generate_nonce(),
3749            iat: 1699999000,
3750            authorization: Authorization::IdJag("my-jwt-token".to_owned()),
3751            delegation_token: Some("delegated".to_owned()),
3752            wth: Some([0xAB; 32]),
3753            client_dh_public: Some([0xCD; 32]),
3754            client_kem_public: None,
3755            response_kem_recipient: None,
3756            service_domain: None,
3757            proof_cwt: None,
3758            authorization_witness: None,
3759        };
3760
3761        let mut message = Builder::new_default();
3762        let mut builder = message.init_root::<common_capnp::request_envelope::Builder>();
3763        envelope.write_to(&mut builder);
3764
3765        let reader = builder.into_reader();
3766        let decoded = RequestEnvelope::read_from(reader)?;
3767
3768        assert_eq!(envelope.request_id, decoded.request_id);
3769        assert_eq!(envelope.payload, decoded.payload);
3770        assert_eq!(envelope.nonce, decoded.nonce);
3771        assert_eq!(envelope.iat, decoded.iat);
3772        assert_eq!(envelope.authorization, decoded.authorization);
3773        assert_eq!(envelope.delegation_token, decoded.delegation_token);
3774        assert_eq!(envelope.wth, decoded.wth);
3775        assert_eq!(envelope.client_dh_public, decoded.client_dh_public);
3776        Ok(())
3777    }
3778
3779    #[test]
3780    fn mesh_kem_envelope_seal_open_roundtrip() {
3781        use crate::node_identity::{derive_mesh_kem_recipient, derive_mesh_mldsa_key};
3782
3783        // Node identity: Ed25519 root → #mesh-mldsa sign key + #mesh-kem keypair.
3784        let (node_sk, node_vk) = generate_signing_keypair();
3785        let pq_sk = derive_mesh_mldsa_key(&node_sk);
3786        let kem_kp = derive_mesh_kem_recipient(&node_sk).expect("derive #mesh-kem");
3787        let kem_pub = kem_kp.public();
3788
3789        let req_id = 777u64;
3790        let payload = vec![9u8, 8, 7, 6];
3791        let envelope = RequestEnvelope {
3792            request_id: req_id,
3793            payload: payload.clone(),
3794            nonce: generate_nonce(),
3795            iat: current_timestamp(),
3796            authorization: Authorization::None,
3797            delegation_token: None,
3798            wth: None,
3799            client_dh_public: None,
3800            client_kem_public: None,
3801            response_kem_recipient: None,
3802            service_domain: None,
3803            proof_cwt: None,
3804            authorization_witness: None,
3805        };
3806
3807        // Seal to the node's #mesh-kem public, dual-signed (EdDSA + ML-DSA-65).
3808        let signed =
3809            SignedEnvelope::new_signed_encrypted_mesh_kem(envelope, &node_sk, &pq_sk, &kem_pub)
3810                .expect("seal");
3811
3812        // Encrypted; plaintext is NOT on the wire; no separate eph/KEM-ct fields.
3813        assert!(signed.is_encrypted());
3814        assert!(signed.encrypted_envelope.is_some());
3815        assert!(signed.client_ephemeral_public.is_none());
3816        assert!(signed.pq_kem_ciphertext.is_none());
3817
3818        // COSE composite signature verifies over the COSE_Encrypt0 bytes.
3819        signed
3820            .verify_signature_only(&node_vk)
3821            .expect("signature over COSE_Encrypt0 verifies");
3822
3823        // Decrypt with the node's #mesh-kem keypair.
3824        let mut opened = signed.clone();
3825        opened.decrypt_in_place_mesh_kem(&kem_kp).expect("open");
3826        assert_eq!(opened.envelope.request_id, req_id);
3827        assert_eq!(opened.envelope.payload, payload);
3828
3829        // Fail-closed: a WRONG #mesh-kem keypair must not open.
3830        let (other_sk, _) = generate_signing_keypair();
3831        let other_kem = derive_mesh_kem_recipient(&other_sk).unwrap();
3832        let mut wrong = signed.clone();
3833        assert!(
3834            wrong.decrypt_in_place_mesh_kem(&other_kem).is_err(),
3835            "wrong #mesh-kem key must not open"
3836        );
3837    }
3838
3839    #[test]
3840    fn mesh_kem_outer_replay_metadata_is_aead_bound() {
3841        // Regression (S4 replay-binding): the outer replay metadata (nonce/iat/
3842        // request_id) is unsigned on the wire — the composite signature covers
3843        // only the ciphertext. It MUST be bound into the COSE_Encrypt0 AEAD so a
3844        // network attacker cannot mutate the outer nonce/iat to evade the
3845        // server's replay admission while the signature still verifies.
3846        use crate::node_identity::{derive_mesh_kem_recipient, derive_mesh_mldsa_key};
3847
3848        let (node_sk, node_vk) = generate_signing_keypair();
3849        let pq_sk = derive_mesh_mldsa_key(&node_sk);
3850        let kem_kp = derive_mesh_kem_recipient(&node_sk).expect("derive #mesh-kem");
3851        let kem_pub = kem_kp.public();
3852
3853        // Bind the original replay nonce so the tamper below can derive a
3854        // provably-distinct value without a second hard-coded literal.
3855        let original_nonce = generate_nonce();
3856        let envelope = RequestEnvelope {
3857            request_id: 42,
3858            payload: vec![1, 2, 3],
3859            nonce: original_nonce,
3860            iat: current_timestamp(),
3861            authorization: Authorization::None,
3862            delegation_token: None,
3863            wth: None,
3864            client_dh_public: None,
3865            client_kem_public: None,
3866            response_kem_recipient: None,
3867            service_domain: None,
3868            proof_cwt: None,
3869            authorization_witness: None,
3870        };
3871        let signed =
3872            SignedEnvelope::new_signed_encrypted_mesh_kem(envelope, &node_sk, &pq_sk, &kem_pub)
3873                .expect("seal");
3874
3875        // Attacker mutates ONLY the outer replay metadata (fields carried in the
3876        // clear beside the ciphertext) — the ciphertext and its composite
3877        // signature are untouched, so the signature still verifies…
3878        let mut tampered = signed.clone();
3879        tampered.envelope.iat = tampered.envelope.iat.wrapping_add(1);
3880        tampered
3881            .verify_signature_only(&node_vk)
3882            .expect("signature over ciphertext is unaffected by outer-field tampering");
3883
3884        // …but decryption MUST fail: the AAD the server recomputes from the
3885        // mutated outer fields no longer matches what was sealed.
3886        assert!(
3887            tampered.decrypt_in_place_mesh_kem(&kem_kp).is_err(),
3888            "mutated outer replay metadata must break #mesh-kem decryption (replay bind)"
3889        );
3890
3891        // Sanity: the untouched envelope still opens.
3892        let mut good = signed.clone();
3893        good.decrypt_in_place_mesh_kem(&kem_kp)
3894            .expect("untampered envelope opens");
3895        assert_eq!(good.envelope.request_id, 42);
3896    }
3897
3898    #[test]
3899    fn compatibility_replay_commits_only_after_full_authentication_and_atomically() {
3900        use crate::node_identity::{derive_mesh_kem_recipient, derive_mesh_mldsa_key};
3901
3902        let (node_sk, node_vk) = generate_signing_keypair();
3903        let pq_sk = derive_mesh_mldsa_key(&node_sk);
3904        let kem_pub = derive_mesh_kem_recipient(&node_sk)
3905            .expect("derive #mesh-kem")
3906            .public();
3907        let original_nonce = generate_nonce();
3908        let original = SignedEnvelope::new_signed_encrypted_mesh_kem(
3909            RequestEnvelope {
3910                request_id: 553,
3911                payload: b"authenticated payload".to_vec(),
3912                nonce: original_nonce,
3913                iat: current_timestamp(),
3914                authorization: Authorization::None,
3915                delegation_token: None,
3916                wth: None,
3917                client_dh_public: None,
3918                client_kem_public: None,
3919                response_kem_recipient: None,
3920                service_domain: None,
3921                proof_cwt: None,
3922                authorization_witness: None,
3923            },
3924            &node_sk,
3925            &pq_sk,
3926            &kem_pub,
3927        )
3928        .expect("seal original");
3929        let original_wire = signed_envelope_to_wire(&original);
3930
3931        // Fill a capacity-one cache with one fully authenticated request.
3932        let cache = InMemoryNonceCache::with_config(MAX_TIMESTAMP_AGE_MS, 1);
3933        let options = || {
3934            UnwrapOptions::fixed_signer(&node_vk, &cache)
3935                .with_decryption_key(&node_sk)
3936                .require_encrypted(true)
3937                .with_verify_policy(crate::crypto::CryptoPolicy::Classical)
3938        };
3939        unwrap_and_verify(&original_wire, &options()).expect("original request is accepted");
3940
3941        // Wire-controlled integer extremes fail in the early non-mutating
3942        // timestamp precheck and cannot evict the accepted entry from this
3943        // capacity-one cache. The ciphertext signature is intentionally left
3944        // valid; changing only outer metadata would otherwise proceed to AEAD.
3945        for extreme_iat in [i64::MIN, i64::MAX] {
3946            let mut extreme = original.clone();
3947            extreme.envelope.iat = extreme_iat;
3948            extreme
3949                .verify_signature_only(&node_vk)
3950                .expect("ciphertext signature remains valid");
3951            let error = unwrap_and_verify(&signed_envelope_to_wire(&extreme), &options())
3952                .expect_err("extreme timestamp is rejected without a panic");
3953            assert!(error.to_string().contains(if extreme_iat == i64::MIN {
3954                "timestamp too old"
3955            } else {
3956                "timestamp in future"
3957            }));
3958            assert!(
3959                unwrap_and_verify(&original_wire, &options()).is_err(),
3960                "rejected extreme timestamp must not evict accepted replay state"
3961            );
3962        }
3963
3964        // Authenticated but expired outer metadata is rejected before KEM work
3965        // and cannot disturb the full capacity-one cache.
3966        let mut stale = original.clone();
3967        stale.envelope.iat = current_timestamp() - MAX_TIMESTAMP_AGE_MS - 1;
3968        stale
3969            .verify_signature_only(&node_vk)
3970            .expect("ciphertext signature remains valid");
3971        let stale_error = unwrap_and_verify(&signed_envelope_to_wire(&stale), &options())
3972            .expect_err("expired request is rejected");
3973        assert!(stale_error.to_string().contains("timestamp too old"));
3974        assert!(unwrap_and_verify(&original_wire, &options()).is_err());
3975
3976        // A distinct outer nonce plus an invalid signature must not consume or
3977        // evict cache capacity.
3978        let mut invalid_signature = original.clone();
3979        let last = invalid_signature.cose.len() - 1;
3980        invalid_signature.cose[last] ^= 1;
3981        assert!(
3982            unwrap_and_verify(&signed_envelope_to_wire(&invalid_signature), &options()).is_err()
3983        );
3984        assert!(unwrap_and_verify(&original_wire, &options()).is_err());
3985
3986        // The signature covers the unchanged ciphertext and remains valid, but
3987        // the distinct outer nonce changes authenticated external AAD. Failed
3988        // AEAD authentication likewise must not touch replay state.
3989        let invalid_aad = original.clone();
3990        invalid_aad
3991            .verify_signature_only(&node_vk)
3992            .expect("ciphertext signature remains valid");
3993        assert!(unwrap_and_verify(&signed_envelope_to_wire(&invalid_aad), &options()).is_err());
3994
3995        // Both invalid attempts independently left the original accepted nonce
3996        // resident in the capacity-one cache.
3997        assert!(unwrap_and_verify(&original_wire, &options()).is_err());
3998
3999        // Two concurrent, identical, fully valid inputs perform all validation
4000        // before racing at one atomic check-and-insert; exactly one can commit.
4001        let concurrent_cache = InMemoryNonceCache::with_config(MAX_TIMESTAMP_AGE_MS, 1);
4002        let accepted = std::thread::scope(|scope| {
4003            let attempts: Vec<_> = (0..2)
4004                .map(|_| {
4005                    scope.spawn(|| {
4006                        let opts = UnwrapOptions::fixed_signer(&node_vk, &concurrent_cache)
4007                            .with_decryption_key(&node_sk)
4008                            .require_encrypted(true)
4009                            .with_verify_policy(crate::crypto::CryptoPolicy::Classical);
4010                        unwrap_and_verify(&original_wire, &opts).is_ok()
4011                    })
4012                })
4013                .collect();
4014            attempts
4015                .into_iter()
4016                .map(|attempt| attempt.join().expect("verification thread"))
4017                .filter(|accepted| *accepted)
4018                .count()
4019        });
4020        assert_eq!(accepted, 1);
4021    }
4022
4023    #[test]
4024    fn timestamp_window_boundaries_and_extremes_are_overflow_safe() {
4025        let now = 0;
4026
4027        // Both documented limits are inclusive.
4028        assert!(SignedEnvelope::validate_timestamp_at(-MAX_TIMESTAMP_AGE_MS, now).is_ok());
4029        assert!(SignedEnvelope::validate_timestamp_at(MAX_CLOCK_SKEW_MS, now).is_ok());
4030
4031        // Values one millisecond inside either inclusive limit also remain valid.
4032        assert!(SignedEnvelope::validate_timestamp_at(-MAX_TIMESTAMP_AGE_MS + 1, now).is_ok());
4033        assert!(SignedEnvelope::validate_timestamp_at(MAX_CLOCK_SKEW_MS - 1, now).is_ok());
4034
4035        // The immediately adjacent values outside either window fail closed.
4036        assert!(SignedEnvelope::validate_timestamp_at(-MAX_TIMESTAMP_AGE_MS - 1, now).is_err());
4037        assert!(SignedEnvelope::validate_timestamp_at(MAX_CLOCK_SKEW_MS + 1, now).is_err());
4038
4039        // Widening before subtraction defines both ends of the wire domain,
4040        // even when the clock is itself at the opposite i64 boundary.
4041        assert!(SignedEnvelope::validate_timestamp_at(i64::MIN, now).is_err());
4042        assert!(SignedEnvelope::validate_timestamp_at(i64::MAX, now).is_err());
4043        assert!(SignedEnvelope::validate_timestamp_at(i64::MIN, i64::MAX).is_err());
4044        assert!(SignedEnvelope::validate_timestamp_at(i64::MAX, i64::MIN).is_err());
4045    }
4046
4047    #[test]
4048    fn ordinary_unwrap_rejects_extreme_timestamps_for_all_compatibility_paths() {
4049        use crate::node_identity::{derive_mesh_kem_recipient, derive_mesh_mldsa_key};
4050
4051        let (node_sk, node_vk) = generate_signing_keypair();
4052        let pq_sk = derive_mesh_mldsa_key(&node_sk);
4053        let kem_pub = derive_mesh_kem_recipient(&node_sk)
4054            .expect("derive #mesh-kem")
4055            .public();
4056
4057        let clear = SignedEnvelope::new_signed(
4058            RequestEnvelope::anonymous(b"clear timestamp boundary".to_vec()),
4059            &node_sk,
4060        );
4061        let encrypted = SignedEnvelope::new_signed_encrypted_mesh_kem(
4062            RequestEnvelope::anonymous(b"encrypted timestamp boundary".to_vec()),
4063            &node_sk,
4064            &pq_sk,
4065            &kem_pub,
4066        )
4067        .expect("seal encrypted boundary fixture");
4068
4069        for extreme_iat in [i64::MIN, i64::MAX] {
4070            for fixture in [&clear, &encrypted] {
4071                let mut extreme = fixture.clone();
4072                extreme.envelope.iat = extreme_iat;
4073                let wire = signed_envelope_to_wire(&extreme);
4074
4075                for any_signer in [false, true] {
4076                    let cache = TestNonceCache::new();
4077                    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4078                        let opts = if any_signer {
4079                            UnwrapOptions::any_signer(&cache)
4080                        } else {
4081                            UnwrapOptions::fixed_signer(&node_vk, &cache)
4082                        }
4083                        .with_verify_policy(crate::crypto::CryptoPolicy::Classical);
4084                        unwrap_and_verify(&wire, &opts)
4085                    }));
4086                    let error = result
4087                        .expect("wire-controlled timestamp must never panic")
4088                        .expect_err("extreme timestamp must fail closed");
4089                    assert!(
4090                        error.to_string().contains(if extreme_iat == i64::MIN {
4091                            "timestamp too old"
4092                        } else {
4093                            "timestamp in future"
4094                        }),
4095                        "timestamp rejection must precede signature or KEM work: {error}"
4096                    );
4097                    assert!(
4098                        cache.seen.lock().is_empty(),
4099                        "rejected timestamp must not commit replay state"
4100                    );
4101                }
4102            }
4103        }
4104    }
4105
4106    #[test]
4107    fn test_tampered_authorization_breaks_signature() {
4108        let (signing_key, verifying_key) = generate_signing_keypair();
4109
4110        let envelope = RequestEnvelope {
4111            request_id: 100,
4112            payload: vec![1, 2, 3],
4113            nonce: generate_nonce(),
4114            iat: current_timestamp(),
4115            authorization: Authorization::None,
4116            delegation_token: None,
4117            wth: None,
4118            client_dh_public: None,
4119            client_kem_public: None,
4120            response_kem_recipient: None,
4121            service_domain: None,
4122            proof_cwt: None,
4123            authorization_witness: None,
4124        };
4125
4126        let mut signed = test_new_signed(envelope, &signing_key);
4127
4128        // Tamper with the authorization after signing
4129        signed.envelope.authorization = Authorization::IdJag("evil-token".to_owned());
4130
4131        // Signature verification must fail
4132        let result = signed.verify_signature_only(&verifying_key);
4133        assert!(
4134            result.is_err(),
4135            "Tampered authorization must invalidate signature"
4136        );
4137    }
4138
4139    #[test]
4140    fn test_tampered_payload_breaks_signature() {
4141        let (signing_key, verifying_key) = generate_signing_keypair();
4142
4143        let envelope = RequestEnvelope::anonymous(vec![1, 2, 3]);
4144        let mut signed = test_new_signed(envelope, &signing_key);
4145
4146        signed.envelope.payload = vec![9, 9, 9];
4147
4148        let result = signed.verify_signature_only(&verifying_key);
4149        assert!(
4150            result.is_err(),
4151            "Tampered payload must invalidate signature"
4152        );
4153    }
4154
4155    #[test]
4156    fn test_tampered_wth_breaks_signature() {
4157        let (signing_key, verifying_key) = generate_signing_keypair();
4158
4159        let envelope = RequestEnvelope {
4160            request_id: 100,
4161            payload: vec![1, 2, 3],
4162            nonce: generate_nonce(),
4163            iat: current_timestamp(),
4164            authorization: Authorization::None,
4165            delegation_token: None,
4166            wth: Some([0xAA; 32]),
4167            client_dh_public: None,
4168            client_kem_public: None,
4169            response_kem_recipient: None,
4170            service_domain: None,
4171            proof_cwt: None,
4172            authorization_witness: None,
4173        };
4174
4175        let mut signed = test_new_signed(envelope, &signing_key);
4176        signed.envelope.wth = Some([0xBB; 32]);
4177
4178        let result = signed.verify_signature_only(&verifying_key);
4179        assert!(result.is_err(), "Tampered wth must invalidate signature");
4180    }
4181
4182    // =========================================================================
4183    // M3 (#152): COSE composite envelope — both schemes + cross-compat + anchor
4184    // =========================================================================
4185
4186    use crate::crypto::CryptoPolicy;
4187
4188    fn pq_store_for(
4189        ed_pubkey: [u8; 32],
4190        pq_vk: &crate::crypto::pq::MlDsaVerifyingKey,
4191    ) -> TestPqStore {
4192        let vk =
4193            crate::crypto::pq::ml_dsa_vk_from_bytes(&crate::crypto::pq::ml_dsa_vk_bytes(pq_vk))
4194                .expect("decode pq vk");
4195        TestPqStore {
4196            bindings: vec![(ed_pubkey, vk)],
4197        }
4198    }
4199
4200    /// classical_only: sign + verify in Classical mode.
4201    #[test]
4202    fn m3_classical_only() -> crate::EnvelopeResult<()> {
4203        let (sk, vk) = generate_signing_keypair();
4204        let cache = TestNonceCache::new();
4205        let signed = SignedEnvelope::new_signed_with_policy(
4206            RequestEnvelope::anonymous(vec![1, 2, 3]),
4207            &sk,
4208            None,
4209            CryptoPolicy::Classical,
4210        )
4211        .expect("classical signing");
4212        signed.verify_with(&vk, &cache, None, CryptoPolicy::Classical)?;
4213        Ok(())
4214    }
4215
4216    /// Hybrid construction without a PQ key is a fail-closed `Err` — not a
4217    /// panic, and never a silent classical downgrade.
4218    #[test]
4219    fn m3_hybrid_without_pq_key_errors() {
4220        let (sk, _vk) = generate_signing_keypair();
4221        assert!(SignedEnvelope::new_signed_with_policy(
4222            RequestEnvelope::anonymous(vec![1]),
4223            &sk,
4224            None,
4225            CryptoPolicy::Hybrid,
4226        )
4227        .is_err());
4228        assert!(ResponseEnvelope::new_signed_with_policy(
4229            1,
4230            vec![1],
4231            &sk,
4232            None,
4233            CryptoPolicy::Hybrid,
4234        )
4235        .is_err());
4236    }
4237
4238    /// hybrid: sign + verify composite (both EdDSA + ML-DSA-65 checked).
4239    #[test]
4240    fn m3_hybrid_both_checked() -> crate::EnvelopeResult<()> {
4241        let (sk, vk) = generate_signing_keypair();
4242        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4243        let cache = TestNonceCache::new();
4244        let signed = SignedEnvelope::new_signed_hybrid(
4245            RequestEnvelope::anonymous(vec![4, 5, 6]),
4246            &sk,
4247            &pq_sk,
4248        );
4249        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4250        signed.verify_with(&vk, &cache, Some(&store), CryptoPolicy::Hybrid)?;
4251        Ok(())
4252    }
4253
4254    /// cross_pq_signer_classical_verifier: a Hybrid-signed envelope verifies
4255    /// under a Classical verifier via the EdDSA component + skip-unknown.
4256    #[test]
4257    fn m3_cross_hybrid_signer_classical_verifier() -> crate::EnvelopeResult<()> {
4258        let (sk, vk) = generate_signing_keypair();
4259        let (pq_sk, _pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4260        let cache = TestNonceCache::new();
4261        let signed = SignedEnvelope::new_signed_hybrid(
4262            RequestEnvelope::anonymous(vec![7, 8, 9]),
4263            &sk,
4264            &pq_sk,
4265        );
4266        // Classical verifier: no PQ store, Classical policy → skips ML-DSA entry.
4267        signed.verify_with(&vk, &cache, None, CryptoPolicy::Classical)?;
4268        Ok(())
4269    }
4270
4271    /// cross_classical_signer_hybrid_verifier: a Classical-signed item from an
4272    /// ANCHORED signer under a Hybrid verifier — WNS enforces the outer layer for
4273    /// anchored identities, so a classical-only (no outer) envelope is rejected.
4274    #[test]
4275    fn m3_cross_classical_signer_hybrid_verifier_rejected() {
4276        let (sk, vk) = generate_signing_keypair();
4277        let (_pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4278        let cache = TestNonceCache::new();
4279        let signed = SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![1]), &sk);
4280        // Signer's PQ key IS anchored → Hybrid must require its outer ML-DSA layer.
4281        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4282        let res = signed.verify_with(&vk, &cache, Some(&store), CryptoPolicy::Hybrid);
4283        assert!(
4284            res.is_err(),
4285            "Hybrid policy must reject a classical-only envelope from an anchored signer"
4286        );
4287    }
4288
4289    /// Classical signer accepted by a verifier whose policy permits classical.
4290    #[test]
4291    fn m3_classical_signer_classical_policy_accepted() -> crate::EnvelopeResult<()> {
4292        let (sk, vk) = generate_signing_keypair();
4293        let cache = TestNonceCache::new();
4294        let signed = SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![1]), &sk);
4295        signed.verify_with(&vk, &cache, None, CryptoPolicy::Classical)?;
4296        Ok(())
4297    }
4298
4299    /// self_cert_fix: an envelope whose ML-DSA key doesn't match the
4300    /// kid-resolved key is REJECTED (proves the kid-anchoring).
4301    #[test]
4302    fn m3_self_cert_fix_wrong_anchored_pq_key_rejected() {
4303        let (sk, vk) = generate_signing_keypair();
4304        let (pq_sk, _pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4305        // Attacker/foreign anchored key that does NOT match the signer's PQ key.
4306        let (_other_sk, other_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4307        let cache = TestNonceCache::new();
4308        let signed = SignedEnvelope::new_signed_hybrid(
4309            RequestEnvelope::anonymous(vec![1, 2, 3]),
4310            &sk,
4311            &pq_sk,
4312        );
4313        let store = pq_store_for(vk.to_bytes(), &other_vk);
4314        let res = signed.verify_with(&vk, &cache, Some(&store), CryptoPolicy::Hybrid);
4315        assert!(
4316            res.is_err(),
4317            "PQ key not matching the kid-anchored key must be rejected (self-cert fix)"
4318        );
4319    }
4320
4321    /// Hybrid policy with no anchored key fails closed.
4322    #[test]
4323    fn m3_hybrid_policy_without_anchor_rejected() {
4324        let (sk, vk) = generate_signing_keypair();
4325        let (pq_sk, _pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4326        let cache = TestNonceCache::new();
4327        let signed =
4328            SignedEnvelope::new_signed_hybrid(RequestEnvelope::anonymous(vec![1]), &sk, &pq_sk);
4329        assert!(signed
4330            .verify_with(&vk, &cache, None, CryptoPolicy::Hybrid)
4331            .is_err());
4332    }
4333
4334    // -- SNS-specific: strip the outer ML-DSA layer at the cose level and prove
4335    //    Hybrid policy rejects it (the attack the review found accepted before).
4336    #[test]
4337    fn m3_sns_strip_outer_mldsa_rejected() {
4338        let (sk, vk) = generate_signing_keypair();
4339        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4340        let cache = TestNonceCache::new();
4341        let mut signed = SignedEnvelope::new_signed_hybrid(
4342            RequestEnvelope::anonymous(vec![1, 2, 3]),
4343            &sk,
4344            &pq_sk,
4345        );
4346        // Strip: re-encode the composite with the outer set to null.
4347        let (inner, outer) =
4348            crate::crypto::cose_sign::decode_composite_for_test(&signed.cose).expect("decode");
4349        assert!(outer.is_some(), "hybrid envelope must have an outer layer");
4350        signed.cose =
4351            crate::crypto::cose_sign::encode_composite_for_test(inner, None).expect("encode");
4352
4353        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4354        let res = signed.verify_with(&vk, &cache, Some(&store), CryptoPolicy::Hybrid);
4355        assert!(
4356            res.is_err(),
4357            "stripping the outer ML-DSA layer must fail Hybrid policy"
4358        );
4359    }
4360
4361    /// Integration at the `unwrap_and_verify` level (prod-wiring path the review
4362    /// flagged as missing): sign Hybrid, strip the outer, serialize to wire, and
4363    /// assert `unwrap_and_verify` REJECTS under a Hybrid deployment.
4364    #[test]
4365    fn m3_unwrap_and_verify_strip_rejected_under_hybrid() {
4366        let (sk, vk) = generate_signing_keypair();
4367        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4368        let cache = TestNonceCache::new();
4369
4370        // Sign Hybrid, then strip the outer layer.
4371        let mut signed = SignedEnvelope::new_signed_hybrid(
4372            RequestEnvelope::anonymous(vec![9, 9, 9]),
4373            &sk,
4374            &pq_sk,
4375        );
4376        let (inner, _outer) =
4377            crate::crypto::cose_sign::decode_composite_for_test(&signed.cose).expect("decode");
4378        signed.cose =
4379            crate::crypto::cose_sign::encode_composite_for_test(inner, None).expect("encode");
4380
4381        // Serialize to wire bytes.
4382        let mut message = capnp::message::Builder::new_default();
4383        {
4384            let mut builder = message.init_root::<common_capnp::signed_envelope::Builder>();
4385            signed.write_to(&mut builder);
4386        }
4387        let mut wire = Vec::new();
4388        capnp::serialize::write_message(&mut wire, &message).expect("serialize");
4389
4390        // Verify under a Hybrid deployment via unwrap_and_verify.
4391        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4392        let opts = UnwrapOptions::fixed_signer(&vk, &cache)
4393            .with_verify_policy(CryptoPolicy::Hybrid)
4394            .with_pq_store(&store);
4395        let res = unwrap_and_verify(&wire, &opts);
4396        assert!(
4397            res.is_err(),
4398            "unwrap_and_verify must reject a stripped Hybrid envelope (prod fail-open closed)"
4399        );
4400    }
4401
4402    /// Integration: a well-formed Hybrid envelope passes unwrap_and_verify under
4403    /// a Hybrid deployment with the correct anchor.
4404    #[test]
4405    fn m3_unwrap_and_verify_hybrid_round_trip() -> crate::EnvelopeResult<()> {
4406        let (sk, vk) = generate_signing_keypair();
4407        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4408        let cache = TestNonceCache::new();
4409
4410        let signed =
4411            SignedEnvelope::new_signed_hybrid(RequestEnvelope::anonymous(vec![4, 2]), &sk, &pq_sk);
4412        let mut message = capnp::message::Builder::new_default();
4413        {
4414            let mut builder = message.init_root::<common_capnp::signed_envelope::Builder>();
4415            signed.write_to(&mut builder);
4416        }
4417        let mut wire = Vec::new();
4418        capnp::serialize::write_message(&mut wire, &message).expect("serialize");
4419
4420        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4421        let opts = UnwrapOptions::fixed_signer(&vk, &cache)
4422            .with_verify_policy(CryptoPolicy::Hybrid)
4423            .with_pq_store(&store);
4424        let (_signed, payload) = unwrap_and_verify(&wire, &opts)
4425            .map_err(|e| EnvelopeError::PqSignatureInvalid(e.to_string()))?;
4426        assert_eq!(payload, vec![4, 2]);
4427        Ok(())
4428    }
4429
4430    // ── Fu2/#677: unanchored identity under Hybrid ──────────────────────────
4431
4432    /// Helper: a Hybrid-signed envelope on the wire (no PQ anchor installed).
4433    fn fu2_hybrid_wire_unanchored() -> ((SigningKey, VerifyingKey), Vec<u8>) {
4434        let (sk, vk) = generate_signing_keypair();
4435        let (pq_sk, _pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4436        let signed = SignedEnvelope::new_signed_hybrid(
4437            RequestEnvelope::anonymous(vec![5, 0, 2]),
4438            &sk,
4439            &pq_sk,
4440        );
4441        let mut message = capnp::message::Builder::new_default();
4442        {
4443            let mut builder = message.init_root::<common_capnp::signed_envelope::Builder>();
4444            signed.write_to(&mut builder);
4445        }
4446        let mut wire = Vec::new();
4447        capnp::serialize::write_message(&mut wire, &message).expect("serialize");
4448        ((sk, vk), wire)
4449    }
4450
4451    /// Fu2/#677 default: an unanchored identity (no ML-DSA-65 binding) is
4452    /// DENIED under Hybrid via the production wire-verify path, even though the
4453    /// inner EdDSA is valid. The previous behavior accepted it (WNS classical
4454    /// floor); the default is now deny-on-missing-anchor.
4455    #[test]
4456    fn fu2_unanchored_denied_by_default_under_hybrid() {
4457        let ((_sk, vk), wire) = fu2_hybrid_wire_unanchored();
4458        let cache = TestNonceCache::new();
4459        // Hybrid + NO pq_store (unanchored) + default Deny posture.
4460        let opts =
4461            UnwrapOptions::fixed_signer(&vk, &cache).with_verify_policy(CryptoPolicy::Hybrid);
4462        let res = unwrap_and_verify(&wire, &opts);
4463        assert!(
4464            res.is_err(),
4465            "an unanchored identity MUST be denied under Hybrid by default (Fu2/#677)"
4466        );
4467    }
4468
4469    // =========================================================================
4470    // #275: ResponseEnvelope COSE composite (Hybrid parity with SignedEnvelope)
4471    // =========================================================================
4472
4473    /// Serialize a ResponseEnvelope to wire bytes (mirrors the prod path).
4474    fn response_to_wire(env: &ResponseEnvelope) -> Vec<u8> {
4475        let mut message = capnp::message::Builder::new_default();
4476        {
4477            let mut builder = message.init_root::<common_capnp::response_envelope::Builder>();
4478            env.write_to(&mut builder);
4479        }
4480        let mut wire = Vec::new();
4481        capnp::serialize::write_message(&mut wire, &message).expect("serialize response");
4482        wire
4483    }
4484
4485    #[test]
4486    fn exact_flat_parser_rejects_trailing_and_partial_frames() {
4487        let (sk, _) = generate_signing_keypair();
4488        let wire = response_to_wire(&ResponseEnvelope::new_signed(1, vec![1, 2, 3], &sk));
4489
4490        let mut trailing = wire.clone();
4491        trailing.extend_from_slice(&[0u8; 8]);
4492        assert!(
4493            read_exact_envelope_message(&trailing).is_err(),
4494            "a second/trailing frame must not be ignored"
4495        );
4496
4497        let partial = &wire[..wire.len() - 1];
4498        assert!(
4499            read_exact_envelope_message(partial).is_err(),
4500            "a truncated declared segment must be rejected"
4501        );
4502    }
4503
4504    #[test]
4505    fn exact_flat_parser_rejects_oversized_and_malformed_segment_tables() {
4506        // One segment declaring 131,073 words: one word over the canonical
4507        // 1 MiB traversal cap. No body is supplied; rejection must occur from
4508        // the bounded table parse without allocating the declared body.
4509        let oversized = [0, 0, 0, 0, 1, 0, 2, 0];
4510        assert!(read_exact_envelope_message(&oversized).is_err());
4511
4512        // u32::MAX + 1 wraps to an invalid zero segment count.
4513        let malformed_count = [0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0];
4514        assert!(read_exact_envelope_message(&malformed_count).is_err());
4515    }
4516
4517    /// Classical round-trip: sign + verify a response (EdDSA-only COSE).
4518    #[test]
4519    fn resp_classical_round_trip() -> anyhow::Result<()> {
4520        let (sk, vk) = generate_signing_keypair();
4521        let resp = ResponseEnvelope::new_signed(7, vec![1, 2, 3], &sk);
4522        // Direct verify.
4523        resp.verify(Some(&vk))?;
4524        // Via the wire + unwrap_response (Classical).
4525        let wire = response_to_wire(&resp);
4526        let (rid, payload) = unwrap_response(&wire, Some(&vk))?;
4527        assert_eq!(rid, 7);
4528        assert_eq!(payload, vec![1, 2, 3]);
4529        Ok(())
4530    }
4531
4532    /// Hybrid round-trip: sign + verify a response (EdDSA + ML-DSA-65 anchored).
4533    #[test]
4534    fn resp_hybrid_round_trip() -> anyhow::Result<()> {
4535        let (sk, vk) = generate_signing_keypair();
4536        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4537        let resp = ResponseEnvelope::new_signed_hybrid(9, vec![4, 5, 6], &sk, &pq_sk);
4538        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4539
4540        resp.verify_with(Some(&vk), Some(&store), CryptoPolicy::Hybrid)?;
4541
4542        let wire = response_to_wire(&resp);
4543        let (rid, payload) =
4544            unwrap_response_with(&wire, Some(&vk), Some(&store), CryptoPolicy::Hybrid)?;
4545        assert_eq!(rid, 9);
4546        assert_eq!(payload, vec![4, 5, 6]);
4547        Ok(())
4548    }
4549
4550    // =========================================================================
4551    // #277: process-global RESPONSE verify config — fail-closed Hybrid default,
4552    // and anchored-key enforcement.
4553    // =========================================================================
4554
4555    /// The production selector has exactly one pinned suite and reads no wire
4556    /// or environment input.
4557    #[test]
4558    fn mandatory_policy_is_pinned_hybrid() {
4559        assert_eq!(mandatory_envelope_policy(), CryptoPolicy::Hybrid);
4560    }
4561
4562    /// Process-global RESPONSE verify config drives per-identity enforcement
4563    /// (#277, WNS posture): once a Hybrid config + admin-anchored
4564    /// `KeyedPqTrustStore` is installed, a Hybrid response whose server ML-DSA key
4565    /// IS anchored verifies with the outer enforced; an unanchored signer and an
4566    /// anchored signer that sends a classical-only response are both rejected.
4567    /// This is the install/consult path native
4568    /// RPC clients fall back to when no per-client store was set. Single OnceLock
4569    /// install per test binary, so this is the one test that installs the config.
4570    #[test]
4571    fn resp_global_config_requires_anchor_and_hybrid_outer() -> anyhow::Result<()> {
4572        // Anchored signer.
4573        let (sk, vk) = generate_signing_keypair();
4574        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4575        // A different signer whose ML-DSA key is NOT bound in the store.
4576        let (sk2, vk2) = generate_signing_keypair();
4577        let (pq_sk2, _pq_vk2) = crate::crypto::pq::ml_dsa_generate_keypair();
4578
4579        // Admin-anchored store (#157 reuse): only the first signer's key is bound.
4580        let mut keyed = KeyedPqTrustStore::new();
4581        keyed.bind(vk.to_bytes(), &pq_vk);
4582        install_response_verify_config(ResponseVerifyConfig {
4583            policy: CryptoPolicy::Hybrid,
4584            pq_store: Some(std::sync::Arc::new(keyed)),
4585        })
4586        .expect("install response verify config once");
4587
4588        assert_eq!(global_response_verify_policy(), CryptoPolicy::Hybrid);
4589        let store = global_response_pq_store().expect("global response store installed");
4590
4591        // Anchored Hybrid response verifies under the global config.
4592        let resp = ResponseEnvelope::new_signed_hybrid(11, vec![7, 7], &sk, &pq_sk);
4593        let wire = response_to_wire(&resp);
4594        let (rid, payload) = unwrap_response_with(
4595            &wire,
4596            Some(&vk),
4597            Some(store.as_ref()),
4598            global_response_verify_policy(),
4599        )?;
4600        assert_eq!(rid, 11);
4601        assert_eq!(payload, vec![7, 7]);
4602
4603        // Unanchored signer is rejected even when it carries a valid hybrid
4604        // composite; the verifying key must be policy-anchored.
4605        let resp2 = ResponseEnvelope::new_signed_hybrid(12, vec![8, 8], &sk2, &pq_sk2);
4606        let wire2 = response_to_wire(&resp2);
4607        let unanchored = unwrap_response_with(
4608            &wire2,
4609            Some(&vk2),
4610            Some(store.as_ref()),
4611            global_response_verify_policy(),
4612        );
4613        assert!(unanchored.is_err());
4614
4615        // A Classical-only (inner-EdDSA-only) response from the ANCHORED signer is
4616        // rejected: an anchored identity must use its PQ key (the outer is enforced
4617        // per-identity), so a stripped/absent outer on an anchored signer downgrades.
4618        let resp_classical = ResponseEnvelope::new_signed(13, vec![9], &sk);
4619        let wire3 = response_to_wire(&resp_classical);
4620        let res3 = unwrap_response_with(
4621            &wire3,
4622            Some(&vk),
4623            Some(store.as_ref()),
4624            global_response_verify_policy(),
4625        );
4626        assert!(
4627            res3.is_err(),
4628            "classical-only response from an anchored signer must be rejected"
4629        );
4630        Ok(())
4631    }
4632
4633    /// A Hybrid-signed response verifies under a Classical verifier via its
4634    /// inner EdDSA (skip-unknown interop) — the default-policy interop path.
4635    #[test]
4636    fn resp_hybrid_signed_classical_verifier_accepted() -> anyhow::Result<()> {
4637        let (sk, vk) = generate_signing_keypair();
4638        let (pq_sk, _pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4639        let resp = ResponseEnvelope::new_signed_hybrid(1, vec![1], &sk, &pq_sk);
4640        resp.verify(Some(&vk))?; // Classical, no store
4641        Ok(())
4642    }
4643
4644    /// Stripping the outer ML-DSA layer under Hybrid policy is rejected.
4645    #[test]
4646    fn resp_strip_outer_mldsa_rejected_under_hybrid() {
4647        let (sk, vk) = generate_signing_keypair();
4648        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4649        let mut resp = ResponseEnvelope::new_signed_hybrid(2, vec![2, 2], &sk, &pq_sk);
4650        let (inner, outer) =
4651            crate::crypto::cose_sign::decode_composite_for_test(&resp.cose).expect("decode");
4652        assert!(outer.is_some(), "hybrid response must have an outer layer");
4653        resp.cose =
4654            crate::crypto::cose_sign::encode_composite_for_test(inner, None).expect("encode");
4655
4656        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4657        let res = resp.verify_with(Some(&vk), Some(&store), CryptoPolicy::Hybrid);
4658        assert!(
4659            res.is_err(),
4660            "stripping the outer ML-DSA layer must fail Hybrid policy"
4661        );
4662    }
4663
4664    /// Tampering the inner EdDSA signature invalidates the Hybrid composite.
4665    #[test]
4666    fn resp_tamper_inner_rejected() {
4667        let (sk, vk) = generate_signing_keypair();
4668        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4669        let resp = ResponseEnvelope::new_signed_hybrid(3, vec![3, 3, 3], &sk, &pq_sk);
4670        let (_inner, outer) =
4671            crate::crypto::cose_sign::decode_composite_for_test(&resp.cose).expect("decode");
4672        // Forge a new inner with a different key; keep the original outer.
4673        let (other_sk, _other_vk) = generate_signing_keypair();
4674        let other_resp = ResponseEnvelope::new_signed(3, vec![3, 3, 3], &other_sk);
4675        let (forged_inner, _none) =
4676            crate::crypto::cose_sign::decode_composite_for_test(&other_resp.cose).expect("decode");
4677        let mut tampered = resp.clone();
4678        tampered.cose = crate::crypto::cose_sign::encode_composite_for_test(forged_inner, outer)
4679            .expect("encode");
4680
4681        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4682        let res = tampered.verify_with(Some(&vk), Some(&store), CryptoPolicy::Hybrid);
4683        assert!(
4684            res.is_err(),
4685            "tampering the inner EdDSA must invalidate the response composite"
4686        );
4687    }
4688
4689    /// Tampering the payload invalidates the signature.
4690    #[test]
4691    fn resp_tamper_payload_rejected() {
4692        let (sk, vk) = generate_signing_keypair();
4693        let mut resp = ResponseEnvelope::new_signed(4, vec![1, 2, 3], &sk);
4694        resp.payload = vec![9, 9, 9];
4695        assert!(
4696            resp.verify(Some(&vk)).is_err(),
4697            "tampered payload must invalidate the response"
4698        );
4699    }
4700
4701    /// self-cert: anchored ML-DSA key not matching the signer's PQ key → reject.
4702    #[test]
4703    fn resp_self_cert_wrong_anchor_rejected() {
4704        let (sk, vk) = generate_signing_keypair();
4705        let (pq_sk, _pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4706        let (_other_sk, other_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4707        let resp = ResponseEnvelope::new_signed_hybrid(5, vec![5], &sk, &pq_sk);
4708        let store = pq_store_for(vk.to_bytes(), &other_vk);
4709        let res = resp.verify_with(Some(&vk), Some(&store), CryptoPolicy::Hybrid);
4710        assert!(
4711            res.is_err(),
4712            "wrong anchored PQ key must be rejected (self-cert fix)"
4713        );
4714    }
4715
4716    /// Hybrid policy with no anchored response key fails closed.
4717    #[test]
4718    fn resp_hybrid_without_anchor_is_rejected() {
4719        let (sk, vk) = generate_signing_keypair();
4720        let (pq_sk, _pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4721        let resp = ResponseEnvelope::new_signed_hybrid(6, vec![6], &sk, &pq_sk);
4722        assert!(resp
4723            .verify_with(Some(&vk), None, CryptoPolicy::Hybrid)
4724            .is_err());
4725    }
4726
4727    /// classical-signed response under Hybrid policy → rejected (no downgrade).
4728    #[test]
4729    fn resp_classical_signed_hybrid_verifier_rejected() {
4730        let (sk, vk) = generate_signing_keypair();
4731        let (_pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4732        let resp = ResponseEnvelope::new_signed(8, vec![8], &sk);
4733        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4734        let res = resp.verify_with(Some(&vk), Some(&store), CryptoPolicy::Hybrid);
4735        assert!(
4736            res.is_err(),
4737            "Hybrid policy must reject a classical-only response"
4738        );
4739    }
4740
4741    // =========================================================================
4742    // Mandatory hybrid posture: every identity requires an anchored PQ key.
4743    // Covers BOTH SignedEnvelope and ResponseEnvelope paths.
4744    // =========================================================================
4745
4746    /// WNS / SignedEnvelope (1) anchored downgrade rejected: anchor the signer's
4747    /// correct ML-DSA key, strip the outer layer, verify under Hybrid → REJECTED.
4748    #[test]
4749    fn wns_signed_anchored_downgrade_rejected() {
4750        let (sk, vk) = generate_signing_keypair();
4751        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4752        let cache = TestNonceCache::new();
4753        let mut signed = SignedEnvelope::new_signed_hybrid(
4754            RequestEnvelope::anonymous(vec![1, 2, 3]),
4755            &sk,
4756            &pq_sk,
4757        );
4758        let (inner, outer) =
4759            crate::crypto::cose_sign::decode_composite_for_test(&signed.cose).expect("decode");
4760        assert!(outer.is_some(), "hybrid envelope must carry an outer layer");
4761        signed.cose =
4762            crate::crypto::cose_sign::encode_composite_for_test(inner, None).expect("encode");
4763        // Signer's PQ key IS anchored → the outer is enforced; stripping it fails.
4764        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4765        let res = signed.verify_with(&vk, &cache, Some(&store), CryptoPolicy::Hybrid);
4766        assert!(
4767            res.is_err(),
4768            "anchored identity must not be downgradable by stripping the outer"
4769        );
4770    }
4771
4772    /// An unanchored signer is rejected with an empty or absent trust store.
4773    #[test]
4774    fn mandatory_hybrid_signed_unanchored_rejected() {
4775        let (sk, vk) = generate_signing_keypair();
4776        let (pq_sk, _pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4777        let cache = TestNonceCache::new();
4778        let signed = SignedEnvelope::new_signed_hybrid(
4779            RequestEnvelope::anonymous(vec![4, 5, 6]),
4780            &sk,
4781            &pq_sk,
4782        );
4783        let empty = TestPqStore { bindings: vec![] };
4784        assert!(signed
4785            .verify_with(&vk, &cache, Some(&empty), CryptoPolicy::Hybrid)
4786            .is_err());
4787        let cache2 = TestNonceCache::new();
4788        assert!(signed
4789            .verify_with(&vk, &cache2, None, CryptoPolicy::Hybrid)
4790            .is_err());
4791    }
4792
4793    /// WNS / SignedEnvelope (3) anchored enforced: anchored signer + intact Hybrid
4794    /// succeeds; anchored signer + classical-only (no outer) is rejected.
4795    #[test]
4796    fn wns_signed_anchored_enforced() {
4797        let (sk, vk) = generate_signing_keypair();
4798        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4799        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4800
4801        let cache = TestNonceCache::new();
4802        let intact =
4803            SignedEnvelope::new_signed_hybrid(RequestEnvelope::anonymous(vec![7]), &sk, &pq_sk);
4804        intact
4805            .verify_with(&vk, &cache, Some(&store), CryptoPolicy::Hybrid)
4806            .expect("intact hybrid from an anchored signer must verify");
4807
4808        let cache2 = TestNonceCache::new();
4809        let classical = SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![8]), &sk);
4810        let res = classical.verify_with(&vk, &cache2, Some(&store), CryptoPolicy::Hybrid);
4811        assert!(
4812            res.is_err(),
4813            "anchored signer must use its PQ key — classical-only is rejected"
4814        );
4815    }
4816
4817    /// WNS / ResponseEnvelope (1) anchored downgrade rejected.
4818    #[test]
4819    fn wns_response_anchored_downgrade_rejected() {
4820        let (sk, vk) = generate_signing_keypair();
4821        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4822        let mut resp = ResponseEnvelope::new_signed_hybrid(20, vec![2, 0], &sk, &pq_sk);
4823        let (inner, outer) =
4824            crate::crypto::cose_sign::decode_composite_for_test(&resp.cose).expect("decode");
4825        assert!(outer.is_some(), "hybrid response must carry an outer layer");
4826        resp.cose =
4827            crate::crypto::cose_sign::encode_composite_for_test(inner, None).expect("encode");
4828        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4829        let res = resp.verify_with(Some(&vk), Some(&store), CryptoPolicy::Hybrid);
4830        assert!(
4831            res.is_err(),
4832            "anchored response identity must not be downgradable"
4833        );
4834    }
4835
4836    /// Response verification also rejects unanchored signers.
4837    #[test]
4838    fn mandatory_hybrid_response_unanchored_rejected() {
4839        let (sk, vk) = generate_signing_keypair();
4840        let (pq_sk, _pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4841        let resp = ResponseEnvelope::new_signed_hybrid(21, vec![2, 1], &sk, &pq_sk);
4842        let empty = TestPqStore { bindings: vec![] };
4843        assert!(resp
4844            .verify_with(Some(&vk), Some(&empty), CryptoPolicy::Hybrid)
4845            .is_err());
4846        assert!(resp
4847            .verify_with(Some(&vk), None, CryptoPolicy::Hybrid)
4848            .is_err());
4849    }
4850
4851    /// WNS / ResponseEnvelope (3) anchored enforced.
4852    #[test]
4853    fn wns_response_anchored_enforced() {
4854        let (sk, vk) = generate_signing_keypair();
4855        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4856        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4857
4858        let intact = ResponseEnvelope::new_signed_hybrid(22, vec![2, 2], &sk, &pq_sk);
4859        intact
4860            .verify_with(Some(&vk), Some(&store), CryptoPolicy::Hybrid)
4861            .expect("intact hybrid response from an anchored signer must verify");
4862
4863        let classical = ResponseEnvelope::new_signed(23, vec![2, 3], &sk);
4864        let res = classical.verify_with(Some(&vk), Some(&store), CryptoPolicy::Hybrid);
4865        assert!(
4866            res.is_err(),
4867            "anchored response signer must use its PQ key — classical-only rejected"
4868        );
4869    }
4870
4871    /// Wrong expected signer key → rejected.
4872    #[test]
4873    fn resp_wrong_signer_rejected() {
4874        let (sk, _vk) = generate_signing_keypair();
4875        let (_other_sk, other_vk) = generate_signing_keypair();
4876        let resp = ResponseEnvelope::new_signed(10, vec![1], &sk);
4877        assert!(
4878            resp.verify(Some(&other_vk)).is_err(),
4879            "wrong expected signer must be rejected"
4880        );
4881    }
4882
4883    /// Cap'n Proto round-trip preserves the cose field.
4884    #[test]
4885    fn resp_capnp_roundtrip_preserves_cose() -> anyhow::Result<()> {
4886        let (sk, vk) = generate_signing_keypair();
4887        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
4888        let resp = ResponseEnvelope::new_signed_hybrid(11, vec![7, 7], &sk, &pq_sk);
4889        let wire = response_to_wire(&resp);
4890        let reader = capnp::serialize::read_message(
4891            &mut std::io::Cursor::new(&wire),
4892            envelope_reader_options(),
4893        )?;
4894        let r = reader.get_root::<common_capnp::response_envelope::Reader>()?;
4895        let decoded = ResponseEnvelope::read_from(r)?;
4896        assert_eq!(
4897            decoded.cose, resp.cose,
4898            "cose must survive the capnp round-trip"
4899        );
4900        let store = pq_store_for(vk.to_bytes(), &pq_vk);
4901        decoded.verify_with(Some(&vk), Some(&store), CryptoPolicy::Hybrid)?;
4902        Ok(())
4903    }
4904
4905    // -- Cross-direction replay (the load-bearing domain-separation guard) -----
4906
4907    /// A REQUEST COSE composite must NOT verify against the RESPONSE AAD, and a
4908    /// RESPONSE COSE composite must NOT verify against the REQUEST AAD. Distinct
4909    /// type-ids in `external_aad` enforce this: the bytes are interchangeable but
4910    /// the AAD binding differs, so each direction's signature is non-fungible.
4911    #[test]
4912    fn cross_direction_replay_rejected() {
4913        let (sk, vk) = generate_signing_keypair();
4914        let payload = b"shared bytes";
4915
4916        // Build a REQUEST-domain composite and a RESPONSE-domain composite over
4917        // the same payload bytes, same key.
4918        let req_aad = envelope_external_aad();
4919        let resp_aad = response_envelope_external_aad();
4920        assert_ne!(
4921            req_aad, resp_aad,
4922            "request/response AADs must differ (domain separation)"
4923        );
4924
4925        let req_cose = crate::crypto::cose_sign::sign_composite(&sk, None, payload, &req_aad)
4926            .expect("sign req");
4927        let resp_cose = crate::crypto::cose_sign::sign_composite(&sk, None, payload, &resp_aad)
4928            .expect("sign resp");
4929
4930        // The request signature verifies under the request AAD …
4931        crate::crypto::cose_sign::verify_composite(&req_cose, &vk, None, payload, &req_aad, false)
4932            .expect("request verifies under request AAD");
4933        // … but MUST NOT verify under the response AAD (replay as a response).
4934        let cross1 = crate::crypto::cose_sign::verify_composite(
4935            &req_cose, &vk, None, payload, &resp_aad, false,
4936        );
4937        assert!(
4938            cross1.is_err(),
4939            "a request COSE sig must not verify as a response"
4940        );
4941
4942        // And symmetrically for the response signature.
4943        crate::crypto::cose_sign::verify_composite(
4944            &resp_cose, &vk, None, payload, &resp_aad, false,
4945        )
4946        .expect("response verifies under response AAD");
4947        let cross2 = crate::crypto::cose_sign::verify_composite(
4948            &resp_cose, &vk, None, payload, &req_aad, false,
4949        );
4950        assert!(
4951            cross2.is_err(),
4952            "a response COSE sig must not verify as a request"
4953        );
4954    }
4955
4956    /// End-to-end cross-direction: a `SignedEnvelope`'s COSE must not satisfy a
4957    /// `ResponseEnvelope::verify_with`, proving the request and response signing
4958    /// domains are separated at the envelope API level (not just the AAD helper).
4959    #[test]
4960    fn cross_direction_request_cose_rejected_as_response() {
4961        let (sk, vk) = generate_signing_keypair();
4962        // A request envelope's signing-data is canonical(RequestEnvelope); a
4963        // response's is request_id||payload. Even constructing a response whose
4964        // signing-data happens to match, the request-domain AAD differs, so the
4965        // composite cannot be reused. Here we directly graft a request COSE onto
4966        // a response and confirm rejection.
4967        let req = SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![1, 2, 3]), &sk);
4968        let mut resp = ResponseEnvelope::new_signed(0, vec![1, 2, 3], &sk);
4969        resp.cose = req.cose.clone(); // graft the request composite onto the response
4970        let res = resp.verify(Some(&vk));
4971        assert!(
4972            res.is_err(),
4973            "a request-domain COSE grafted onto a response must be rejected"
4974        );
4975    }
4976
4977    // -- v16 §4.7: the advertised server challenge is part of the transcript --
4978
4979    fn classical_denial(challenge: Option<Vec<u8>>, sk: &SigningKey) -> ResponseEnvelope {
4980        ResponseEnvelope::new_signed_with_challenge(
4981            7,
4982            b"denied".to_vec(),
4983            challenge,
4984            sk,
4985            None,
4986            crate::crypto::CryptoPolicy::Classical,
4987        )
4988        .expect("classical denial must sign")
4989    }
4990
4991    /// An ordinary response carries no challenge, and its transcript is
4992    /// unchanged by the new slot.
4993    #[test]
4994    fn a_response_without_a_challenge_has_the_original_transcript() {
4995        let (sk, vk) = generate_signing_keypair();
4996        let plain = ResponseEnvelope::new_signed(7, b"denied".to_vec(), &sk);
4997        let none = classical_denial(None, &sk);
4998        assert!(none.server_challenge.is_none());
4999        assert_eq!(
5000            plain.sig, none.sig,
5001            "no challenge must not alter the transcript"
5002        );
5003        assert!(none.verify(Some(&vk)).is_ok());
5004    }
5005
5006    #[test]
5007    fn an_advertised_challenge_verifies_and_survives_the_wire() {
5008        let (sk, vk) = generate_signing_keypair();
5009        let challenge = vec![0xa5u8; 32];
5010        let denied = classical_denial(Some(challenge.clone()), &sk);
5011        assert!(denied.verify(Some(&vk)).is_ok());
5012
5013        let mut message = capnp::message::Builder::new_default();
5014        {
5015            let mut builder =
5016                message.init_root::<crate::common_capnp::response_envelope::Builder>();
5017            denied.write_to(&mut builder);
5018        }
5019        let mut bytes = Vec::new();
5020        capnp::serialize::write_message(&mut bytes, &message).unwrap();
5021        let reader =
5022            capnp::serialize::read_message(&mut &bytes[..], capnp::message::ReaderOptions::new())
5023                .unwrap();
5024        let decoded = ResponseEnvelope::read_from(
5025            reader
5026                .get_root::<crate::common_capnp::response_envelope::Reader>()
5027                .unwrap(),
5028        )
5029        .unwrap();
5030        assert_eq!(decoded.server_challenge.as_deref(), Some(&challenge[..]));
5031        assert!(decoded.verify(Some(&vk)).is_ok());
5032    }
5033
5034    /// Stripping the advertised challenge in flight must not verify: a client
5035    /// can never be tricked into retrying without one, or into thinking the
5036    /// server issued none.
5037    #[test]
5038    fn a_stripped_challenge_fails_verification() {
5039        let (sk, vk) = generate_signing_keypair();
5040        let mut denied = classical_denial(Some(vec![0xa5u8; 32]), &sk);
5041        denied.server_challenge = None;
5042        assert!(denied.verify(Some(&vk)).is_err());
5043    }
5044
5045    /// Substituting a different challenge must not verify either, so an
5046    /// attacker cannot burn the client's single bounded retry.
5047    #[test]
5048    fn a_substituted_challenge_fails_verification() {
5049        let (sk, vk) = generate_signing_keypair();
5050        let mut denied = classical_denial(Some(vec![0xa5u8; 32]), &sk);
5051        denied.server_challenge = Some(vec![0x5au8; 32]);
5052        assert!(denied.verify(Some(&vk)).is_err());
5053    }
5054
5055    /// Injecting a challenge onto a response that advertised none fails too.
5056    #[test]
5057    fn an_injected_challenge_fails_verification() {
5058        let (sk, vk) = generate_signing_keypair();
5059        let mut plain = ResponseEnvelope::new_signed(7, b"denied".to_vec(), &sk);
5060        plain.server_challenge = Some(vec![0xa5u8; 32]);
5061        assert!(plain.verify(Some(&vk)).is_err());
5062    }
5063
5064    /// The length prefix makes the transcript unambiguous: no
5065    /// (payload, challenge) pair can be re-cut into a different one.
5066    #[test]
5067    fn the_challenge_binding_is_unambiguous() {
5068        let (sk, vk) = generate_signing_keypair();
5069        let a = ResponseEnvelope::new_signed_with_challenge(
5070            7,
5071            b"ab".to_vec(),
5072            Some(b"cdefghijklmnopqr".to_vec()),
5073            &sk,
5074            None,
5075            crate::crypto::CryptoPolicy::Classical,
5076        )
5077        .unwrap();
5078        let b = ResponseEnvelope::new_signed_with_challenge(
5079            7,
5080            b"abc".to_vec(),
5081            Some(b"defghijklmnopqr".to_vec()),
5082            &sk,
5083            None,
5084            crate::crypto::CryptoPolicy::Classical,
5085        );
5086        // The second challenge is below the profile floor, so it is not a
5087        // reachable wire state; the transcripts still differ regardless.
5088        if let Ok(b) = b {
5089            assert_ne!(a.sig, b.sig);
5090        }
5091        assert!(a.verify(Some(&vk)).is_ok());
5092    }
5093
5094    /// A challenge outside the profile's 16..64-byte bounds is not a value
5095    /// this profile can have issued, so decoding rejects it outright.
5096    #[test]
5097    fn an_out_of_profile_challenge_is_rejected_on_decode() {
5098        for bad in [vec![1u8; 15], vec![1u8; 65]] {
5099            let mut message = capnp::message::Builder::new_default();
5100            {
5101                let mut builder =
5102                    message.init_root::<crate::common_capnp::response_envelope::Builder>();
5103                builder.set_request_id(7);
5104                builder.set_payload(b"denied");
5105                builder.set_sig(&[0u8; 64]);
5106                builder.set_cnf(&[0u8; 32]);
5107                builder.set_cose(&[]);
5108                builder.set_server_challenge(&bad);
5109            }
5110            let mut bytes = Vec::new();
5111            capnp::serialize::write_message(&mut bytes, &message).unwrap();
5112            let reader = capnp::serialize::read_message(
5113                &mut &bytes[..],
5114                capnp::message::ReaderOptions::new(),
5115            )
5116            .unwrap();
5117            assert!(
5118                ResponseEnvelope::read_from(
5119                    reader
5120                        .get_root::<crate::common_capnp::response_envelope::Reader>()
5121                        .unwrap()
5122                )
5123                .is_err(),
5124                "a {}-byte challenge must be rejected",
5125                bad.len()
5126            );
5127        }
5128    }
5129
5130    #[test]
5131    fn sealed_response_roundtrip_is_transcript_bound_and_not_plaintext_on_wire() {
5132        let (server_sk, server_vk) = generate_signing_keypair();
5133        let pq_sk = crate::node_identity::derive_mesh_mldsa_key(&server_sk);
5134        let pq_vk = crate::crypto::pq::ml_dsa_vk_from_bytes(
5135            &crate::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq_sk),
5136        )
5137        .unwrap();
5138        let store = pq_store_for(server_vk.to_bytes(), &pq_vk);
5139        let recipient = crate::crypto::hybrid_kem::generate_recipient(
5140            crate::crypto::hybrid_kem::SuiteId::HyKemX25519MlKem768,
5141        )
5142        .unwrap();
5143        let public = recipient.public();
5144        let nonce = [0u8; 16];
5145        let secret_payload = b"response-plaintext-sentinel";
5146        let response = ResponseEnvelope::new_signed_encrypted(
5147            77,
5148            secret_payload.to_vec(),
5149            &server_sk,
5150            &pq_sk,
5151            &public,
5152            1234,
5153            &nonce,
5154            "service-a",
5155        )
5156        .unwrap();
5157        response
5158            .verify_encrypted_with_service_domain(&server_vk, &store, "service-a")
5159            .unwrap();
5160        let wire = response_to_wire(&response);
5161        assert!(!wire
5162            .windows(secret_payload.len())
5163            .any(|w| w == secret_payload));
5164        let public_unwrap =
5165            unwrap_response_with(&wire, Some(&server_vk), Some(&store), CryptoPolicy::Hybrid)
5166                .expect_err("public unwrap has no one-shot decapsulation state");
5167        assert!(public_unwrap.to_string().contains("decapsulation material"));
5168        let opened = response
5169            .open_encrypted(
5170                &recipient,
5171                &public,
5172                1234,
5173                &nonce,
5174                &server_vk.to_bytes(),
5175                "service-a",
5176            )
5177            .unwrap();
5178        assert_eq!(opened, secret_payload);
5179
5180        let wrong_recipient = crate::crypto::hybrid_kem::generate_recipient(
5181            crate::crypto::hybrid_kem::SuiteId::HyKemX25519MlKem768,
5182        )
5183        .unwrap();
5184        assert!(response
5185            .open_encrypted(
5186                &wrong_recipient,
5187                &wrong_recipient.public(),
5188                1234,
5189                &nonce,
5190                &server_vk.to_bytes(),
5191                "service-a",
5192            )
5193            .is_err());
5194        assert!(response
5195            .open_encrypted(
5196                &recipient,
5197                &public,
5198                1235,
5199                &nonce,
5200                &server_vk.to_bytes(),
5201                "service-a",
5202            )
5203            .is_err());
5204        let wrong_nonce = distinct_test_nonce(&nonce);
5205        assert!(response
5206            .open_encrypted(
5207                &recipient,
5208                &public,
5209                1234,
5210                &wrong_nonce,
5211                &server_vk.to_bytes(),
5212                "service-a",
5213            )
5214            .is_err());
5215        let (other_server, _) = generate_signing_keypair();
5216        assert!(response
5217            .open_encrypted(
5218                &recipient,
5219                &public,
5220                1234,
5221                &nonce,
5222                &other_server.verifying_key().to_bytes(),
5223                "service-a",
5224            )
5225            .is_err());
5226        assert!(response
5227            .verify_encrypted_with_service_domain(&server_vk, &store, "service-b")
5228            .is_err());
5229        assert!(response
5230            .open_encrypted(
5231                &recipient,
5232                &public,
5233                1234,
5234                &nonce,
5235                &server_vk.to_bytes(),
5236                "service-b",
5237            )
5238            .is_err());
5239    }
5240
5241    #[test]
5242    fn sealed_response_rejects_request_id_substitution_and_validly_signed_garbage() {
5243        let (server_sk, server_vk) = generate_signing_keypair();
5244        let pq_sk = crate::node_identity::derive_mesh_mldsa_key(&server_sk);
5245        let pq_vk = crate::crypto::pq::ml_dsa_vk_from_bytes(
5246            &crate::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq_sk),
5247        )
5248        .unwrap();
5249        let store = pq_store_for(server_vk.to_bytes(), &pq_vk);
5250        let recipient = crate::crypto::hybrid_kem::generate_recipient(
5251            crate::crypto::hybrid_kem::SuiteId::HyKemX25519MlKem768,
5252        )
5253        .unwrap();
5254        let public = recipient.public();
5255        let nonce = [0u8; 16];
5256        let mut response = ResponseEnvelope::new_signed_encrypted(
5257            8,
5258            b"bound".to_vec(),
5259            &server_sk,
5260            &pq_sk,
5261            &public,
5262            99,
5263            &nonce,
5264            "service-a",
5265        )
5266        .unwrap();
5267
5268        response.request_id = 9;
5269        let data = ResponseEnvelope::encrypted_signing_data(
5270            response.request_id,
5271            response.encrypted_response.as_deref().unwrap(),
5272            "service-a",
5273        )
5274        .unwrap();
5275        response.sig = server_sk.sign(&data).to_bytes();
5276        response.cose =
5277            ResponseEnvelope::build_cose(&server_sk, Some(&pq_sk), CryptoPolicy::Hybrid, &data)
5278                .unwrap();
5279        response
5280            .verify_encrypted_with_service_domain(&server_vk, &store, "service-a")
5281            .unwrap();
5282        assert!(response
5283            .open_encrypted(
5284                &recipient,
5285                &public,
5286                99,
5287                &nonce,
5288                &server_vk.to_bytes(),
5289                "service-a",
5290            )
5291            .is_err());
5292
5293        response.encrypted_response = Some(b"not-a-cose-encrypt0".to_vec());
5294        let data = ResponseEnvelope::encrypted_signing_data(
5295            9,
5296            response.encrypted_response.as_deref().unwrap(),
5297            "service-a",
5298        )
5299        .unwrap();
5300        response.sig = server_sk.sign(&data).to_bytes();
5301        response.cose =
5302            ResponseEnvelope::build_cose(&server_sk, Some(&pq_sk), CryptoPolicy::Hybrid, &data)
5303                .unwrap();
5304        response
5305            .verify_encrypted_with_service_domain(&server_vk, &store, "service-a")
5306            .unwrap();
5307        assert!(response
5308            .open_encrypted(
5309                &recipient,
5310                &public,
5311                99,
5312                &nonce,
5313                &server_vk.to_bytes(),
5314                "service-a",
5315            )
5316            .is_err());
5317    }
5318
5319    #[test]
5320    fn cleartext_response_is_refused_by_early_network_gate() {
5321        let (sk, _) = generate_signing_keypair();
5322        let wire = response_to_wire(&ResponseEnvelope::new_signed(
5323            1,
5324            b"must-not-surface".to_vec(),
5325            &sk,
5326        ));
5327        assert!(read_response_envelope(&wire, true).is_err());
5328    }
5329
5330    #[test]
5331    fn response_recipient_and_ciphertext_sizes_are_bounded() {
5332        let mut request_message = capnp::message::Builder::new_default();
5333        {
5334            let mut builder =
5335                request_message.init_root::<crate::common_capnp::request_envelope::Builder>();
5336            builder.set_nonce(&[0u8; 16]);
5337            builder.set_response_kem_recipient(&vec![0u8; MAX_RESPONSE_KEM_RECIPIENT_BYTES + 1]);
5338        }
5339        let request_message_reader = request_message.into_reader();
5340        let request_reader = request_message_reader
5341            .get_root::<crate::common_capnp::request_envelope::Reader>()
5342            .unwrap();
5343        assert!(RequestEnvelope::read_from(request_reader).is_err());
5344
5345        let mut response_message = capnp::message::Builder::new_default();
5346        {
5347            let mut builder =
5348                response_message.init_root::<crate::common_capnp::response_envelope::Builder>();
5349            builder.set_sig(&[0u8; 64]);
5350            builder.set_cnf(&[0u8; 32]);
5351            builder.set_encrypted_response(&vec![0u8; MAX_ENCRYPTED_RESPONSE_BYTES + 1]);
5352        }
5353        let response_message_reader = response_message.into_reader();
5354        let response_reader = response_message_reader
5355            .get_root::<crate::common_capnp::response_envelope::Reader>()
5356            .unwrap();
5357        assert!(ResponseEnvelope::read_from(response_reader).is_err());
5358    }
5359
5360    // =========================================================================
5361    // Per-identity PQ enforcement: anchoring an identity turns PQ on for THAT
5362    // identity, without a deployment-wide flag day for everyone else.
5363    // =========================================================================
5364
5365    /// An anchored identity must present the outer ML-DSA-65 layer even where
5366    /// the deployment's global policy still admits classical peers.
5367    #[test]
5368    fn anchored_identity_rejects_classical_under_classical_policy() {
5369        let (sk, vk) = generate_signing_keypair();
5370        let (_pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
5371        let cache = TestNonceCache::new();
5372        let signed = SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![1]), &sk);
5373        let store = pq_store_for(vk.to_bytes(), &pq_vk);
5374        let res = signed.verify_with(&vk, &cache, Some(&store), CryptoPolicy::Classical);
5375        assert!(
5376            res.is_err(),
5377            "an anchored identity must not be admitted with a classical-only signature"
5378        );
5379    }
5380
5381    /// The same anchored identity is admitted when it signs hybrid.
5382    #[test]
5383    fn anchored_identity_accepts_hybrid_under_classical_policy() -> crate::EnvelopeResult<()> {
5384        let (sk, vk) = generate_signing_keypair();
5385        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
5386        let cache = TestNonceCache::new();
5387        let signed =
5388            SignedEnvelope::new_signed_hybrid(RequestEnvelope::anonymous(vec![2]), &sk, &pq_sk);
5389        let store = pq_store_for(vk.to_bytes(), &pq_vk);
5390        signed.verify_with(&vk, &cache, Some(&store), CryptoPolicy::Classical)?;
5391        Ok(())
5392    }
5393
5394    /// No flag day: an identity with no anchored PQ key keeps behaving exactly
5395    /// as before under a classical-permissive policy, even when a PQ store is
5396    /// consulted and holds bindings for other identities.
5397    #[test]
5398    fn unanchored_identity_unchanged_under_classical_policy() -> crate::EnvelopeResult<()> {
5399        let (sk, vk) = generate_signing_keypair();
5400        let (other_sk, other_vk) = generate_signing_keypair();
5401        let (_pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
5402        let cache = TestNonceCache::new();
5403
5404        // A store that anchors somebody else entirely.
5405        let store = pq_store_for(other_vk.to_bytes(), &pq_vk);
5406        let signed = SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![3]), &sk);
5407        signed.verify_with(&vk, &cache, Some(&store), CryptoPolicy::Classical)?;
5408
5409        // An entirely empty store is likewise unchanged.
5410        let empty = KeyedPqTrustStore::new();
5411        let signed2 = SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![4]), &other_sk);
5412        signed2.verify_with(&other_vk, &cache, Some(&empty), CryptoPolicy::Classical)?;
5413        Ok(())
5414    }
5415
5416    /// One process, one store, two services: the anchored one is enforced and
5417    /// the unanchored one is not.
5418    #[test]
5419    fn mixed_anchored_and_unanchored_services_in_one_store() -> crate::EnvelopeResult<()> {
5420        let (anchored_sk, anchored_vk) = generate_signing_keypair();
5421        let (legacy_sk, legacy_vk) = generate_signing_keypair();
5422        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
5423        let cache = TestNonceCache::new();
5424
5425        let mut store = KeyedPqTrustStore::new();
5426        store.bind(anchored_vk.to_bytes(), &pq_vk);
5427
5428        // Anchored service: classical rejected, hybrid accepted.
5429        let classical =
5430            SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![5]), &anchored_sk);
5431        assert!(
5432            classical
5433                .verify_with(&anchored_vk, &cache, Some(&store), CryptoPolicy::Classical)
5434                .is_err(),
5435            "anchored service must be held to the hybrid signature"
5436        );
5437        let hybrid = SignedEnvelope::new_signed_hybrid(
5438            RequestEnvelope::anonymous(vec![6]),
5439            &anchored_sk,
5440            &pq_sk,
5441        );
5442        hybrid.verify_with(&anchored_vk, &cache, Some(&store), CryptoPolicy::Classical)?;
5443
5444        // Unanchored service in the SAME store keeps the classical floor.
5445        let legacy = SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![7]), &legacy_sk);
5446        legacy.verify_with(&legacy_vk, &cache, Some(&store), CryptoPolicy::Classical)?;
5447        Ok(())
5448    }
5449
5450    /// The interop guarantee, in the shape a real deployment has it.
5451    ///
5452    /// Every internal service identity is provisioned hybrid and is therefore
5453    /// anchored, so the store is non-empty and PQ is enforced for all of them.
5454    /// An external classical client — an identity this node does not provision
5455    /// and never anchors — must keep verifying on its Ed25519 signature alone
5456    /// in that same process, against that same store. Making internal service
5457    /// identities mandatorily hybrid must not reach this path.
5458    #[test]
5459    fn unanchored_interop_client_still_verifies_classically() -> crate::EnvelopeResult<()> {
5460        let cache = TestNonceCache::new();
5461
5462        // Two internal services, both hybrid and both anchored.
5463        let (svc_a_sk, svc_a_vk) = generate_signing_keypair();
5464        let (svc_b_sk, svc_b_vk) = generate_signing_keypair();
5465        let (svc_a_pq_sk, svc_a_pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
5466        let (svc_b_pq_sk, svc_b_pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
5467        let mut store = KeyedPqTrustStore::new();
5468        store.bind(svc_a_vk.to_bytes(), &svc_a_pq_vk);
5469        store.bind(svc_b_vk.to_bytes(), &svc_b_pq_vk);
5470
5471        // Both services verify hybrid, and neither can fall back to classical.
5472        for (sk, vk, pq_sk, tag) in [
5473            (&svc_a_sk, &svc_a_vk, &svc_a_pq_sk, 10u8),
5474            (&svc_b_sk, &svc_b_vk, &svc_b_pq_sk, 11u8),
5475        ] {
5476            SignedEnvelope::new_signed_hybrid(RequestEnvelope::anonymous(vec![tag]), sk, pq_sk)
5477                .verify_with(vk, &cache, Some(&store), CryptoPolicy::Classical)?;
5478            assert!(
5479                SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![tag + 100]), sk)
5480                    .verify_with(vk, &cache, Some(&store), CryptoPolicy::Classical)
5481                    .is_err(),
5482                "an anchored service identity must not verify classically"
5483            );
5484        }
5485
5486        // The interop client: not a service, never anchored, classical only.
5487        let (client_sk, client_vk) = generate_signing_keypair();
5488        assert!(
5489            !store.is_anchored(&client_vk.to_bytes()),
5490            "the interop client must not be anchored — that is what this test is about"
5491        );
5492        SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![12]), &client_sk).verify_with(
5493            &client_vk,
5494            &cache,
5495            Some(&store),
5496            CryptoPolicy::Classical,
5497        )?;
5498
5499        Ok(())
5500    }
5501
5502    /// Anchoring is monotonic: re-registering an anchored identity from a
5503    /// classical-only source must not drop the binding, or enforcement could be
5504    /// switched back off by replaying a legacy enrollment.
5505    #[test]
5506    fn anchored_identity_cannot_be_downgraded_to_unanchored() {
5507        let (sk, vk) = generate_signing_keypair();
5508        let (_pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
5509        let cache = TestNonceCache::new();
5510
5511        let mut store = KeyedPqTrustStore::new();
5512        assert!(store.register(vk.to_bytes(), Some(&pq_vk)));
5513        assert!(
5514            store.register(vk.to_bytes(), None),
5515            "classical re-registration must not clear the anchor"
5516        );
5517        assert!(store.is_anchored(&vk.to_bytes()));
5518        assert_eq!(store.len(), 1);
5519
5520        // And the surviving anchor still enforces the PQ leg.
5521        let classical = SignedEnvelope::new_signed(RequestEnvelope::anonymous(vec![8]), &sk);
5522        assert!(
5523            classical
5524                .verify_with(&vk, &cache, Some(&store), CryptoPolicy::Classical)
5525                .is_err(),
5526            "the surviving anchor must still require the hybrid signature"
5527        );
5528    }
5529
5530    /// Registering an unanchored identity leaves it unanchored (a classical
5531    /// entry never fabricates a binding).
5532    #[test]
5533    fn classical_registration_anchors_nothing() {
5534        let (_sk, vk) = generate_signing_keypair();
5535        let mut store = KeyedPqTrustStore::new();
5536        assert!(!store.register(vk.to_bytes(), None));
5537        assert!(store.is_empty());
5538    }
5539
5540    /// A differing PQ key for an already-anchored identity is refused — the
5541    /// existing anchor is retained and the rebind is not silent. This prevents
5542    /// a stale bootstrap entry (or hostile seeding source) from substituting a
5543    /// different PQ identity for an operator-anchored peer.
5544    #[test]
5545    fn differing_pq_rebind_is_refused_not_silent() {
5546        let (_sk1, vk) = generate_signing_keypair();
5547        let (_pq_sk_a, pq_vk_a) = crate::crypto::pq::ml_dsa_generate_keypair();
5548        let (_pq_sk_b, pq_vk_b) = crate::crypto::pq::ml_dsa_generate_keypair();
5549
5550        let mut store = KeyedPqTrustStore::new();
5551        store.bind(vk.to_bytes(), &pq_vk_a);
5552
5553        // Attempt to rebind to a different PQ key — must be refused.
5554        store.bind(vk.to_bytes(), &pq_vk_b);
5555
5556        // The original anchor survives.
5557        let anchored_vk = store
5558            .ml_dsa_key_for(&vk.to_bytes())
5559            .expect("anchor survived");
5560        let original_bytes = crate::crypto::pq::ml_dsa_vk_bytes(&pq_vk_a);
5561        let survived_bytes = crate::crypto::pq::ml_dsa_vk_bytes(&anchored_vk);
5562        assert_eq!(
5563            original_bytes, survived_bytes,
5564            "the original PQ key must be retained, not the attempted rebind"
5565        );
5566        assert_eq!(store.len(), 1, "no duplicate entry created");
5567
5568        // Re-registering the SAME key via register() is idempotent.
5569        store.register(vk.to_bytes(), Some(&pq_vk_a));
5570        assert_eq!(store.len(), 1);
5571    }
5572
5573    /// The response side enforces the same per-identity rule.
5574    #[test]
5575    fn anchored_responder_rejects_classical_response() -> anyhow::Result<()> {
5576        let (sk, vk) = generate_signing_keypair();
5577        let (pq_sk, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
5578        let store = pq_store_for(vk.to_bytes(), &pq_vk);
5579
5580        let classical = ResponseEnvelope::new_signed(21, vec![1, 2], &sk);
5581        assert!(
5582            classical
5583                .verify_with(Some(&vk), Some(&store), CryptoPolicy::Classical)
5584                .is_err(),
5585            "an anchored responder must not be admitted with a classical-only signature"
5586        );
5587
5588        let hybrid = ResponseEnvelope::new_signed_hybrid(22, vec![3, 4], &sk, &pq_sk);
5589        hybrid.verify_with(Some(&vk), Some(&store), CryptoPolicy::Classical)?;
5590        Ok(())
5591    }
5592
5593    /// No flag day on the response side either.
5594    #[test]
5595    fn unanchored_responder_unchanged_under_classical_policy() -> anyhow::Result<()> {
5596        let (sk, vk) = generate_signing_keypair();
5597        let empty = KeyedPqTrustStore::new();
5598        let classical = ResponseEnvelope::new_signed(23, vec![5, 6], &sk);
5599        classical.verify_with(Some(&vk), Some(&empty), CryptoPolicy::Classical)?;
5600        Ok(())
5601    }
5602}