Skip to main content

hyprstream_rpc/service/
svc.rs

1//! RPC service infrastructure.
2//!
3//! Provides `RequestService`, `EnvelopeContext`, `ServiceHandle`, and `QuicLoopConfig`.
4//!
5//! # Envelope-Based Security
6//!
7//! All requests are wrapped in `SignedEnvelope` for authentication:
8//! - `process_request` unwraps and verifies signatures before dispatching
9//! - Handlers receive `EnvelopeContext` with verified identity
10//! - Services use `ctx.subject()` for policy checks
11
12use crate::identity::UNAUTHENTICATED_DID_SENTINEL;
13use crate::prelude::*;
14use crate::transport::TransportConfig;
15use anyhow::Result;
16use async_trait::async_trait;
17use zeroize::Zeroizing;
18// AtomicU64 and Ordering removed — were unused
19use std::sync::Arc;
20use tokio::sync::Notify;
21use tracing::warn;
22
23/// Maximum serialized holder evidence accepted by mediated authorization.
24const MAX_MEDIATED_EVIDENCE_BYTES: usize = crate::envelope::MAX_MEDIATED_EVIDENCE_BYTES;
25
26/// Original signed material is sensitive; Debug must never expose it.
27#[derive(Clone)]
28struct MediatedEvidence(Arc<[u8]>);
29
30impl std::fmt::Debug for MediatedEvidence {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.write_str("MediatedEvidence([REDACTED])")
33    }
34}
35
36impl MediatedEvidence {
37    fn from_envelope(envelope: &SignedEnvelope) -> Option<Self> {
38        // Never represent recovered plaintext as an outer ciphertext signature.
39        if envelope.encrypted_envelope.is_some() {
40            return crate::authorization_witness::package(&envelope.envelope, &envelope.cnf)
41                .map(|bytes| Self(bytes.into()));
42        }
43        if !crate::envelope::mediated_request_fits(&envelope.envelope)
44            || envelope.cose.len() > MAX_MEDIATED_EVIDENCE_BYTES
45            || envelope
46                .pq_kem_ciphertext
47                .as_ref()
48                .is_some_and(|bytes| bytes.len() > MAX_MEDIATED_EVIDENCE_BYTES)
49        {
50            return None;
51        }
52        let mut message = capnp::message::Builder::new_default();
53        envelope.write_to(
54            &mut message.init_root::<crate::common_capnp::signed_envelope::Builder<'_>>(),
55        );
56        let bytes = capnp::serialize::write_message_to_words(&message);
57        (bytes.len() <= MAX_MEDIATED_EVIDENCE_BYTES).then(|| Self(bytes.into()))
58    }
59}
60
61/// Authorization callback for policy checks.
62///
63/// Parameters: (verified ingress context, resource, operation) -> allowed.
64/// Carry the original evidence with the context; a subject string and bearer
65/// alone cannot prove a service holder's request to a mediator.
66/// Services store this and call it from their `authorize()` handler method.
67/// The concrete implementation typically wraps `PolicyClient::check_policy()`.
68///
69/// Returns a boxed future to support async policy checks on single-threaded runtimes.
70pub type AuthorizeFn = Arc<
71    dyn Fn(
72            EnvelopeContext,
73            String,
74            String,
75        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool>> + Send>>
76        + Send
77        + Sync,
78>;
79
80/// Decompose a composite JWT alg into its underlying component algs.
81///
82/// Used by the stripping defense in `verify_claims`: when a JWKS lists
83/// multiple algs under one kid, the verifier needs to know that an
84/// incoming alg like `ML-DSA-65-Ed25519` covers both `ML-DSA-65` and
85/// `EdDSA`, so a composite-signed JWT is sufficient. Single algs return
86/// just themselves.
87fn composite_alg_components(alg: &str) -> Vec<&'static str> {
88    match alg {
89        "ML-DSA-65-Ed25519" => vec!["ML-DSA-65", "EdDSA", "ML-DSA-65-Ed25519"],
90        "ML-DSA-65" => vec!["ML-DSA-65"],
91        "EdDSA" => vec!["EdDSA"],
92        "ES256" => vec!["ES256"],
93        "RS256" => vec!["RS256"],
94        _ => Vec::new(),
95    }
96}
97
98/// Whether a JWT `alg` carries an ML-DSA-65 (post-quantum) component. Fu4/#677.
99fn alg_covers_pq(alg: &str) -> bool {
100    matches!(alg, "ML-DSA-65" | "ML-DSA-65-Ed25519")
101}
102
103/// Fu4/#677: CryptoPolicy-driven minimum-alg gate for JWT verification.
104///
105/// The `verify_claims` alg-routing accepts an EdDSA-only (classical) JWT
106/// whenever a kid resolves. Anti-stripping relies on `kid_algs`, whose default
107/// impl is empty ([`crate::auth::JwtKeySource::kid_algs]) and which the common
108/// `ClusterKeySource` never populates — so the existing defense is a no-op for
109/// most services. This gate makes the floor explicit and policy-driven: under a
110/// Hybrid [`CryptoPolicy`] a classical-only (`EdDSA`) JWT is rejected
111/// **independent of JWKS alg-list hygiene**. Under Classical any single alg is
112/// passed through to the per-alg decoders (existing behavior).
113fn jwt_alg_satisfies_policy(policy: crate::crypto::CryptoPolicy, alg: &str) -> anyhow::Result<()> {
114    if policy.uses_pq() && !alg_covers_pq(alg) {
115        anyhow::bail!(
116            "Hybrid crypto policy requires a post-quantum JWT alg; \
117             classical-only alg '{}' rejected (Fu4/#677)",
118            alg
119        );
120    }
121    Ok(())
122}
123
124/// Work to execute after the RPC response is sent (e.g., stream publishing).
125pub type Continuation = std::pin::Pin<Box<dyn std::future::Future<Output = ()>>>;
126
127/// Context extracted from a verified SignedEnvelope.
128///
129/// Passed to service handlers after signature verification. Handlers use this for:
130/// - Authorization checks via `subject()`
131/// - Correlation via `request_id`
132///
133/// # Example
134///
135/// ```ignore
136/// fn handle_request(&self, ctx: &EnvelopeContext, payload: &[u8]) -> Result<(Vec<u8>, Option<Continuation>)> {
137///     // Check authorization
138///     let sub = ctx.subject().to_string();
139///     if !policy_manager.check(&sub, "Model", "infer") {
140///         return Err(anyhow!("unauthorized: {}", sub));
141///     }
142///     // Process request...
143/// }
144/// ```
145#[derive(Debug, Clone)]
146pub struct EnvelopeContext {
147    /// Unique request ID for correlation and logging
148    pub request_id: u64,
149
150    /// User claims decoded from jwt_token (or legacy claims field).
151    /// Populated by `verify_claims()` after JWT signature verification.
152    claims: Option<crate::auth::Claims>,
153
154    /// Tenant/domain from a verified JWT claim or a trusted local constructor.
155    ///
156    /// Network callers cannot populate this directly: `verify_claims()` copies
157    /// it only after the JWT signature and issuer have been verified.
158    verified_tenant: Option<String>,
159
160    /// Raw JWT token from the envelope. Server decodes and verifies this.
161    /// Preferred over the legacy `claims` field when present.
162    jwt_token: Option<String>,
163    /// Set only after the complete direct JWT verification path succeeds,
164    /// including revocation, session, confirmation and WTH checks. Prevents a
165    /// future dynamic proof consumer from constructing an authority handle
166    /// from merely parsed, legacy or partially verified claims.
167    direct_jwt_verified: bool,
168    /// Set only when a delegated user credential was signature-checked against
169    /// a configured non-native audience; dispatch restricts its decoded leaf.
170    delegated_resource_audience: bool,
171    /// A signature-verified reserved Federate JWT awaiting its original-holder
172    /// proof and Policy admission. It confers no identity before commit.
173    deferred_federate: Option<(crate::auth::Claims, Subject)>,
174    /// Set by `verify_claims()`: the credential is of the Federate TUI client
175    /// class (marker set, or the authority-owned deployment class pin).
176    /// Dispatch fences classified credentials (see dispatch.rs); evidence
177    /// verification never sets this on the REQUEST context.
178    federate_tui_class: bool,
179    /// Installed only after the H3b hybrid proof and durable Policy admission.
180    /// The envelope signer may be a relay and is never the caller's assurance.
181    federate_holder_ed: Option<[u8; 32]>,
182    federate_request_use: Option<(String, String)>,
183    /// Bearer relayed by an authenticated service; deny-by-default.
184    delegation_token: Option<String>,
185
186    /// Authorization subject derived from the verified Ed25519 signer key.
187    ///
188    /// Set by `from_verified_as_system()` (FixedSigner path).
189    /// `Anonymous` when AnySigner/WebTransport callers (identity from JWT/trust store).
190    key_derived_subject: Subject,
191
192    /// Authorization subject resolved from a verified JWT token.
193    ///
194    /// Set by `verify_claims()` after it determines whether the token is
195    /// local (bare subject: `"alice"`) or federated (`"https://node-a:alice"`).
196    /// `None` until `verify_claims()` runs, or when no JWT is present.
197    pub(crate) jwt_subject: Option<Subject>,
198
199    /// Ed25519 public key of the envelope signer (RFC 7800 confirmation key).
200    /// Cryptographically verified by Ed25519 signature check.
201    pub cnf: [u8; 32],
202
203    /// WIMSE wth binding: SHA-256 of the WIT JWT from the envelope (if present).
204    /// Populated from `RequestEnvelope.wit_hash` during context construction.
205    pub(crate) envelope_wit_hash: Option<[u8; 32]>,
206
207    /// Client's ephemeral DH public key for stream key derivation.
208    /// Present on streaming requests; extracted from `RequestEnvelope.client_dh_public`.
209    client_dh_public: Option<[u8; 32]>,
210
211    /// Authenticated, suite-complete ephemeral HyKEM recipient for an identified
212    /// stream.  This is only key material; handlers must still supply the
213    /// accepted-current [`IdentifiedStreamBinding`] and pass the key-release PEP.
214    client_kem_public: Option<crate::crypto::hybrid_kem::RecipientPublic>,
215
216    /// Authenticated request transcript and one-shot response recipient.
217    /// These are used only by the response seal chokepoint.
218    pub(crate) request_iat: i64,
219    pub(crate) request_nonce: [u8; 16],
220    pub(crate) response_kem_recipient: Option<crate::crypto::hybrid_kem::RecipientPublic>,
221    pub(crate) service_domain: Option<String>,
222
223    /// v16 proof CWT bytes, if present on the verified envelope.
224    pub(crate) envelope_proof_cwt: Option<Vec<u8>>,
225    original_holder_evidence: Option<MediatedEvidence>,
226
227    /// Browser-only method commitment independently checked by generated
228    /// service dispatch after the sealed transcript is recovered.
229    pub(crate) browser_method_discriminator: Option<u16>,
230
231    /// Verified internal execution work order (`iw+jwt`, single-service
232    /// Model→Inference boundary). Set ONLY by `verify_claims` after the
233    /// service's `verify_internal_work_bearer` hook authenticated the token
234    /// against its pinned controller; never populated from wire data alone.
235    pub(crate) internal_work: Option<crate::auth::internal_work::InternalWorkContext>,
236
237    /// Whether this request originated from a genuine in-process / IPC caller
238    /// (the `FixedSigner` mutual-auth plane), as opposed to a networked peer
239    /// (the `AnySigner` plane used by ZMQ-QUIC / iroh / WebTransport).
240    ///
241    /// `true` ONLY for `from_verified_as_system` and `from_callback_service`
242    /// (genuine local callers). Networked callers (`from_verified`) are `false`.
243    /// Gates the empty-`iss` JWT shortcut (#328): an empty issuer is the local
244    /// PolicyService's bare-`sub` token and is accepted ONLY for local callers;
245    /// a networked peer presenting an empty-`iss` token is rejected (fail-closed).
246    is_local_caller: bool,
247}
248
249impl EnvelopeContext {
250    /// Verify the original holder's hybrid transcript without granting local
251    /// transport provenance. Credential verification is still mandatory.
252    #[cfg(not(target_arch = "wasm32"))]
253    pub fn from_mediated_evidence(
254        evidence: &[u8],
255        mediator_service: &str,
256        operation: &str,
257    ) -> Result<Self> {
258        if crate::authorization_witness::is_witness_evidence(evidence) {
259            let verified = crate::authorization_witness::verify(evidence, mediator_service)?;
260            if let Some(signed_operation) = verified.operation.as_deref() {
261                anyhow::ensure!(
262                    signed_operation == operation,
263                    "mediated operation does not match holder-signed request leaf"
264                );
265            } else {
266                crate::proof::policy::verify_mediated_operation(
267                    mediator_service,
268                    &verified.request.payload,
269                    operation,
270                )?;
271            }
272            return Ok(Self::from_authenticated_request(
273                &verified.request,
274                verified.signer,
275                Some(MediatedEvidence(evidence.to_vec().into())),
276            ));
277        }
278        let signed =
279            crate::envelope::verify_mediated_envelope_evidence(evidence, mediator_service)?;
280        crate::proof::policy::verify_mediated_operation(
281            mediator_service,
282            &signed.envelope.payload,
283            operation,
284        )?;
285        Ok(Self::from_verified(&signed))
286    }
287
288    /// Bounded original signed request for a read-only mediated Policy query.
289    /// Possession of these bytes is not an identity grant; the receiver must
290    /// independently verify holder, credential, target, method and freshness.
291    pub fn original_holder_evidence(&self) -> Option<&[u8]> {
292        self.original_holder_evidence
293            .as_ref()
294            .map(|evidence| evidence.0.as_ref())
295    }
296
297    /// Record a verified holder's derived authorization query, independently
298    /// of the request's original dispatch admission. No default local store:
299    /// startup must install the topology-qualified replay backend.
300    #[cfg(not(target_arch = "wasm32"))]
301    pub fn admit_mediated_query(
302        &self,
303        mediator: &str,
304        resource: &str,
305        operation: &str,
306    ) -> Result<()> {
307        use crate::proof::admission::{
308            admit_mediated_query, global_proof_replay_store, validate_mediated_query_dimensions,
309            MediatedQueryReplayKey, ProofAdmissionResult,
310        };
311        use sha2::{Digest, Sha256};
312        anyhow::ensure!(
313            self.claims().is_some() && self.original_holder_evidence.is_some(),
314            "verified holder evidence required"
315        );
316        // Validate mediated-query dimensions on the borrowed values before the
317        // owned replay key is built (bounded preallocation, Sol MED-2).
318        validate_mediated_query_dimensions(mediator, resource, operation)?;
319        anyhow::ensure!(
320            self.service_domain.as_deref() == Some(mediator),
321            "mediator target mismatch"
322        );
323        // Envelope iat is milliseconds and its age boundary is inclusive.
324        // Retain through that last accepted millisecond, rounding up to the
325        // replay store's exclusive seconds boundary, never down.
326        let last_valid_ms = self
327            .request_iat
328            .checked_add(crate::envelope::MAX_TIMESTAMP_AGE_MS)
329            .ok_or_else(|| anyhow::anyhow!("mediated expiry overflow"))?;
330        let expires_at = u64::try_from(
331            last_valid_ms
332                .div_euclid(1000)
333                .checked_add(1)
334                .ok_or_else(|| anyhow::anyhow!("mediated expiry overflow"))?,
335        )?;
336        let key = MediatedQueryReplayKey {
337            signer_thumbprint: Sha256::digest(self.cnf).into(),
338            request_id: self.request_id,
339            request_nonce: self.request_nonce,
340            mediator: mediator.to_owned(),
341            resource: resource.to_owned(),
342            operation: operation.to_owned(),
343        };
344        let store = global_proof_replay_store()
345            .ok_or_else(|| anyhow::anyhow!("no mediated replay backend installed"))?;
346        anyhow::ensure!(
347            admit_mediated_query(store, &key, expires_at) == ProofAdmissionResult::Admitted,
348            "mediated query replay admission denied"
349        );
350        Ok(())
351    }
352
353    /// Create context from a verified SignedEnvelope (AnySigner path).
354    ///
355    /// `key_derived_subject` is `Anonymous`. Use `from_verified_as_system()` for
356    /// FixedSigner/inproc callers.
357    ///
358    /// `pub(crate)` — external callers should use the named constructors above
359    /// to make the trust level explicit.
360    pub(crate) fn from_verified(envelope: &SignedEnvelope) -> Self {
361        Self::from_authenticated_request(
362            &envelope.envelope,
363            envelope.cnf,
364            MediatedEvidence::from_envelope(envelope),
365        )
366    }
367
368    // Only callers that verified either the envelope or the purpose-bound
369    // witness may use this. Credential verification is still mandatory.
370    fn from_authenticated_request(
371        envelope: &crate::envelope::RequestEnvelope,
372        cnf: [u8; 32],
373        evidence: Option<MediatedEvidence>,
374    ) -> Self {
375        Self {
376            request_id: envelope.request_id,
377            claims: None,
378            verified_tenant: None,
379            jwt_token: envelope.jwt_token().map(ToOwned::to_owned),
380            direct_jwt_verified: false,
381            delegated_resource_audience: false,
382            deferred_federate: None,
383            federate_tui_class: false,
384            federate_holder_ed: None,
385            federate_request_use: None,
386            delegation_token: envelope.delegation_token.clone(),
387            key_derived_subject: Subject::anonymous(),
388            jwt_subject: None,
389            cnf,
390            envelope_wit_hash: envelope.wth,
391            client_dh_public: envelope.client_dh_public,
392            client_kem_public: envelope.client_kem_public.clone(),
393            request_iat: envelope.iat,
394            request_nonce: envelope.nonce,
395            response_kem_recipient: envelope.response_kem_recipient.clone(),
396            service_domain: envelope.service_domain.clone(),
397            envelope_proof_cwt: envelope.proof_cwt.clone(),
398            original_holder_evidence: evidence,
399            browser_method_discriminator: None,
400            internal_work: None,
401            // AnySigner / networked plane — NOT a local caller (#328).
402            is_local_caller: false,
403        }
404    }
405
406    /// Create context for a FixedSigner (inproc/IPC) caller.
407    ///
408    /// Sets `key_derived_subject = Subject::new("system")`, so `subject()` always
409    /// returns `"system"` for this context regardless of any caller-asserted
410    /// authorization field. Used in `process_request` for inproc callers.
411    pub fn from_verified_as_system(envelope: &SignedEnvelope) -> Self {
412        Self {
413            request_id: envelope.request_id(),
414            claims: None,
415            verified_tenant: Some("local".to_owned()),
416            jwt_token: envelope.envelope.jwt_token().map(ToOwned::to_owned),
417            direct_jwt_verified: false,
418            delegated_resource_audience: false,
419            deferred_federate: None,
420            federate_tui_class: false,
421            federate_holder_ed: None,
422            federate_request_use: None,
423            delegation_token: envelope.envelope.delegation_token.clone(),
424            key_derived_subject: Subject::new("system"),
425            jwt_subject: None,
426            cnf: envelope.cnf,
427            envelope_wit_hash: envelope.envelope.wth,
428            client_dh_public: envelope.envelope.client_dh_public,
429            client_kem_public: envelope.envelope.client_kem_public.clone(),
430            request_iat: envelope.envelope.iat,
431            request_nonce: envelope.envelope.nonce,
432            response_kem_recipient: envelope.envelope.response_kem_recipient.clone(),
433            service_domain: envelope.envelope.service_domain.clone(),
434            envelope_proof_cwt: envelope.envelope.proof_cwt.clone(),
435            original_holder_evidence: MediatedEvidence::from_envelope(envelope),
436            browser_method_discriminator: None,
437            internal_work: None,
438            // FixedSigner mutual-auth plane — genuine in-process / IPC caller (#328).
439            is_local_caller: true,
440        }
441    }
442
443    /// Create a service-identity context for internal callbacks that bypass the envelope pipeline.
444    ///
445    /// Used by services that make inproc self-calls without a real `SignedEnvelope`
446    /// (e.g., `InferenceService` callback mode). Sets `key_derived_subject = "service:{name}"`
447    /// so that `subject()` returns a proper service identity for authorization.
448    ///
449    /// `cnf` is zeroed because there is no real envelope; the service subject
450    /// is asserted directly and is trusted because this constructor is only reachable
451    /// from internal code paths that never cross a network boundary.
452    pub fn from_callback_service(request_id: u64, service_name: &str) -> Self {
453        Self {
454            request_id,
455            claims: None,
456            verified_tenant: Some("local".to_owned()),
457            jwt_token: None,
458            direct_jwt_verified: false,
459            delegated_resource_audience: false,
460            deferred_federate: None,
461            federate_tui_class: false,
462            federate_holder_ed: None,
463            federate_request_use: None,
464            delegation_token: None,
465            key_derived_subject: Subject::new(format!("service:{service_name}")),
466            jwt_subject: None,
467            cnf: [0u8; 32],
468            envelope_wit_hash: None,
469            client_dh_public: None,
470            client_kem_public: None,
471            request_iat: 0,
472            request_nonce: [0; 16],
473            response_kem_recipient: None,
474            service_domain: None,
475            envelope_proof_cwt: None,
476            original_holder_evidence: None,
477            browser_method_discriminator: None,
478            internal_work: None,
479            // Internal self-call that never crosses a network boundary (#328).
480            is_local_caller: true,
481        }
482    }
483
484    /// Compare the sealed client method commitment with the discriminator
485    /// independently decoded by generated service dispatch. Legacy carriers
486    /// have no commitment; browser dispatch always installs one.
487    pub fn ensure_browser_method(&self, actual_method_discriminator: u16) -> Result<()> {
488        if let Some(expected) = self.browser_method_discriminator {
489            anyhow::ensure!(
490                expected == actual_method_discriminator,
491                "browser method commitment {expected} does not match decoded service method {actual_method_discriminator}"
492            );
493        }
494        Ok(())
495    }
496
497    /// Construct a test context with specific `cnf` and optional clearance
498    /// claims. **Test-only** — production code uses `from_verified` /
499    /// `from_verified_as_system`.
500    #[cfg(test)]
501    pub(crate) fn for_mac_test(
502        cnf: [u8; 32],
503        clearance: Option<crate::auth::mac::SecurityLabel>,
504    ) -> Self {
505        let claims = clearance.map(|c| {
506            crate::auth::Claims::new("test".to_owned(), 0, 1_000_000_000).with_clearance(c)
507        });
508        Self {
509            request_id: 1,
510            claims,
511            verified_tenant: Some("local".to_owned()),
512            jwt_token: None,
513            direct_jwt_verified: false,
514            delegated_resource_audience: false,
515            deferred_federate: None,
516            federate_tui_class: false,
517            federate_holder_ed: None,
518            federate_request_use: None,
519            delegation_token: None,
520            key_derived_subject: crate::envelope::Subject::anonymous(),
521            jwt_subject: None,
522            cnf,
523            envelope_wit_hash: None,
524            client_dh_public: None,
525            client_kem_public: None,
526            request_iat: 0,
527            request_nonce: [0; 16],
528            response_kem_recipient: None,
529            service_domain: None,
530            envelope_proof_cwt: None,
531            original_holder_evidence: None,
532            browser_method_discriminator: None,
533            internal_work: None,
534            is_local_caller: false,
535        }
536    }
537
538    /// Get the cryptographically-verified authorization subject.
539    ///
540    /// Resolution order:
541    /// 1. Key-derived subject (from verified Ed25519 signer key via `KeyRegistry`).
542    ///    For FixedSigner/inproc callers this is always `Subject::new("system")`.
543    /// 2. JWT upgrade: if the envelope carries a verified JWT token, use its subject.
544    ///    Federated JWTs (`iss` non-empty) produce `Subject::federated(iss, sub)`.
545    /// 3. `Subject::anonymous()` — no verified identity.
546    ///
547    /// The caller-asserted envelope authorization is not preserved in the
548    /// context — only verified state is available to handlers.
549    pub fn subject(&self) -> Subject {
550        // Prefer key-derived subject (cryptographically proven via signer key)
551        if !self.key_derived_subject.is_anonymous() {
552            return self.key_derived_subject.clone();
553        }
554        // JWT upgrade: use the pre-resolved subject set by verify_claims(), which
555        // correctly distinguishes local tokens (bare sub) from federated ones
556        // (iss:sub format).  Falls back to anonymous if no JWT was verified.
557        if let Some(ref s) = self.jwt_subject {
558            return s.clone();
559        }
560        Subject::anonymous()
561    }
562
563    /// Derive the Casbin request domain from the verified tenant binding.
564    ///
565    /// For network callers this comes only from a JWT after `verify_claims()`
566    /// verifies its signature and issuer. Trusted in-process constructors bind
567    /// their callers to the local tenant. The subject name is deliberately not
568    /// a fallback: multiple subjects may share a tenant, and identities without
569    /// a tenant binding must fail closed.
570    pub fn domain(&self) -> Result<String> {
571        let tenant = self
572            .verified_tenant
573            .as_deref()
574            .ok_or_else(|| anyhow::anyhow!("authorization denied: no verified tenant domain"))?;
575        anyhow::ensure!(
576            !tenant.trim().is_empty() && tenant != "*",
577            "authorization denied: empty or wildcard tenant domain"
578        );
579        Ok(tenant.to_owned())
580    }
581
582    /// Return the authority-verified tenant binding, if the request has one.
583    ///
584    /// Callers must still use [`Self::domain`] before treating this value as a
585    /// Casbin domain: that accessor rejects empty and wildcard tenant claims.
586    /// This optional view lets cross-tenant authorities distinguish a missing
587    /// tenant (where an authenticated service principal may use the global
588    /// policy domain) from a present-but-invalid tenant (which must fail
589    /// closed).
590    #[must_use]
591    pub fn verified_tenant(&self) -> Option<&str> {
592        self.verified_tenant.as_deref()
593    }
594
595    /// Get the bare username string.
596    pub fn user(&self) -> &str {
597        // Resolution order mirrors subject(): prefer key-derived, then JWT, then anonymous.
598        if !self.key_derived_subject.is_anonymous() {
599            return self.key_derived_subject.name().unwrap_or("anonymous");
600        }
601        if let Some(ref s) = self.jwt_subject {
602            return s.name().unwrap_or("anonymous");
603        }
604        "anonymous"
605    }
606
607    /// Check if the identity is authenticated (not anonymous).
608    pub fn is_authenticated(&self) -> bool {
609        !self.subject().is_anonymous()
610    }
611
612    /// Return the verified Ed25519 signer key for this authenticated request.
613    ///
614    /// This is the authentication-bound key material for the subject returned
615    /// by [`Self::subject`].  For JWT callers, `verify_claims()` requires the
616    /// JWT confirmation key to match `cnf` before the context reaches a
617    /// handler.  For key-resolved callers, the subject is resolved from this
618    /// same verified key.  Callback contexts have no envelope signer and are
619    /// deliberately refused.
620    #[must_use]
621    pub fn authenticated_signer_key(&self) -> Option<ed25519_dalek::VerifyingKey> {
622        let ed = self.federate_holder_ed.unwrap_or(self.cnf);
623        if !self.is_authenticated() || ed == [0u8; 32] {
624            return None;
625        }
626        ed25519_dalek::VerifyingKey::from_bytes(&ed).ok()
627    }
628
629    /// Return this request's self-certifying pairwise DID.
630    ///
631    /// This is deliberately distinct from [`Self::subject`]. The latter is a
632    /// Casbin-facing authorization label (for example `"alice"` or
633    /// `"https://issuer:alice"`); it is not a decentralized identifier and
634    /// must never be relabelled as one. The pairwise DID is derived only from
635    /// the Ed25519 key whose possession the verified envelope established.
636    /// Callback contexts and anonymous requests have no such identity.
637    #[must_use]
638    pub fn authenticated_pairwise_did(&self) -> Option<crate::identity::Did> {
639        let signer = self.authenticated_signer_key()?;
640        Some(crate::identity::Did::from_ed25519(&signer.to_bytes()))
641    }
642
643    /// Return the trusted PQ key anchored to this request's verified signer.
644    ///
645    /// A missing binding is represented as `None` because Classical transport
646    /// authentication is a valid, lower-assurance state; the returned key is
647    /// never taken from request data.
648    #[must_use]
649    pub fn authenticated_pq_signer_key(&self) -> Option<crate::crypto::pq::MlDsaVerifyingKey> {
650        self.authenticated_signer_key()?;
651        #[cfg(not(target_arch = "wasm32"))]
652        {
653            crate::envelope::global_pq_store().and_then(|store| store.ml_dsa_key_for(&self.cnf))
654        }
655        #[cfg(target_arch = "wasm32")]
656        {
657            None
658        }
659    }
660
661    /// Build an authenticated context fixture for downstream integration tests.
662    ///
663    /// This is intentionally absent from production builds: production contexts
664    /// are created only after envelope verification.
665    #[cfg(any(test, feature = "test-classical-policy"))]
666    pub fn for_test_authenticated_subject(
667        subject: Subject,
668        signer: ed25519_dalek::VerifyingKey,
669    ) -> Self {
670        Self {
671            request_id: 0,
672            claims: None,
673            verified_tenant: None,
674            jwt_token: None,
675            direct_jwt_verified: false,
676            delegated_resource_audience: false,
677            deferred_federate: None,
678            federate_tui_class: false,
679            federate_holder_ed: None,
680            federate_request_use: None,
681            delegation_token: None,
682            key_derived_subject: subject,
683            jwt_subject: None,
684            cnf: signer.to_bytes(),
685            envelope_wit_hash: None,
686            client_dh_public: None,
687            client_kem_public: None,
688            request_iat: 0,
689            request_nonce: [0; 16],
690            response_kem_recipient: None,
691            service_domain: None,
692            envelope_proof_cwt: None,
693            original_holder_evidence: None,
694            browser_method_discriminator: None,
695            internal_work: None,
696            is_local_caller: false,
697        }
698    }
699
700    /// Build an authenticated context fixture with an authority-bound tenant.
701    #[cfg(any(test, feature = "test-classical-policy"))]
702    pub fn for_test_authenticated_subject_in_tenant(
703        subject: Subject,
704        tenant: impl Into<String>,
705        signer: ed25519_dalek::VerifyingKey,
706    ) -> Self {
707        let mut context = Self::for_test_authenticated_subject(subject, signer);
708        context.verified_tenant = Some(tenant.into());
709        context
710    }
711
712    /// Build an authenticated, tenant-bound context fixture that also carries
713    /// verified `claims` — for exercising handlers that read `ctx.claims()`
714    /// (e.g. a service credential's `workload_session_id` on renewal).
715    #[cfg(any(test, feature = "test-classical-policy"))]
716    pub fn for_test_authenticated_subject_with_claims(
717        subject: Subject,
718        tenant: impl Into<String>,
719        signer: ed25519_dalek::VerifyingKey,
720        claims: crate::auth::Claims,
721    ) -> Self {
722        let mut context = Self::for_test_authenticated_subject_in_tenant(subject, tenant, signer);
723        context.claims = Some(claims);
724        context
725    }
726
727    /// Get user claims (if present, after verify_claims has run).
728    pub fn claims(&self) -> Option<&crate::auth::Claims> {
729        self.claims.as_ref()
730    }
731
732    /// **Derive the verified key material (S8/#574, S1/#548).** This is the
733    /// accessor that threads crypto-derived assurance from the envelope's
734    /// verified signature into MAC context assembly.
735    ///
736    /// Returns the [`VerifiedKeyMaterial`] assurance axis for THIS verified
737    /// envelope, derived (never trusted) from what the signature layer actually
738    /// verified:
739    ///
740    /// - **`PqHybrid`** — the envelope's `cnf` Ed25519 signer key is
741    ///   cryptographically verified (it is `self.cnf`, set during
742    ///   [`Self::from_verified`] from the signature check) AND a bound ML-DSA-65
743    ///   anchor for that identity is present in the global `PqTrustStore`
744    ///   (`register_pq_trust` binding) under the enforced Hybrid policy. This is
745    ///   the kid-anchored binding the rest of the TCB uses — the PQ key is
746    ///   resolved from the trust store keyed by the EdDSA identity, never
747    ///   self-asserted.
748    ///   A session-overlay binding also reaches `PqHybrid`, but **only** when it
749    ///   has been confirmed out of band; a first-contact binding is capped at
750    ///   `Classical` by
751    ///   [`crate::session_pq_overlay::PqProvenance::key_material`].
752    /// - **`Classical`** — the `cnf` Ed25519 signer key is verified but NO bound
753    ///   ML-DSA-65 anchor is present (the federation edge, or a pre-PQ
754    ///   identity), or the only binding is a first-contact one, which makes the
755    ///   signature checkable without making the signer more trusted.
756    /// - **`Unverified`** — the `cnf` key is zeroed (a callback-service context
757    ///   with no real envelope; assurance floors to the S1 `Unverified` floor
758    ///   so it dominates nothing above it).
759    ///
760    /// **Re-derive per verified envelope; never cache across identities.** Each
761    /// envelope has its own signer; caching would conflate assurances.
762    ///
763    /// This is the load-bearing S8 input: without it every subject floors to
764    /// `Unverified` and dominates nothing (S6 would deny everything). The MAC
765    /// PDP combines this with the clearance off `Claims` via
766    /// [`crate::auth::mac::SubjectContextClaims::security_context`].
767    #[must_use]
768    pub fn verified_key_material(&self) -> crate::auth::mac::VerifiedKeyMaterial {
769        // A completed Federate request proved the original holder's hybrid
770        // suite. The envelope signer may be a relay: its key must not supply
771        // the caller's MAC assurance or subject-keyed identity.
772        if self.federate_holder_ed.is_some() {
773            return crate::auth::mac::VerifiedKeyMaterial::PqHybrid;
774        }
775        // The callback-service path mints a context with a zeroed cnf and no
776        // real envelope — there is no signature to derive assurance from. Floor
777        // to Unverified so the S1 dominance check denies anything above the
778        // floor (this is the correct posture for an un-attested service self-
779        // call that crosses into MAC-enforced territory).
780        if self.cnf == [0u8; 32] {
781            return crate::auth::mac::VerifiedKeyMaterial::Unverified;
782        }
783        // cnf is the cryptographically-verified Ed25519 signer key (set during
784        // from_verified* from the envelope signature check). It is verified by
785        // construction — the only question is whether a PQ anchor is bound.
786        #[cfg(not(target_arch = "wasm32"))]
787        {
788            if let Some(store) = crate::envelope::global_pq_store() {
789                if store.ml_dsa_key_for(&self.cnf).is_some() {
790                    return crate::auth::mac::VerifiedKeyMaterial::PqHybrid;
791                }
792            }
793            // A session overlay binding makes the signature checkable; whether
794            // it makes the signer more believed is a separate question, and
795            // `PqProvenance::key_material` is the only place it is answered. A
796            // first-contact binding maps to Classical there — the overlay lets
797            // the request in, it does not promote the requester.
798            if let Some(overlay) = crate::session_pq_overlay::global_session_pq_overlay() {
799                if let Some(provenance) = overlay.provenance_for(&self.cnf) {
800                    return provenance.key_material();
801                }
802            }
803        }
804        // Verified Ed25519, no bound PQ anchor ⇒ Classical (the federation edge
805        // / pre-PQ identity). NOT PqHybrid — no silent upgrade.
806        crate::auth::mac::VerifiedKeyMaterial::Classical
807    }
808
809    /// Derive the full MAC [`SecurityContext`] for this verified envelope: the
810    /// **two-input** S1 derivation (clearance from `Claims` + assurance from
811    /// [`Self::verified_key_material`]). This is the convenience entry-point the
812    /// MAC PDP / S6 grant path call; it composes the authority-asserted
813    /// clearance with the crypto-derived assurance, clamping the assurance axis
814    /// DOWN to what the verified key supports.
815    ///
816    /// Returns `None` (→ S1 deny) when the subject carries no clearance
817    /// (unlabeled subject) — there is no default clearance. The resulting
818    /// context is a SIBLING to [`Subject`]: identity and clearance are
819    /// independent dimensions of the same verified principal.
820    ///
821    /// **Re-derive per verified envelope; never cache across identities.**
822    #[must_use]
823    pub fn security_context(&self) -> Option<crate::auth::mac::SecurityContext> {
824        use crate::auth::mac::SubjectContextClaims as _;
825        let claims = self.claims.as_ref()?;
826        let key_material = self.verified_key_material();
827        claims.security_context(key_material)
828    }
829
830    /// Get the effective verified JWT token from the envelope.
831    ///
832    /// For an authorized relay this is the delegated bearer, allowing a
833    /// downstream service to preserve the original user's verified identity
834    /// across another local service boundary.
835    /// Whether the verified credential is of the Federate TUI client class
836    /// (set by `verify_claims`; never caller-supplied).
837    pub fn is_federate_tui_class(&self) -> bool {
838        self.federate_tui_class
839    }
840
841    /// Whether this request's identity came from a delegated bearer token
842    /// (an authenticated service mediator presented the holder's token).
843    pub fn is_delegated_bearer(&self) -> bool {
844        self.jwt_token.is_none() && self.delegation_token.is_some()
845    }
846
847    pub fn has_delegated_resource_audience(&self) -> bool {
848        self.delegated_resource_audience
849    }
850
851    pub fn jwt_token(&self) -> Option<&str> {
852        self.jwt_token
853            .as_deref()
854            .or(self.delegation_token.as_deref())
855    }
856
857    /// A direct network credential only after the full verifier returned
858    /// successfully. Never substitutes a relayed bearer, legacy claims,
859    /// local callback identity, or a partially checked JWT. The returned
860    /// claims remain evidence, not a dispatch permit.
861    pub fn verified_direct_jwt(&self) -> Option<(&crate::auth::Claims, &str)> {
862        if !self.direct_jwt_verified
863            || self.is_local_caller
864            || self.delegation_token.is_some()
865            || self.internal_work.is_some()
866        {
867            return None;
868        }
869        Some((self.claims.as_ref()?, self.jwt_token.as_deref()?))
870    }
871
872    /// Signature-verified reserved credential awaiting dynamic holder proof,
873    /// current session and Policy request-use admission. This is evidence only;
874    /// `subject()`, `domain()` and `claims()` remain unpublished meanwhile.
875    pub fn deferred_federate_credential(&self) -> Option<(&crate::auth::Claims, &str)> {
876        let (claims, _) = self.deferred_federate.as_ref()?;
877        Some((claims, self.jwt_token.as_deref()?))
878    }
879
880    /// Original verified-envelope proof bytes, still untrusted until the
881    /// appropriate signer-suite verifier authenticates them.
882    pub fn request_proof_cwt(&self) -> Option<&[u8]> {
883        self.envelope_proof_cwt.as_deref()
884    }
885
886    pub(crate) fn commit_deferred_federate(
887        &mut self,
888        verified: &crate::proof::verify::VerifiedProof,
889        holder_ed: [u8; 32],
890        resource: String,
891        operation: String,
892    ) -> anyhow::Result<()> {
893        let (claims, subject) = self
894            .deferred_federate
895            .take()
896            .ok_or_else(|| anyhow::anyhow!("no deferred Federate credential"))?;
897        anyhow::ensure!(
898            holder_ed != [0; 32]
899                && claims.cnf_key_bytes() == Some(holder_ed)
900                && verified.primary_principal.as_deref() == Some(claims.sub.as_str())
901                && verified.primary_suite == "hs-cose-sign-ed25519-mldsa65-wns-v1"
902                && subject.name() == Some(claims.sub.as_str())
903                && claims
904                    .tenant
905                    .as_deref()
906                    .is_some_and(|tenant| !tenant.is_empty() && tenant != "*")
907                && !resource.is_empty()
908                && !operation.is_empty(),
909            "Federate holder/subject/profile mismatch"
910        );
911        self.verified_tenant = claims.tenant.clone();
912        self.jwt_subject = Some(subject);
913        self.claims = Some(claims);
914        self.federate_holder_ed = Some(holder_ed);
915        self.federate_request_use = Some((resource, operation));
916        // This is not the ordinary cnf-to-envelope direct JWT provenance;
917        // keep `verified_direct_jwt()` unavailable to downstream consumers.
918        Ok(())
919    }
920
921    /// Exact request-local Policy-use coordinate, never a reusable permit.
922    /// A serving handler must compare every generated authorization call with
923    /// this tuple and perform its ordinary fresh Policy check as well.
924    pub fn admitted_federate_operation(&self, resource: &str, operation: &str) -> bool {
925        self.federate_request_use
926            .as_ref()
927            .is_some_and(|(r, a)| r == resource && a == operation)
928    }
929
930    pub fn is_federate_admitted(&self) -> bool {
931        self.federate_request_use.is_some()
932    }
933
934    /// Check if request has user context
935    pub fn has_user_context(&self) -> bool {
936        self.claims.is_some()
937    }
938
939    /// The verified internal execution work order, when this request crossed a
940    /// pinned single-service execution boundary (Model → its Inference
941    /// subprocessor). `None` for every direct caller; a service MUST treat its
942    /// presence as "the controller already authorized this exact operation" —
943    /// never as bearer delegation.
944    #[must_use]
945    pub fn internal_work(&self) -> Option<&crate::auth::internal_work::InternalWorkContext> {
946        self.internal_work.as_ref()
947    }
948
949    /// Get the client's ephemeral DH public key (if present).
950    /// Used by streaming handlers to derive shared secrets for HMAC chain keys.
951    pub fn ephemeral_pubkey(&self) -> Option<[u8; 32]> {
952        self.client_dh_public
953    }
954
955    /// Get the authenticated identified-stream HyKEM recipient.
956    pub fn stream_kem_recipient(&self) -> Option<&crate::crypto::hybrid_kem::RecipientPublic> {
957        self.client_kem_public.as_ref()
958    }
959
960    /// The one-shot unary reply recipient authenticated by the envelope.
961    /// Deferred Federate admission additionally requires the original holder
962    /// proof to bind this value before any handler or authority side effect.
963    pub fn response_kem_recipient(&self) -> Option<&crate::crypto::hybrid_kem::RecipientPublic> {
964        self.response_kem_recipient.as_ref()
965    }
966
967    /// Whether this request came from a genuine in-process / IPC caller (#328).
968    ///
969    /// `true` for the `FixedSigner` mutual-auth plane and internal self-calls;
970    /// `false` for networked / mesh peers (`AnySigner`). Used to confine the
971    /// empty-`iss` JWT shortcut to local callers.
972    pub fn is_local_caller(&self) -> bool {
973        self.is_local_caller
974    }
975
976    /// Emit an accounting / audit record for an authorization decision (#445).
977    ///
978    /// This is the **Accounting** leg of AAA: it makes every authorization
979    /// decision attributable after the fact to the *cryptographically verified*
980    /// subject (`self.subject()`), never a caller-asserted field. It is called
981    /// by generated dispatch code at the authorization decision point — the
982    /// single DRY chokepoint where the verified subject, the resource, the
983    /// operation, and the allow/deny effect are all in scope.
984    ///
985    /// The record is a structured `tracing` event on the dedicated `audit`
986    /// target so it can be filtered/routed independently (e.g. shipped to an
987    /// audit sink) without coupling to the rest of the daemon's logs. Fields:
988    /// `subject`, `resource`, `action`, `decision` (`allow`/`deny`), and
989    /// `request_id` for correlation. It records only identity + resource +
990    /// action + decision — never key material or request payloads.
991    ///
992    /// Allow is logged at `info`; deny at `warn` (deny is the security-relevant
993    /// event), but both carry identical structured fields so "who did what" is
994    /// reconstructable for the allow path AND the deny path.
995    ///
996    /// **S7 (#573, #453):** this is the *control-plane* (Casbin `#[authorize]`)
997    /// audit surface. The *data-plane* MAC surface (the AVC) emits its own
998    /// records on the same unified `hyprstream.mac.audit` target via
999    /// `hyprstream::mac::audit`. Both targets fan out to OpenTelemetry when the
1000    /// `otel` feature is active (OTel is a `tracing` subscriber), so denials
1001    /// are first-class observable signals — closing the #453 visibility gap
1002    /// where auth failures were previously buried at `debug` level. We also
1003    /// mirror the decision onto `hyprstream.mac.audit` here so a single OTel
1004    /// subscriber captures the whole authorization audit stream.
1005    pub fn audit_authz(&self, resource: &str, operation: &str, allowed: bool) {
1006        let subject = self.subject();
1007        let decision = if allowed { "allow" } else { "deny" };
1008        if allowed {
1009            tracing::info!(
1010                target: "audit",
1011                subject = %subject,
1012                resource = %resource,
1013                action = %operation,
1014                decision = decision,
1015                request_id = self.request_id,
1016                "authz decision"
1017            );
1018        } else {
1019            tracing::warn!(
1020                target: "audit",
1021                subject = %subject,
1022                resource = %resource,
1023                action = %operation,
1024                decision = decision,
1025                request_id = self.request_id,
1026                "authz decision"
1027            );
1028        }
1029        // S7 (#453): mirror onto the unified MAC audit target so a single OTel
1030        // subscriber captures every authorization decision (control-plane
1031        // Casbin + data-plane MAC AVC). Denials become first-class observable,
1032        // no longer buried at debug level.
1033        if allowed {
1034            tracing::info!(
1035                target: "hyprstream.mac.audit",
1036                decision = decision,
1037                subject = %subject,
1038                resource = %resource,
1039                action = %operation,
1040                request_id = self.request_id,
1041                plane = "control",
1042                "authorization decision"
1043            );
1044        } else {
1045            tracing::warn!(
1046                target: "hyprstream.mac.audit",
1047                decision = decision,
1048                subject = %subject,
1049                resource = %resource,
1050                action = %operation,
1051                request_id = self.request_id,
1052                plane = "control",
1053                "authorization decision"
1054            );
1055        }
1056    }
1057}
1058
1059/// Trait for RPC services.
1060///
1061/// This is the unified trait for services that:
1062/// 1. Handle requests via `handle_request()`
1063/// 2. Are automatically spawnable (blanket `impl Spawnable for S: RequestService`)
1064#[async_trait(?Send)]
1065pub trait RequestService: 'static {
1066    /// Process a request and return a response with optional continuation.
1067    ///
1068    /// # Arguments
1069    ///
1070    /// * `ctx` - Verified envelope context with identity
1071    /// * `body` - The request body decoded exactly once by
1072    ///   [`RequestService::decode_request_body`] (v16 §5.2). Generated
1073    ///   dispatch reads the typed request from [`DecodedRequestBody::root`]
1074    ///   — the same decoded message whose derived leaf fed the generated
1075    ///   method policy and the dispatch MAC PEP — never from a second decode
1076    ///   of the bytes.
1077    ///
1078    /// Returns `(response_bytes, optional_continuation)`:
1079    /// - `response_bytes`: Cap'n Proto encoded response sent as REP
1080    /// - `continuation`: Optional future spawned AFTER the REP is sent
1081    ///   (used for streaming: ensures client has stream_id before data flows)
1082    ///
1083    /// Non-streaming services always return `None` for the continuation.
1084    async fn handle_request(
1085        &self,
1086        ctx: &EnvelopeContext,
1087        body: &crate::service::DecodedRequestBody,
1088    ) -> Result<(Vec<u8>, Option<Continuation>)>;
1089
1090    /// Decode the signed request body **exactly once** (bounded) and derive
1091    /// the full numeric method leaf path (v16 §5.2 step 4).
1092    ///
1093    /// The returned [`DecodedRequestBody`] is the one decode for the entire
1094    /// request lifetime: its leaf path keys the generated method policy and
1095    /// the dispatch MAC PEP, and its decoded message is what
1096    /// [`RequestService::handle_request`] dispatches from. The leaf comes
1097    /// from the signed body — never from a transport-specific hint such as
1098    /// the browser transcript's method commitment, which does not exist on
1099    /// other carriers and is not the signed leaf.
1100    ///
1101    /// This method is **required** — there is deliberately no default. A
1102    /// schema-generated service delegates to its generated
1103    /// `decode_<service>_request_body` function; a service with no Cap'n
1104    /// Proto request schema must affirmatively construct
1105    /// [`DecodedRequestBody::opaque`], which denies proof-bearing dispatch at
1106    /// leaf derivation instead of silently passing a policy row it never
1107    /// resolved.
1108    ///
1109    /// An unknown discriminant, a malformed body, or a body exceeding the
1110    /// reviewed decode caps is an error — the same denial as an unlisted
1111    /// leaf, never a coarser fallback.
1112    fn decode_request_body(&self, signed_body: &[u8])
1113        -> Result<crate::service::DecodedRequestBody>;
1114
1115    /// Service name (for logging and registry).
1116    fn name(&self) -> &str;
1117
1118    /// Transport configuration (endpoint binding).
1119    fn transport(&self) -> &TransportConfig;
1120
1121    /// Ed25519 signing key for signing responses.
1122    fn signing_key(&self) -> SigningKey;
1123
1124    /// Mutable reach source filled by the unified service spawner after the
1125    /// service's QUIC and iroh listeners bind.
1126    fn producer_reach_config_handle(&self) -> Option<crate::moq_stream::ProducerReachConfigHandle> {
1127        None
1128    }
1129
1130    /// Optional per-service MoQ origin source. The unified spawner installs a
1131    /// scoped origin here when this service has a relay configured.
1132    fn moq_origin_handle(&self) -> Option<crate::moq_stream::MoqStreamOriginHandle> {
1133        None
1134    }
1135
1136    /// ML-DSA-65 signing key for the post-quantum half of the response COSE
1137    /// composite (#275). Returning `None` makes `process_request` fail closed
1138    /// before dispatch; it never selects an EdDSA-only response. The matching ML-DSA-65 public key
1139    /// must be anchored in the client's PQ trust store for Hybrid verification
1140    /// to succeed (peer attestation).
1141    ///
1142    /// The default derives the node's **persistent** mesh ML-DSA-65 key
1143    /// deterministically from this service's Ed25519 [`Self::signing_key`] via
1144    /// [`crate::node_identity::derive_mesh_mldsa_key`] (#157). Because the EdDSA
1145    /// half of the response is signed with that same Ed25519 key (dispatch is
1146    /// handed `service.signing_key()`), the kid-anchored binding the client
1147    /// stores — Ed25519 signer pubkey → ML-DSA vk — is self-consistent, and the
1148    /// published `#mesh-pq` DID verification method equals this signing key.
1149    ///
1150    /// Mirrors the request-side mandatory pinned suite.
1151    fn pq_signing_key(&self) -> Option<crate::crypto::pq::MlDsaSigningKey> {
1152        Some(crate::node_identity::derive_mesh_mldsa_key(
1153            &self.signing_key(),
1154        ))
1155    }
1156
1157    /// Ed25519 verifying key for envelope signature verification.
1158    fn verifying_key(&self) -> VerifyingKey {
1159        self.signing_key().verifying_key()
1160    }
1161
1162    /// JWT key source for token verification.
1163    ///
1164    /// Returns the key source used to verify JWT signatures. Services must
1165    /// provide this to enable JWT verification. Returns `None` by default,
1166    /// which means JWT verification is skipped (anonymous access only).
1167    ///
1168    /// Most services should return a `ClusterKeySource` that trusts the
1169    /// cluster's CA key. PolicyService may return a `FederatedKeySource`
1170    /// for cross-cluster token exchange.
1171    fn jwt_key_source(&self) -> Option<std::sync::Arc<dyn crate::auth::JwtKeySource>> {
1172        None
1173    }
1174
1175    /// Expected audience (resource URL) for JWT validation.
1176    ///
1177    /// When `Some`, `verify_claims()` rejects tokens whose `aud` claim doesn't match.
1178    /// Override this on services that should bind tokens to a specific resource.
1179    fn expected_audience(&self) -> Option<&str> {
1180        None
1181    }
1182
1183    /// Select an exact, configured audience for an already-admitted delegated
1184    /// user bearer. The unverified claim is only a selector: implementations
1185    /// must return their own configured string, never a borrowed token value.
1186    /// Direct and service credentials always use `expected_audience` instead.
1187    fn delegated_user_audience(
1188        &self,
1189        _signer_pubkey: &[u8; 32],
1190        _untrusted_aud: Option<&str>,
1191    ) -> Option<&str> {
1192        self.expected_audience()
1193    }
1194
1195    /// Admit a non-native resource bearer only for a decoded signed request
1196    /// leaf. Default denial preserves every service's native issuer boundary.
1197    fn accept_delegated_resource_leaf(
1198        &self,
1199        _ctx: &EnvelopeContext,
1200        _body: &crate::service::DecodedRequestBody,
1201    ) -> bool {
1202        false
1203    }
1204
1205    /// Whether to reject JWTs that lack a `cnf` key binding (jwk or jkt).
1206    ///
1207    /// When `true`, `verify_claims()` will reject any JWT that does not carry
1208    /// a `cnf` confirmation key, ensuring every authenticated request is
1209    /// cryptographically bound to its envelope signer.
1210    ///
1211    /// Default is `true` — override to `false` only for services that
1212    /// intentionally accept unbound JWTs (e.g., legacy compatibility).
1213    fn require_cnf_binding(&self) -> bool {
1214        true
1215    }
1216
1217    /// Credential revocation store for access token revocation.
1218    ///
1219    /// Returns the process-global store published at startup: the durable
1220    /// authority store in the policy process, or a policy-authority RPC
1221    /// client store in every other process (checks cross the RPC bus to the
1222    /// policy service, the one canonical revocation authority). When `None`
1223    /// (startup not yet complete or authority initialization failed),
1224    /// `verify_claims()` rejects tokens with a jti (fail-closed). Override
1225    /// only for specialized testing.
1226    fn credential_revocation_store(&self) -> Option<&dyn crate::auth::CredentialRevocationStore> {
1227        crate::auth::global_credential_revocation_store().map(std::convert::AsRef::as_ref)
1228    }
1229
1230    /// Fu4/#677: the minimum JWT `alg` policy enforced in `verify_claims`.
1231    ///
1232    /// Under [`CryptoPolicy::Hybrid`] a classical-only (`EdDSA`) JWT is rejected
1233    /// outright, independent of JWKS `kid_algs` hygiene. The default reads the
1234    /// process-global envelope verify config (Hybrid in production), so the
1235    /// per-call policy is test-isolated from sibling tests that mutate the
1236    /// shared global.
1237    fn jwt_verify_policy(&self) -> crate::crypto::CryptoPolicy {
1238        #[cfg(not(target_arch = "wasm32"))]
1239        {
1240            crate::envelope::global_verify_policy()
1241        }
1242        #[cfg(target_arch = "wasm32")]
1243        {
1244            crate::crypto::CryptoPolicy::Hybrid
1245        }
1246    }
1247
1248    /// Resolve a verified signer key to an authorization subject (#446).
1249    ///
1250    /// Consulted by `verify_claims` for an unauthenticated (no-JWT) request: the
1251    /// envelope `cnf` (the signer's Ed25519 pubkey, already verified by the COSE
1252    /// signature check) is mapped to its authoritative subject so a *signed*
1253    /// service-to-service IPC caller resolves as its `service:<name>` identity
1254    /// instead of `anonymous`.
1255    ///
1256    /// The default routes through the process-global [key→subject
1257    /// resolver](crate::auth::key_subject_resolver), which the trust-store layer
1258    /// (`hyprstream-service`, populated fail-closed under #441) installs at
1259    /// startup. This wires *every* service — including those whose crate cannot
1260    /// depend on the trust store (e.g. `DiscoveryService`) — without each one
1261    /// re-implementing the lookup.
1262    ///
1263    /// Fail-closed: an unregistered key resolves to `None` → `anonymous`, so a
1264    /// genuinely anonymous caller stays denied for policy-gated writes. Override
1265    /// only to bypass or narrow this resolution; never to fabricate identity.
1266    #[cfg(not(target_arch = "wasm32"))]
1267    fn resolve_key_subject(&self, signer_pubkey: &[u8; 32]) -> Option<crate::envelope::Subject> {
1268        crate::auth::key_subject_resolver::resolve_subject(signer_pubkey)
1269    }
1270
1271    /// Resolve a signer key to a subject (WASM: no trust store available).
1272    #[cfg(target_arch = "wasm32")]
1273    fn resolve_key_subject(&self, _signer_pubkey: &[u8; 32]) -> Option<crate::envelope::Subject> {
1274        None
1275    }
1276
1277    /// Cache a verified key→subject binding in the trust store.
1278    ///
1279    /// Called after successful JWT verification when the JWT's `pub_key` matches
1280    /// the envelope signer. Default implementation is a no-op.
1281    fn cache_key_binding(
1282        &self,
1283        _verifying_key: ed25519_dalek::VerifyingKey,
1284        _subject: &str,
1285        _jwt: &str,
1286        _expires_at: i64,
1287    ) {
1288    }
1289
1290    /// Accept a relayed bearer from this verified envelope signer. Services
1291    /// enabling this must pin an independently configured controller key.
1292    fn accept_delegated_bearer(&self, _signer_pubkey: &[u8; 32]) -> bool {
1293        false
1294    }
1295
1296    /// Opt in only when this serving instance has a complete request-local
1297    /// holder-proof, current-primary and durable Policy-use adapter. Default
1298    /// false preserves the generic verifier's reserved-profile denial.
1299    fn accept_deferred_federate_credential(&self) -> bool {
1300        false
1301    }
1302
1303    /// Verify the original holder's proof and bind it to the exact decoded
1304    /// body/leaf/resource/action before identity publication. This stage must
1305    /// not consume replay state: generated method-policy and MAC authorization
1306    /// still run afterward. Durable Policy admission happens in
1307    /// `commit_deferred_federate_request` only after those gates pass.
1308    async fn admit_deferred_federate_request(
1309        &self,
1310        _ctx: &EnvelopeContext,
1311        _body: &crate::service::DecodedRequestBody,
1312        _proof: &crate::proof::parser::ParsedProof,
1313    ) -> anyhow::Result<(
1314        crate::proof::verify::VerifiedProof,
1315        [u8; 32],
1316        String,
1317        String,
1318        crate::proof::admission::ProofReplayKey,
1319        u64,
1320    )> {
1321        anyhow::bail!("Federate request admission is disabled")
1322    }
1323
1324    /// Perform fresh Policy admission and durable replay consumption after the
1325    /// generated method-policy and mandatory MAC gates, immediately before
1326    /// handler dispatch. Implementations must fail closed if the durable
1327    /// admission service is unavailable. The default never admits a request.
1328    async fn commit_deferred_federate_request(
1329        &self,
1330        _ctx: &EnvelopeContext,
1331        _resource: &str,
1332        _operation: &str,
1333        _replay_key: &crate::proof::admission::ProofReplayKey,
1334        _replay_expiry: u64,
1335    ) -> anyhow::Result<()> {
1336        anyhow::bail!("Federate durable request admission is disabled")
1337    }
1338
1339    /// Verify an `iw+jwt` internal execution work order presented as the
1340    /// direct JWT (single-service Model→Inference boundary, user-approved D5).
1341    ///
1342    /// The generic pipeline rejects this token type at EVERY service by
1343    /// default; only a service operating a pinned execution boundary overrides
1344    /// this hook. The override must authenticate the token against the PINNED
1345    /// controller key and bind it to the exact instance/tenant/model/operation
1346    /// admitted. On `Ok` the pipeline installs the original-caller identity
1347    /// (subject, tenant, claims snapshot) and the
1348    /// [`InternalWorkContext`](crate::auth::internal_work::InternalWorkContext)
1349    /// on the context; the work order is never a bearer anywhere else.
1350    async fn verify_internal_work_bearer(
1351        &self,
1352        _ctx: &EnvelopeContext,
1353        _token: &str,
1354        _protected: &crate::auth::ProtectedHeader,
1355    ) -> anyhow::Result<crate::auth::internal_work::InternalWorkClaims> {
1356        anyhow::bail!("internal work bearer is not accepted by this service")
1357    }
1358
1359    /// E2E JWT verification with unified key source.
1360    ///
1361    /// Called by `process_request` after envelope signature verification.
1362    /// Takes `&mut EnvelopeContext` to store the resolved `jwt_subject` directly,
1363    /// which correctly distinguishes local tokens (bare `sub`) from federated
1364    /// ones (`iss:sub` format) using the key source's `local_issuers()`.
1365    /// Async because federated key resolution may require an HTTP JWKS fetch.
1366    ///
1367    /// Prefers `jwt_token` (opaque token string) over legacy `claims` field.
1368    /// When `jwt_token` is present, the server decodes and verifies it directly.
1369    /// The legacy `claims` path is kept for backwards compat with older clients.
1370    async fn verify_claims(&self, ctx: &mut EnvelopeContext) -> anyhow::Result<()> {
1371        // Prefer jwt_token (new path) over legacy claims
1372        let direct_token = ctx
1373            .jwt_token
1374            .clone()
1375            .or_else(|| ctx.claims().and_then(|c| c.token.clone()));
1376        let delegated = direct_token.is_none() && ctx.delegation_token.is_some();
1377        let token = match direct_token {
1378            Some(token) => Some(token),
1379            None => match ctx.delegation_token.clone() {
1380                Some(token) => {
1381                    anyhow::ensure!(
1382                        self.accept_delegated_bearer(&ctx.cnf),
1383                        "delegated bearer rejected: envelope signer is not an authorized relay"
1384                    );
1385                    Some(token)
1386                }
1387                None => None,
1388            },
1389        };
1390
1391        let Some(token) = token else {
1392            // No JWT — try trust store lookup for cached key bindings
1393            if let Some(subject) = self.resolve_key_subject(&ctx.cnf) {
1394                if subject.name() == Some(UNAUTHENTICATED_DID_SENTINEL) {
1395                    tracing::warn!(
1396                        "Ignored reserved unauthenticated subject from signer-key resolver"
1397                    );
1398                    return Ok(());
1399                }
1400                ctx.key_derived_subject = subject;
1401                return Ok(());
1402            }
1403            // No JWT and no trust store entry — subject stays anonymous
1404            return Ok(());
1405        };
1406
1407        // Parse the protected JOSE header once with duplicate detection. All
1408        // dispatch and primitive verification below consumes this exact value.
1409        let protected = crate::auth::parse_protected_header(&token)
1410            .map_err(|e| anyhow::anyhow!("JWT header parse failed: {}", e))?;
1411
1412        // Internal execution work order (single-service Model→Inference
1413        // boundary). Routed to the per-service hook BEFORE the CA key source
1414        // and the generic credential grammar: the hook verifies against the
1415        // PINNED controller key (never the CA source), and its DEFAULT denies —
1416        // so only a service that explicitly operates a pinned execution
1417        // boundary can admit this type, and every other service fails closed
1418        // here (and again at its own grammar below for any unknown typ). Never
1419        // treated as delegation.
1420        if protected.typ == crate::auth::internal_work::INTERNAL_WORK_JWT_TYP {
1421            let work = self
1422                .verify_internal_work_bearer(ctx, &token, &protected)
1423                .await?;
1424            // Sol S1 (MED): work.sub is the ALREADY-RESOLVED subject string
1425            // that Model verified at ingress (`ctx.subject().to_string()`).
1426            // Install the typed subject from that exact string — NEVER
1427            // re-normalize through the legacy `Subject::from_str`, which
1428            // strips `local:`/`token:`/`peer:`/`user:` prefixes and silently
1429            // changes the principal (cross-principal subject-keyed TTT state
1430            // and mis-audit at the worker). Do not apply `Subject::validate`
1431            // here either: it rejects `:` for legitimate service subjects and
1432            // federated subjects have their own grammar.
1433            anyhow::ensure!(
1434                !work.sub.is_empty(),
1435                "internal work bearer subject is empty"
1436            );
1437            anyhow::ensure!(
1438                work.sub != "anonymous",
1439                "internal work bearer subject is the anonymous marker"
1440            );
1441            anyhow::ensure!(
1442                work.sub != UNAUTHENTICATED_DID_SENTINEL,
1443                "internal work bearer subject is the reserved unauthenticated sentinel"
1444            );
1445            let subject = crate::envelope::Subject::new(&work.sub);
1446            // The installed typed identity must round-trip to the exact
1447            // verified string (newtype Display is the string itself).
1448            anyhow::ensure!(
1449                subject.to_string() == work.sub,
1450                "internal work bearer subject installation is not exact"
1451            );
1452            // Snapshot/subject coherence (K3 finding m1): the pinned
1453            // controller authored both fields; require them to agree so
1454            // audit and subject-keyed state are provably consistent.
1455            anyhow::ensure!(
1456                work.caller.sub == work.sub,
1457                "internal work caller snapshot subject disagrees with the work-order subject"
1458            );
1459            let caller = work.caller.clone();
1460            ctx.verified_tenant = Some(work.tenant.clone());
1461            ctx.claims = Some(caller);
1462            ctx.jwt_subject = Some(subject.clone());
1463            ctx.internal_work = Some(crate::auth::internal_work::InternalWorkContext {
1464                subject,
1465                owner_did: work.owner_did.clone(),
1466                resource: work.resource.clone(),
1467                operation: work.operation.clone(),
1468                tenant: work.tenant.clone(),
1469                model: work.model.clone(),
1470                jti: work.jti.clone(),
1471            });
1472            tracing::info!(
1473                target: "audit",
1474                subject = %ctx.subject(),
1475                resource = %work.resource,
1476                action = %work.operation,
1477                decision = "allow",
1478                request_id = ctx.request_id,
1479                via = "model-internal-work",
1480                "internal work admission"
1481            );
1482            return Ok(());
1483        }
1484
1485        // Get key source — if not configured, JWT verification is disabled
1486        let key_source = match self.jwt_key_source() {
1487            Some(ks) => ks,
1488            None => {
1489                tracing::warn!(
1490                    service = self.name(),
1491                    "JWT present but jwt_key_source() not configured — rejecting"
1492                );
1493                anyhow::bail!("JWT verification not configured for this service");
1494            }
1495        };
1496
1497        // Decode the JWT to get claims for issuer routing
1498        let unverified = crate::auth::decode_unverified(&token)
1499            .map_err(|e| anyhow::anyhow!("JWT decode failed: {}", e))?;
1500
1501        // Empty-`iss` gate (#328): an empty issuer denotes the local
1502        // PolicyService's bare-`sub` token, which the key sources treat as
1503        // "always local/trusted". That is only safe for genuine in-process /
1504        // IPC callers (the FixedSigner plane). A networked / mesh peer
1505        // (AnySigner) presenting an empty-`iss` token would otherwise inherit
1506        // local trust — reject it fail-closed; mesh peers must present an
1507        // explicit issuer (or authenticate via the key roster, no JWT).
1508        if unverified.iss.is_empty() && !ctx.is_local_caller {
1509            tracing::warn!(
1510                service = self.name(),
1511                "rejecting empty-iss JWT from a networked caller (empty issuer is in-process only) (#328)"
1512            );
1513            anyhow::bail!("empty JWT issuer is only accepted from in-process callers");
1514        }
1515
1516        anyhow::ensure!(
1517            crate::auth::is_rfc9068_access_token_type(&protected.typ) || protected.typ == "wit+jwt",
1518            "unsupported JWT typ"
1519        );
1520        let kid = Some(protected.kid.clone());
1521
1522        // Check if issuer is trusted
1523        if !key_source.is_trusted(&unverified.iss) {
1524            tracing::warn!(
1525                "JWT from untrusted issuer rejected (iss={})",
1526                unverified.iss
1527            );
1528            anyhow::bail!("JWT issuer not trusted: {}", unverified.iss);
1529        }
1530
1531        // A delegated interactive bearer may select only a receiver-configured
1532        // resource audience. A WIT/service credential and every direct JWT keep
1533        // the native expected audience. The hook sees an unverified selector,
1534        // but the selected configured audience is passed into each signature
1535        // decoder below and must match the signed token exactly.
1536        let expected_audience = if delegated
1537            && crate::auth::is_rfc9068_access_token_type(&protected.typ)
1538            && !unverified.sub.starts_with("service:")
1539        {
1540            let selected = self.delegated_user_audience(&ctx.cnf, unverified.aud.as_deref());
1541            anyhow::ensure!(
1542                self.expected_audience().is_none() || selected.is_some(),
1543                "delegated user audience selection cannot disable the native audience"
1544            );
1545            selected
1546        } else {
1547            self.expected_audience()
1548        };
1549        ctx.delegated_resource_audience = delegated
1550            && expected_audience.is_some()
1551            && expected_audience != self.expected_audience();
1552        if ctx.delegated_resource_audience {
1553            anyhow::ensure!(
1554                unverified.aud.as_deref() == expected_audience,
1555                "delegated resource token must name its exact selected audience"
1556            );
1557        }
1558        let alg = protected.alg.clone();
1559
1560        // ── Stripping defense (composite signature hardening) ───────────────
1561        //
1562        // If the JWKS lists this kid with one or more `alg` values, the JWT's
1563        // header alg MUST exactly match a JWKS alg, AND when the JWKS lists
1564        // multiple algs for this kid, the JWT MUST use a composite alg that
1565        // covers all of them. This prevents an attacker from stripping the
1566        // post-quantum half of a composite signature and presenting only the
1567        // classical EdDSA half under the composite kid.
1568        if let Some(ref kid_str) = kid {
1569            let listed_algs = key_source.kid_algs(&unverified.iss, kid_str);
1570            if !listed_algs.is_empty() {
1571                if !listed_algs.iter().any(|a| a == &alg) {
1572                    tracing::warn!(
1573                        "JWT alg={} not listed in JWKS for kid={} (listed: {:?}) — possible stripping attack",
1574                        alg, kid_str, listed_algs
1575                    );
1576                    anyhow::bail!("JWT alg does not match JWKS for kid (stripping defense)");
1577                }
1578                // When the JWKS lists multiple algs for the kid (e.g. a
1579                // composite-signature publication that names both halves),
1580                // require ALL of them — i.e. require a composite alg whose
1581                // covered components include every listed alg.
1582                if listed_algs.len() > 1 {
1583                    let covered = composite_alg_components(&alg);
1584                    let all_covered = listed_algs
1585                        .iter()
1586                        .all(|need| covered.iter().any(|c| c == need) || need == &alg);
1587                    if !all_covered {
1588                        tracing::warn!(
1589                            "JWT alg={} does not cover all JWKS-listed algs {:?} for kid={} — stripping rejected",
1590                            alg, listed_algs, kid_str
1591                        );
1592                        anyhow::bail!(
1593                            "JWT alg does not cover all JWKS-listed algs (stripping defense)"
1594                        );
1595                    }
1596                }
1597            }
1598        }
1599
1600        // ── Fu4/#677: CryptoPolicy-driven minimum-alg gate ───────────────────
1601        //
1602        // Independent of the JWKS `kid_algs` hygiene below: under a Hybrid
1603        // policy a classical-only (EdDSA) JWT is rejected outright, before
1604        // per-alg routing, so anti-stripping no longer depends on every key
1605        // source populating `kid_algs` (the default impl is empty and
1606        // `ClusterKeySource` never overrides it). The policy comes from
1607        // `jwt_verify_policy` (the global config in production, overridable per
1608        // service for tests).
1609        jwt_alg_satisfies_policy(self.jwt_verify_policy(), &alg)?;
1610
1611        // Route verification by algorithm
1612        let mut verified = match alg.as_str() {
1613            "ML-DSA-65" => {
1614                let vks = key_source.ml_dsa_verifying_keys();
1615                if vks.is_empty() {
1616                    anyhow::bail!("ML-DSA-65 JWT received but no PQ verifying keys available");
1617                }
1618                let aud = expected_audience;
1619                let mut last_err = None;
1620                let mut result = None;
1621                for vk in &vks {
1622                    match crate::auth::jwt::decode_ml_dsa_65(&token, vk, aud) {
1623                        Ok(claims) => {
1624                            result = Some(claims);
1625                            break;
1626                        }
1627                        Err(e) => {
1628                            last_err = Some(e);
1629                        }
1630                    }
1631                }
1632                match result {
1633                    Some(claims) => claims,
1634                    None => {
1635                        tracing::warn!(
1636                            "ML-DSA-65 JWT verification failed (tried {} keys): {:?}",
1637                            vks.len(),
1638                            last_err
1639                        );
1640                        anyhow::bail!("JWT verification failed");
1641                    }
1642                }
1643            }
1644            "ML-DSA-65-Ed25519" => {
1645                if !unverified.iss.is_empty()
1646                    && !key_source
1647                        .local_issuers()
1648                        .iter()
1649                        .any(|issuer| issuer == &unverified.iss)
1650                {
1651                    anyhow::bail!("local composite JWT issuer mismatch");
1652                }
1653                let allowed_types = [
1654                    crate::auth::RFC9068_ACCESS_TOKEN_TYPES[0],
1655                    crate::auth::RFC9068_ACCESS_TOKEN_TYPES[1],
1656                    "wit+jwt",
1657                ];
1658                let dispatch = crate::auth::parse_composite_dispatch(&token, &allowed_types)
1659                    .map_err(|error| anyhow::anyhow!("JWT dispatch failed: {error}"))?;
1660                // Role note: pairs of BOTH issuer roles are acceptable at this
1661                // layer — the OAuth pair signs browser access tokens and
1662                // browser/workload WITs, the Policy pair signs PolicyService-
1663                // issued tokens including service WITs — because this is
1664                // transport authentication only. Handlers whose decisions
1665                // confer signing-domain privileges (e.g. service-key
1666                // certification, announcements) must additionally constrain
1667                // the resolved pair's role themselves.
1668                let pair = key_source
1669                    .composite_pair(dispatch.kid())
1670                    .ok_or_else(|| anyhow::anyhow!("unknown composite JWT kid"))?;
1671                crate::auth::jwt::decode_composite(
1672                    &token,
1673                    pair.ml_dsa(),
1674                    pair.ed25519(),
1675                    expected_audience,
1676                    &dispatch,
1677                )
1678                .map_err(|error| {
1679                    tracing::warn!("composite JWT verification failed: {error}");
1680                    anyhow::anyhow!("JWT verification failed")
1681                })?
1682            }
1683            "EdDSA" => {
1684                let verified = if let Some(kid) = kid.as_deref() {
1685                    let verifying_key = key_source
1686                        .get_key(&unverified.iss, Some(kid))
1687                        .await
1688                        .map_err(|e| {
1689                            tracing::warn!(
1690                                "JWT key resolution failed for iss={} kid={}: {}",
1691                                unverified.iss,
1692                                kid,
1693                                e
1694                            );
1695                            anyhow::anyhow!("JWT key resolution failed")
1696                        })?;
1697                    crate::auth::decode_with_key(&token, &verifying_key, expected_audience)
1698                } else {
1699                    let candidates =
1700                        key_source
1701                            .get_keys(&unverified.iss, None)
1702                            .await
1703                            .map_err(|e| {
1704                                tracing::warn!(
1705                                    "JWT key resolution failed for kid-less iss={}: {}",
1706                                    unverified.iss,
1707                                    e
1708                                );
1709                                anyhow::anyhow!("JWT key resolution failed")
1710                            })?;
1711                    crate::auth::decode_with_any_key_lenient(&token, &candidates, expected_audience)
1712                };
1713                verified.map_err(|e| {
1714                    tracing::warn!("JWT verification failed: {}", e);
1715                    anyhow::anyhow!("JWT verification failed")
1716                })?
1717            }
1718            _ => anyhow::bail!("unsupported JWT algorithm"),
1719        };
1720
1721        // Some native decoders permit a missing aud for compatibility. The
1722        // external delegated-resource path never does, even under those
1723        // algorithms; compare the signed result as well as the selector.
1724        if ctx.delegated_resource_audience {
1725            anyhow::ensure!(
1726                verified.aud.as_deref() == expected_audience,
1727                "verified delegated resource audience mismatch"
1728            );
1729        }
1730        // The selector was unverified. Never let a signed service credential
1731        // take an external resource audience even if an ambiguous pre-decode
1732        // representation appeared to describe a user.
1733        anyhow::ensure!(
1734            !ctx.delegated_resource_audience || !verified.sub.starts_with("service:"),
1735            "delegated resource audience requires a user credential"
1736        );
1737
1738        // Federate's browser proof key is intentionally distinct from the
1739        // envelope/relay key. Reserved credentials use the signed signer
1740        // inventory digest, not a server-side session generation. Reject
1741        // malformed or mixed profiles here before publishing identity or
1742        // caching a key binding; the serving adapter still verifies holder
1743        // proof, shared replay, and fresh Policy authority before dispatch.
1744        let reserved_federate = self
1745            .expected_audience()
1746            .is_some_and(|host| verified.is_reserved_federate_credential(host))
1747            || key_source
1748                .local_issuers()
1749                .iter()
1750                .any(|host| verified.is_reserved_federate_credential(host));
1751        if verified.has_federate_profile_marker() || reserved_federate {
1752            let inventory = verified.federate_signer_inventory()?;
1753            let session_generation = verified.session_authority_generation()?;
1754            anyhow::ensure!(
1755                self.accept_deferred_federate_credential()
1756                    && matches!(self.name(), "registry" | "model")
1757                    && reserved_federate
1758                    && self
1759                        .expected_audience()
1760                        .is_some_and(|host| { verified.is_reserved_federate_credential(host) })
1761                    && verified.aud.as_deref() == self.expected_audience()
1762                    && self.expected_audience().is_some_and(|host| {
1763                        crate::auth::claims::FederateHost::new(host).is_ok()
1764                    })
1765                    && verified.hs_profile.as_deref() == Some("federate-session-v1")
1766                    && inventory.is_some_and(|value| value != [0; 32])
1767                    && session_generation.is_none()
1768                    && protected.typ == "at+jwt"
1769                    && !ctx.is_local_caller
1770                    && !delegated
1771                    && ctx.delegation_token.is_none()
1772                    && ctx.jwt_token.as_deref() == Some(token.as_str())
1773                    && verified.jti.as_deref().is_some_and(|id| !id.is_empty()),
1774                "Federate session dispatch is disabled or malformed"
1775            );
1776            let local = key_source.local_issuers();
1777            let local_refs: Vec<&str> = local.iter().map(String::as_str).collect();
1778            anyhow::ensure!(
1779                crate::auth::is_local_iss(&verified.iss, &local_refs),
1780                "Federate host issuer is not local"
1781            );
1782            let jti = verified
1783                .jti
1784                .as_deref()
1785                .ok_or_else(|| anyhow::anyhow!("missing Federate jti"))?;
1786            let revocations = self
1787                .credential_revocation_store()
1788                .ok_or_else(|| anyhow::anyhow!("Federate revocation authority unavailable"))?;
1789            anyhow::ensure!(
1790                !revocations
1791                    .is_revoked(&crate::auth::CredentialId::jwt(&verified.iss, jti))
1792                    .await,
1793                "Federate credential revoked"
1794            );
1795            if let Some(expected) = ctx.envelope_wit_hash {
1796                use sha2::{Digest, Sha256};
1797                use subtle::ConstantTimeEq as _;
1798                let actual: [u8; 32] = Sha256::digest(token.as_bytes()).into();
1799                anyhow::ensure!(bool::from(expected.ct_eq(&actual)), "Federate wth mismatch");
1800            }
1801            let subject = verified.subject(&local_refs);
1802            anyhow::ensure!(
1803                !subject.is_federated() && subject.name() == Some(verified.sub.as_str()),
1804                "Federate subject is not local"
1805            );
1806            // No subject, tenant, claims or key cache is published. The
1807            // dispatcher must complete original-holder proof + Policy use.
1808            ctx.deferred_federate = Some((verified, subject));
1809            return Ok(());
1810        }
1811
1812        // Credential/session checks. The local-issuer set is resolved first:
1813        // the credential profile makes `jti` REQUIRED on locally issued
1814        // tokens, and the session registry is a local authority — both
1815        // enforcements below apply to local issuers. Federated tokens keep
1816        // the revocation check only (their sessions are not local state).
1817        let local_issuers = key_source.local_issuers();
1818        let local_issuers_refs: Vec<&str> = local_issuers.iter().map(String::as_str).collect();
1819        let token_is_local = crate::auth::is_local_iss(&verified.iss, &local_issuers_refs);
1820
1821        // W1.3: classify Federate TUI-class credentials — marker set, or the
1822        // authority-owned class pin (deployment-configured client id at a
1823        // local issuer). This flag is routing metadata only; ENFORCEMENT
1824        // happens at dispatch (dispatch.rs fences classified credentials to
1825        // the tui service and policy's read-only delegated check) and at the
1826        // TUI consumer gate. Verification itself must stay class-blind here:
1827        // this method also runs for evidence verification (e.g. Policy
1828        // verifying a mediated holder), which is not dispatch.
1829        ctx.federate_tui_class = verified.is_federate_tui_class(&local_issuers_refs);
1830
1831        // v16 §3.1/§3.3: issuer-scoped credential and session enforcement
1832        // applies only to tokens carrying a real authoritative issuer. An
1833        // empty `iss` is the in-process provenance sentinel — accepted solely
1834        // from in-process callers (gated above where an empty issuer from a
1835        // networked caller is rejected) and never issuer-scoped: a
1836        // `CredentialId` requires a non-empty issuer by construction (§3.1), so
1837        // an empty-iss token has no revocable credential identity and no
1838        // issuer namespace to scope a session to. The `jti` that `jwt::encode`
1839        // auto-injects is then an encoding artifact, not a credential —
1840        // running it through the issuer-scoped gate would build an invalid
1841        // `CredentialId`, fail closed, and reject a legitimate in-process
1842        // caller. `is_local_iss` deliberately reports empty-iss as local, so
1843        // the credential gate must additionally require a non-empty issuer.
1844        let issuer_scoped = !verified.iss.is_empty();
1845
1846        // A locally issued token with a real issuer must carry a jti:
1847        // revocation could never observe it otherwise. Reject rather than
1848        // skipping the check. Empty-iss in-process provenance is exempt (no
1849        // issuer to scope the credential to).
1850        if token_is_local && issuer_scoped && verified.jti.is_none() {
1851            tracing::warn!(iss = %verified.iss, sub = %verified.sub, "Rejected local-issuer JWT without jti");
1852            anyhow::bail!("local credential missing required jti");
1853        }
1854
1855        // Check credential against the revocation store (revoked access
1856        // tokens). Only issuer-scoped tokens (non-empty issuer) have a valid
1857        // `CredentialId`; empty-iss in-process provenance carries no revocable
1858        // credential identity and is exempt.
1859        if let Some(jti) = verified.jti.as_ref().filter(|_| issuer_scoped) {
1860            match self.credential_revocation_store() {
1861                Some(store) => {
1862                    let cred_id = crate::auth::CredentialId::jwt(&verified.iss, jti);
1863                    if store.is_revoked(&cred_id).await {
1864                        tracing::warn!(jti = %jti, iss = %verified.iss, sub = %verified.sub, "Revoked JWT rejected");
1865                        anyhow::bail!("JWT has been revoked");
1866                    }
1867                }
1868                None => {
1869                    // Fail-closed: a token carrying a jti cannot be verified
1870                    // for revocation without a store. Reject rather than
1871                    // admitting a potentially-revoked credential.
1872                    tracing::warn!(jti = %jti, sub = %verified.sub, "Token with jti rejected: no revocation store configured");
1873                    anyhow::bail!("revocation store unavailable");
1874                }
1875            }
1876        }
1877
1878        // Session check (v16 §3.3): a local token carrying a session ID is
1879        // rejected when the session is revoked, expired, unknown, or cannot
1880        // be checked. Only issuer-scoped local tokens participate — an
1881        // empty-iss in-process token has no issuer namespace to scope a
1882        // session to (a `SessionKey` requires a non-empty issuer).
1883        if token_is_local && issuer_scoped {
1884            // Exact-one session parsing (v16 §3.3): both-present or empty
1885            // session identifiers are malformed and reject here, before any
1886            // authorization or cache insertion.
1887            let session_key = match verified.session_key() {
1888                Ok(key) => key,
1889                Err(e) => {
1890                    tracing::warn!(iss = %verified.iss, sub = %verified.sub, error = %e, "Rejected JWT with malformed session claims");
1891                    anyhow::bail!("malformed session claims");
1892                }
1893            };
1894            if let Some(session_key) = session_key {
1895                match crate::auth::global_session_registry() {
1896                    Some(registry) => {
1897                        if registry.is_revoked(&session_key).await {
1898                            tracing::warn!(iss = %verified.iss, sub = %verified.sub, "JWT with revoked/unknown session rejected");
1899                            anyhow::bail!("session has been revoked");
1900                        }
1901                    }
1902                    None => {
1903                        tracing::warn!(sub = %verified.sub, "Token with session id rejected: no session registry configured");
1904                        anyhow::bail!("session registry unavailable");
1905                    }
1906                }
1907            }
1908        }
1909
1910        // RFC 9068 §2.2.1 (v16 credential profile): an issuer-scoped `at+jwt`
1911        // credential MUST carry a non-empty `client_id`. Positively typed on
1912        // the already-exact-validated JOSE `typ` (parsed once above): a
1913        // `wit+jwt` service credential is exempt (it carries no client_id), and
1914        // empty-iss in-process provenance is exempt (`issuer_scoped` is false).
1915        // This covers EVERY accepted `at+jwt` — local AND trusted
1916        // federated/delegated — not merely local ones; `token_is_local` is
1917        // deliberately NOT part of the predicate.
1918        if issuer_scoped
1919            && crate::auth::is_rfc9068_access_token_type(&protected.typ)
1920            && verified
1921                .client_id
1922                .as_deref()
1923                .is_none_or(|c| c.trim().is_empty())
1924        {
1925            tracing::warn!(iss = %verified.iss, sub = %verified.sub, typ = %protected.typ, "Rejected at+jwt without client_id");
1926            anyhow::bail!("at+jwt credential missing required client_id");
1927        }
1928
1929        // Service credentials are also published as verification-key
1930        // attestations. Possession of one therefore cannot authorize a relay
1931        // to impersonate its holder, even when that relay may forward users.
1932        // Keep this before publishing any authenticated identity on context.
1933        if delegated && verified.sub.starts_with("service:") {
1934            use subtle::ConstantTimeEq as _;
1935            let holder_matches = if let Some(expected) = verified.cnf_key_bytes() {
1936                bool::from(expected.ct_eq(&ctx.cnf))
1937            } else if let Some(jkt) = verified.cnf_jkt() {
1938                let signer_jkt =
1939                    crate::auth::jwk_thumbprint(&crate::auth::JwkThumbprintInput::Ed25519 {
1940                        x: &ctx.cnf,
1941                    });
1942                bool::from(signer_jkt.as_bytes().ct_eq(jkt.as_bytes()))
1943            } else {
1944                false
1945            };
1946            anyhow::ensure!(
1947                holder_matches,
1948                "delegated service credential requires its bound holder signer"
1949            );
1950        }
1951
1952        // Store verified claims on context for downstream use
1953        if verified.sub == UNAUTHENTICATED_DID_SENTINEL {
1954            tracing::warn!("Rejected JWT whose subject is the reserved unauthenticated sentinel");
1955            anyhow::bail!(
1956                "{UNAUTHENTICATED_DID_SENTINEL} is credential absence and cannot authenticate"
1957            );
1958        }
1959        // Fu5/#677: MAC clearance is authority-asserted and honored only from
1960        // local-issuer tokens. An external OIDC issuer trusted for identity is
1961        // not trusted to assert MAC clearance on this node — strip the claim
1962        // from any federated token before the MAC PDP can read it (⇒ unlabeled
1963        // ⇒ deny). Local-issuer tokens are unaffected.
1964        verified.strip_federated_clearance(&local_issuers_refs);
1965        // Tenant domains are likewise local authority assertions. A federated
1966        // issuer trusted for identity cannot select a local Casbin domain.
1967        verified.strip_federated_tenant(&local_issuers_refs);
1968        let s = verified.subject(&local_issuers_refs);
1969        if !s.is_anonymous() {
1970            ctx.jwt_subject = Some(s);
1971        }
1972        ctx.verified_tenant = verified.tenant.clone();
1973        ctx.claims = Some(verified.clone());
1974
1975        // R2: Bind JWT cnf.jwk claim to envelope signer (WIMSE WIT key binding).
1976        // When a JWT carries a cnf.jwk (Ed25519 pubkey), the envelope signer must
1977        // match. Prevents a valid JWT holder from signing envelopes with a different
1978        // key and being attributed the JWT's subject identity. A pinned relay is
1979        // the sole exception: it already verified that binding at ingress, and
1980        // the downstream envelope is necessarily signed by the relay instead.
1981        // Do not cache a bearer-to-relay binding on this path.
1982        if !delegated {
1983            if let Some(ref claims) = ctx.claims {
1984                if let Some(expected) = claims.cnf_key_bytes() {
1985                    use subtle::ConstantTimeEq as _;
1986                    if expected.ct_ne(&ctx.cnf).into() {
1987                        tracing::warn!("JWT cnf.jwk mismatch: sub={}", claims.sub);
1988                        anyhow::bail!("JWT cnf.jwk does not match envelope signer");
1989                    }
1990
1991                    // Cache the (key → subject) binding in the trust store.
1992                    let vk = match ed25519_dalek::VerifyingKey::from_bytes(&expected) {
1993                        Ok(vk) => vk,
1994                        Err(_) => {
1995                            tracing::warn!("Invalid Ed25519 verifying key in JWT cnf.jwk");
1996                            anyhow::bail!("Invalid Ed25519 verifying key in JWT cnf.jwk");
1997                        }
1998                    };
1999                    let subject_str = claims.subject(&local_issuers_refs);
2000                    if let Some(subject_name) = subject_str.name() {
2001                        if subject_name != UNAUTHENTICATED_DID_SENTINEL {
2002                            self.cache_key_binding(vk, subject_name, &token, claims.exp);
2003                            tracing::info!(subject = %subject_name, "Cached key binding in trust store");
2004                        }
2005                    }
2006                } else if let Some(jkt) = claims.cnf_jkt() {
2007                    // R2b: DPoP path — JWT has cnf.jkt (thumbprint) instead of cnf.jwk.
2008                    // Compute the JWK thumbprint of the envelope signer and compare.
2009                    use subtle::ConstantTimeEq as _;
2010                    let envelope_jkt =
2011                        crate::auth::jwk_thumbprint(&crate::auth::JwkThumbprintInput::Ed25519 {
2012                            x: &ctx.cnf,
2013                        });
2014                    if envelope_jkt.as_bytes().ct_ne(jkt.as_bytes()).into() {
2015                        tracing::warn!("JWT cnf.jkt mismatch: sub={}", claims.sub);
2016                        anyhow::bail!("JWT cnf.jkt does not match envelope signer");
2017                    }
2018
2019                    let vk = match ed25519_dalek::VerifyingKey::from_bytes(&ctx.cnf) {
2020                        Ok(vk) => vk,
2021                        Err(_) => {
2022                            tracing::warn!("Invalid Ed25519 verifying key in envelope cnf");
2023                            anyhow::bail!("Invalid Ed25519 verifying key in envelope cnf");
2024                        }
2025                    };
2026                    let subject_str = claims.subject(&local_issuers_refs);
2027                    if let Some(subject_name) = subject_str.name() {
2028                        if subject_name != UNAUTHENTICATED_DID_SENTINEL {
2029                            self.cache_key_binding(vk, subject_name, &token, claims.exp);
2030                            tracing::info!(subject = %subject_name, "Cached key binding from cnf.jkt");
2031                        }
2032                    }
2033                } else if self.require_cnf_binding() {
2034                    tracing::warn!("JWT missing cnf binding (jwk or jkt): sub={}", claims.sub);
2035                    anyhow::bail!(
2036                        "JWT must include cnf binding for key binding (required by this service)"
2037                    );
2038                }
2039            }
2040        }
2041
2042        // R3: Verify WIMSE wth binding — envelope proof is committed to a specific WIT.
2043        // If the envelope carries a witHash, it must match SHA-256(jwtToken we just verified).
2044        if let Some(ref claimed_hash) = ctx.envelope_wit_hash {
2045            use sha2::{Digest, Sha256};
2046            use subtle::ConstantTimeEq as _;
2047            let expected: [u8; 32] = Sha256::digest(token.as_bytes()).into();
2048            if expected.ct_ne(claimed_hash.as_slice()).into() {
2049                tracing::warn!("witHash mismatch — possible rotation-window replay");
2050                anyhow::bail!("witHash does not match WIT — possible rotation-window replay");
2051            }
2052        }
2053
2054        ctx.direct_jwt_verified = !delegated && ctx.jwt_token.is_some();
2055        Ok(())
2056    }
2057
2058    /// Build a generic error response payload for unexpected errors.
2059    ///
2060    /// Default implementation returns an empty vec (backwards compat).
2061    /// Generated services should override with schema-correct error payloads
2062    /// so clients receive proper `Error(ErrorInfo{...})` instead of parse failures.
2063    fn build_error_payload(&self, request_id: u64, error: &str) -> Vec<u8> {
2064        warn!(
2065            service = self.name(),
2066            request_id, error, "build_error_payload not overridden — sending empty error response"
2067        );
2068        vec![]
2069    }
2070}
2071
2072/// REQ/REP message loop for RequestService.
2073///
2074/// Runs the REQ/REP message loop as an async task with TMQ for I/O.
2075/// Uses proper async/await with epoll integration instead of blocking threads.
2076///
2077/// # Envelope Verification
2078///
2079/// The loop unwraps and verifies `SignedEnvelope` for every request:
2080/// 1. Deserialize `SignedEnvelope` from wire bytes
2081/// 2. Verify Ed25519 signature against server's public key
2082/// 3. Check nonce not replayed (replay protection)
2083/// 4. Extract `EnvelopeContext` and dispatch to handler
2084///
2085/// Invalid/unsigned requests are rejected with an error response.
2086///
2087/// # Usage
2088///
2089/// QUIC server configuration for the service loop.
2090pub struct QuicLoopConfig {
2091    /// Cancels all announcements owned by this bound service before teardown.
2092    pub announcement_cancellation: tokio_util::sync::CancellationToken,
2093    /// DER-encoded certificate chain (leaf first, then intermediates/CA)
2094    pub cert_chain: Vec<Vec<u8>>,
2095    /// DER-encoded private key — zeroed on drop.
2096    pub key_der: Zeroizing<Vec<u8>>,
2097    /// Address to bind the WebTransport server
2098    pub bind_addr: std::net::SocketAddr,
2099    /// TLS server name (for endpoint discovery registration)
2100    pub server_name: String,
2101    /// Pre-serialized RFC 9728 JSON for HTTP/3 `.well-known/oauth-protected-resource`
2102    pub protected_resource_json: Option<Vec<u8>>,
2103    /// Callback invoked after QUIC binding succeeds, with (service_name, actual_addr, server_name).
2104    /// Used to announce endpoints to the DiscoveryService.
2105    pub on_quic_bound: Option<Box<dyn FnOnce(String, std::net::SocketAddr, String) + Send>>,
2106    /// #410/#282: when `true` (the default), the spawner binds an `IrohSubstrate`
2107    /// as the PRIMARY production endpoint, serving BOTH ALPNs
2108    /// (`hyprstream-rpc/1` + `moql`) with the same request processor + moq
2109    /// origin, and installs the shared client endpoint for outbound iroh dials.
2110    /// The quinn endpoint is bound in parallel for back-compat. Native-only.
2111    /// Set `false` (via `[quic] iroh = false`) to run quinn-only (legacy).
2112    #[cfg(not(target_arch = "wasm32"))]
2113    pub iroh_enabled: bool,
2114    /// Iroh is a startup/readiness requirement for native traffic. Quinn may
2115    /// still serve the browser edge but cannot satisfy this native contract.
2116    #[cfg(not(target_arch = "wasm32"))]
2117    pub iroh_required: bool,
2118    /// #282: callback invoked after the iroh substrate binds, with
2119    /// (service_name, node_id) where `node_id` is the endpoint's 32-byte Ed25519
2120    /// public carrier address. Used to advertise only an `IrohTransport` service
2121    /// entry when bound; it must never become a verification method.
2122    #[cfg(not(target_arch = "wasm32"))]
2123    pub on_iroh_bound: Option<Box<dyn FnOnce(String, [u8; 32]) -> anyhow::Result<()> + Send>>,
2124    /// #358: the producer-chosen moq RELAY this node rendezvouses through, in
2125    /// wire-reach form ([`crate::stream_info::TransportConfig`]). When set, the
2126    /// spawner places it in the service's `ProducerReachConfig` (so published
2127    /// streams advertise a `Role::Relay` reach) and links this node's
2128    /// streaming origin UP to the relay
2129    /// ([`crate::moq_stream::serve_origin_to_relay_background`]) — restoring the
2130    /// rendezvous property: neither publisher nor subscriber need be directly
2131    /// reachable by the other. Sourced from the resolved relay DID transport entry
2132    /// (default: the PDS / federation anchor) decoded by the shared
2133    /// [`crate::service_entry`] codec, so the stream relay and DID addresses never
2134    /// drift. `None` = direct-only (the S1/S2 behaviour). Native-only.
2135    #[cfg(not(target_arch = "wasm32"))]
2136    pub moq_relay: Option<crate::stream_info::TransportConfig>,
2137    /// Resolver-verified accepted-state witness for `moq_relay`. Iroh relay
2138    /// links require this distinct remote identity for mutual admission.
2139    #[cfg(not(target_arch = "wasm32"))]
2140    pub moq_relay_server_identity: Option<crate::stream_info::MoqlServerIdentity>,
2141    /// #1027: optional inside-carrier admission authenticator for the iroh
2142    /// `moql` accept path. When set, every accepted `moql` connection must
2143    /// prove an accepted current Ed25519 + ML-DSA-65 identity (fresh
2144    /// challenge/response binding epoch/head/nonces) before the moq handshake;
2145    /// the admitted peer is served only its resolved tenant's scope. When
2146    /// `None`, the pre-#1027 posture stands: anonymous carriers are refused.
2147    /// Native-only.
2148    #[cfg(not(target_arch = "wasm32"))]
2149    pub moq_admission: Option<Arc<crate::transport::moql_admission::MoqlAdmissionAuthenticator>>,
2150    /// Optional service-owned ingress authorization. The spawner forwards it
2151    /// unchanged to the Iroh MoQL handler; absence is deliberately read-only.
2152    #[cfg(not(target_arch = "wasm32"))]
2153    pub moq_ingress_authorizer: Option<crate::transport::iroh_moq::SharedIngressAuthorizer>,
2154    /// Native client proof for authenticated Iroh `moql` dials in this process.
2155    #[cfg(not(target_arch = "wasm32"))]
2156    pub moq_admission_proof: Option<crate::transport::moql_admission::MoqlAdmissionProof>,
2157}
2158
2159/// Handle for a running service
2160pub struct ServiceHandle {
2161    task: Option<tokio::task::JoinHandle<()>>,
2162    /// Shutdown signal using Notify (clean async shutdown)
2163    shutdown: Option<Arc<Notify>>,
2164}
2165
2166impl ServiceHandle {
2167    /// Create a dummy handle for services that manage their own lifecycle
2168    pub fn dummy() -> Self {
2169        Self {
2170            task: None,
2171            shutdown: None,
2172        }
2173    }
2174
2175    /// Create a handle from an existing task and shutdown signal.
2176    ///
2177    /// Used by ServiceSpawner when spawning Spawnable services.
2178    pub fn from_task(task: tokio::task::JoinHandle<()>, shutdown: Arc<Notify>) -> Self {
2179        Self {
2180            task: Some(task),
2181            shutdown: Some(shutdown),
2182        }
2183    }
2184
2185    /// Stop the service gracefully
2186    ///
2187    /// Idempotent: subsequent calls are no-ops if already stopped.
2188    pub async fn stop(&mut self) {
2189        // Signal shutdown via Notify
2190        if let Some(shutdown) = &self.shutdown {
2191            shutdown.notify_one();
2192        }
2193        // Wait for task to complete
2194        if let Some(task) = self.task.take() {
2195            let _ = task.await;
2196        }
2197    }
2198
2199    /// Check if the service is still running
2200    pub fn is_running(&self) -> bool {
2201        self.task.as_ref().map(|t| !t.is_finished()).unwrap_or(true)
2202    }
2203}
2204
2205#[cfg(test)]
2206#[allow(clippy::expect_used)]
2207mod policy_tenant_domain_tests {
2208    use super::*;
2209    use ed25519_dalek::SigningKey;
2210
2211    #[test]
2212    fn multiple_verified_identities_share_the_claimed_tenant_domain() {
2213        let signer = SigningKey::from_bytes(&[0x44; 32]).verifying_key();
2214        let alice = EnvelopeContext::for_test_authenticated_subject_in_tenant(
2215            Subject::new("alice"),
2216            "tenant-a",
2217            signer,
2218        );
2219        let bob = EnvelopeContext::for_test_authenticated_subject_in_tenant(
2220            Subject::new("bob"),
2221            "tenant-a",
2222            signer,
2223        );
2224
2225        assert_ne!(alice.subject(), bob.subject());
2226        assert_eq!(alice.domain().expect("verified tenant"), "tenant-a");
2227        assert_eq!(bob.domain().expect("verified tenant"), "tenant-a");
2228    }
2229
2230    #[test]
2231    fn missing_wildcard_and_blank_tenant_domains_fail_closed() {
2232        let signer = SigningKey::from_bytes(&[0x45; 32]).verifying_key();
2233        let missing =
2234            EnvelopeContext::for_test_authenticated_subject(Subject::new("alice"), signer);
2235        let wildcard = EnvelopeContext::for_test_authenticated_subject_in_tenant(
2236            Subject::new("alice"),
2237            "*",
2238            signer,
2239        );
2240        let empty = EnvelopeContext::for_test_authenticated_subject_in_tenant(
2241            Subject::new("alice"),
2242            "",
2243            signer,
2244        );
2245        let whitespace = EnvelopeContext::for_test_authenticated_subject_in_tenant(
2246            Subject::new("alice"),
2247            " \t\n",
2248            signer,
2249        );
2250
2251        assert!(missing.domain().is_err());
2252        assert!(wildcard.domain().is_err());
2253        assert!(empty.domain().is_err());
2254        assert!(whitespace.domain().is_err());
2255    }
2256}
2257
2258/// Empty-`iss` transport-gating tests (#328).
2259///
2260/// An empty JWT issuer denotes the local PolicyService's bare-`sub` token, which
2261/// the key sources treat as always-trusted/local. That shortcut is confined to
2262/// genuine in-process / IPC callers (`EnvelopeContext::is_local_caller`); a
2263/// networked / mesh peer presenting an empty-`iss` token is rejected fail-closed.
2264#[cfg(test)]
2265#[allow(clippy::unwrap_used, clippy::expect_used)]
2266mod empty_iss_gate_tests {
2267    use super::*;
2268    use crate::auth::{
2269        Claims, ClusterKeySource, FederatedKeySource, FederationKey, FederationKeySource,
2270    };
2271    use crate::transport::TransportConfig;
2272    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
2273    use ed25519_dalek::{Signer as _, SigningKey};
2274
2275    /// Minimal mock service exposing a `ClusterKeySource` for JWT verification.
2276    /// `require_cnf_binding` is disabled so the empty-`iss` gate is exercised in
2277    /// isolation (without a cnf-binding rejection masking the result).
2278    struct MockService {
2279        signing_key: SigningKey,
2280        transport: TransportConfig,
2281        key_source: std::sync::Arc<dyn crate::auth::JwtKeySource>,
2282        policy: crate::crypto::CryptoPolicy,
2283        relay: Option<[u8; 32]>,
2284        cached_subjects: std::sync::Arc<parking_lot::Mutex<Vec<String>>>,
2285        /// Pinned controller key for `iw+jwt` internal work admission
2286        /// (mirrors the Inference subprocessor adapter shape).
2287        internal_controller: Option<ed25519_dalek::VerifyingKey>,
2288        federate_opt_in: bool,
2289        audience: Option<String>,
2290        relay_resource_audience: Option<String>,
2291        /// Exercise generic fail-closed checking against a faulty override.
2292        unchecked_resource_selector: bool,
2293    }
2294
2295    #[async_trait(?Send)]
2296    impl RequestService for MockService {
2297        async fn handle_request(
2298            &self,
2299            _ctx: &EnvelopeContext,
2300            _body: &crate::service::DecodedRequestBody,
2301        ) -> Result<(Vec<u8>, Option<Continuation>)> {
2302            Ok((vec![], None))
2303        }
2304        fn decode_request_body(
2305            &self,
2306            signed_body: &[u8],
2307        ) -> Result<crate::service::DecodedRequestBody> {
2308            // Byte-oriented mock: no Cap'n Proto schema, no derivable leaf.
2309            Ok(crate::service::DecodedRequestBody::opaque(
2310                signed_body.to_vec(),
2311            ))
2312        }
2313        fn name(&self) -> &str {
2314            if self.federate_opt_in {
2315                "model"
2316            } else {
2317                "mock"
2318            }
2319        }
2320        fn accept_deferred_federate_credential(&self) -> bool {
2321            self.federate_opt_in
2322        }
2323        fn expected_audience(&self) -> Option<&str> {
2324            self.audience.as_deref()
2325        }
2326        fn delegated_user_audience(
2327            &self,
2328            signer_pubkey: &[u8; 32],
2329            untrusted_aud: Option<&str>,
2330        ) -> Option<&str> {
2331            if self.relay.as_ref() == Some(signer_pubkey) {
2332                if let Some(configured) = self.relay_resource_audience.as_deref() {
2333                    if self.unchecked_resource_selector || untrusted_aud == Some(configured) {
2334                        return Some(configured);
2335                    }
2336                }
2337            }
2338            self.expected_audience()
2339        }
2340        fn transport(&self) -> &TransportConfig {
2341            &self.transport
2342        }
2343        fn signing_key(&self) -> SigningKey {
2344            self.signing_key.clone()
2345        }
2346        fn jwt_key_source(&self) -> Option<std::sync::Arc<dyn crate::auth::JwtKeySource>> {
2347            Some(self.key_source.clone())
2348        }
2349        fn credential_revocation_store(
2350            &self,
2351        ) -> Option<&dyn crate::auth::CredentialRevocationStore> {
2352            // Test-local revocation store: these tests verify local
2353            // jti-bearing tokens, and every production process publishes a
2354            // store at startup (the policy-authority bootstrap). Without
2355            // this, verification fails closed on store absence and the tests
2356            // only pass when an unrelated sibling test happens to publish
2357            // the process-global handle first.
2358            static STORE: std::sync::OnceLock<crate::auth::InMemoryCredentialRevocationStore> =
2359                std::sync::OnceLock::new();
2360            Some(STORE.get_or_init(crate::auth::InMemoryCredentialRevocationStore::new))
2361        }
2362        fn require_cnf_binding(&self) -> bool {
2363            false
2364        }
2365        fn pq_signing_key(&self) -> Option<crate::crypto::pq::MlDsaSigningKey> {
2366            None
2367        }
2368        // These tests exercise the empty-ISS / subject-routing gate with
2369        // classical EdDSA tokens; pin the JWT policy to Classical so they are
2370        // isolated from sibling tests that install a Hybrid global config.
2371        fn jwt_verify_policy(&self) -> crate::crypto::CryptoPolicy {
2372            self.policy
2373        }
2374        fn accept_delegated_bearer(&self, signer_pubkey: &[u8; 32]) -> bool {
2375            self.relay.as_ref() == Some(signer_pubkey)
2376        }
2377        async fn verify_internal_work_bearer(
2378            &self,
2379            ctx: &EnvelopeContext,
2380            token: &str,
2381            _protected: &crate::auth::ProtectedHeader,
2382        ) -> anyhow::Result<crate::auth::internal_work::InternalWorkClaims> {
2383            let controller = self.internal_controller.as_ref().ok_or_else(|| {
2384                anyhow::anyhow!("internal work bearer is not accepted by this service")
2385            })?;
2386            anyhow::ensure!(
2387                ctx.cnf == controller.to_bytes(),
2388                "internal work bearer envelope was not signed by the pinned controller"
2389            );
2390            let now = chrono::Utc::now().timestamp();
2391            let claims = crate::auth::internal_work::verify_internal_work(
2392                token,
2393                controller,
2394                "mock-instance-1",
2395                now,
2396            )?;
2397            anyhow::ensure!(
2398                crate::auth::internal_work::admit_internal_work_jti_once(
2399                    &claims.jti,
2400                    claims.exp,
2401                    now,
2402                ),
2403                "internal work token jti was already admitted (replay)"
2404            );
2405            Ok(claims)
2406        }
2407        fn cache_key_binding(
2408            &self,
2409            _verifying_key: ed25519_dalek::VerifyingKey,
2410            subject: &str,
2411            _jwt: &str,
2412            _expires_at: i64,
2413        ) {
2414            self.cached_subjects.lock().push(subject.to_owned());
2415        }
2416    }
2417
2418    /// Build an `EnvelopeContext` carrying `jwt_token`, with the chosen
2419    /// transport provenance.
2420    fn ctx_with_token(token: String, is_local_caller: bool) -> EnvelopeContext {
2421        EnvelopeContext {
2422            request_id: 1,
2423            claims: None,
2424            verified_tenant: None,
2425            jwt_token: Some(token),
2426            direct_jwt_verified: false,
2427            delegated_resource_audience: false,
2428            deferred_federate: None,
2429            federate_tui_class: false,
2430            federate_holder_ed: None,
2431            federate_request_use: None,
2432            delegation_token: None,
2433            key_derived_subject: Subject::anonymous(),
2434            jwt_subject: None,
2435            cnf: [0u8; 32],
2436            envelope_wit_hash: None,
2437            client_dh_public: None,
2438            client_kem_public: None,
2439            request_iat: 0,
2440            request_nonce: [0; 16],
2441            response_kem_recipient: None,
2442            service_domain: None,
2443            envelope_proof_cwt: None,
2444            original_holder_evidence: None,
2445            browser_method_discriminator: None,
2446            internal_work: None,
2447            is_local_caller,
2448        }
2449    }
2450
2451    #[test]
2452    fn deferred_federate_identity_stays_unpublished_until_exact_holder_commit() {
2453        let holder = SigningKey::from_bytes(&[41; 32]).verifying_key().to_bytes();
2454        let relay = SigningKey::from_bytes(&[42; 32]).verifying_key().to_bytes();
2455        let claims = Claims::new("alice".into(), 1, 100)
2456            .with_tenant("tenant-a".into())
2457            .with_scope(Some(
2458                "query:model:qwen2.5-0.5b-instruct query:registry:List".into(),
2459            ))
2460            .with_cnf_jwk(&holder);
2461        let mut ctx = ctx_with_token("signature-verified-token".into(), false);
2462        ctx.cnf = relay;
2463        ctx.deferred_federate = Some((claims, Subject::new("alice")));
2464        assert!(ctx.subject().is_anonymous());
2465        assert!(ctx.claims().is_none());
2466        assert!(ctx.domain().is_err());
2467        assert!(ctx.security_context().is_none());
2468        assert!(ctx.verified_direct_jwt().is_none());
2469        let proof = crate::proof::verify::VerifiedProof {
2470            replay_thumbprint: [1; 32],
2471            primary_principal: Some("alice".into()),
2472            primary_suite: "hs-cose-sign-ed25519-mldsa65-wns-v1".into(),
2473            approvers: vec![],
2474        };
2475        let mut wrong = ctx.clone();
2476        assert!(wrong
2477            .commit_deferred_federate(&proof, relay, "registry:List".into(), "query".into())
2478            .is_err());
2479        assert!(wrong.subject().is_anonymous());
2480        assert!(ctx
2481            .commit_deferred_federate(&proof, holder, "registry:List".into(), "query".into())
2482            .is_ok());
2483        assert_eq!(ctx.subject().name(), Some("alice"));
2484        assert_eq!(ctx.domain().unwrap(), "tenant-a");
2485        assert_eq!(ctx.authenticated_signer_key().unwrap().to_bytes(), holder);
2486        assert_eq!(
2487            ctx.verified_key_material(),
2488            crate::auth::mac::VerifiedKeyMaterial::PqHybrid
2489        );
2490        assert!(ctx.admitted_federate_operation("registry:List", "query"));
2491        assert!(!ctx.admitted_federate_operation("registry:Get", "query"));
2492        assert!(ctx.verified_direct_jwt().is_none());
2493    }
2494
2495    /// `verify_claims` fails closed on jti-bearing, issuer-bearing tokens
2496    /// without the process-global revocation store (`jwt::encode`
2497    /// auto-assigns a jti). Install an in-memory authority when no other test
2498    /// in this binary got there first — under nextest per-test process
2499    /// isolation no other test can provide it.
2500    fn ensure_test_revocation_store() {
2501        if crate::auth::global_credential_revocation_store().is_none() {
2502            let _ = crate::auth::set_global_credential_revocation_store(std::sync::Arc::new(
2503                crate::auth::InMemoryCredentialRevocationStore::new(),
2504            ));
2505        }
2506    }
2507
2508    fn mock_service() -> (MockService, SigningKey) {
2509        ensure_test_revocation_store();
2510        // The CA key signs the bare-sub (empty-iss) token; the ClusterKeySource
2511        // anchors that same CA key with an empty local issuer URL (so empty iss
2512        // is "local").
2513        let ca = SigningKey::from_bytes(&[7u8; 32]);
2514        let key_source =
2515            std::sync::Arc::new(ClusterKeySource::new(ca.verifying_key(), String::new()));
2516        let svc = MockService {
2517            signing_key: SigningKey::from_bytes(&[8u8; 32]),
2518            transport: TransportConfig::inproc("mock"),
2519            key_source,
2520            policy: crate::crypto::CryptoPolicy::Classical,
2521            relay: None,
2522            cached_subjects: std::sync::Arc::default(),
2523            internal_controller: None,
2524            federate_opt_in: false,
2525            audience: None,
2526            relay_resource_audience: None,
2527            unchecked_resource_selector: false,
2528        };
2529        (svc, ca)
2530    }
2531
2532    struct MockFederation {
2533        issuer: String,
2534        verifying_key: ed25519_dalek::VerifyingKey,
2535    }
2536
2537    #[async_trait]
2538    impl FederationKeySource for MockFederation {
2539        fn is_trusted(&self, issuer: &str) -> bool {
2540            issuer == self.issuer
2541        }
2542
2543        async fn get_keys(&self, issuer: &str, kid: Option<&str>) -> Result<Vec<FederationKey>> {
2544            anyhow::ensure!(self.is_trusted(issuer), "untrusted issuer");
2545            Ok(vec![FederationKey {
2546                kid: kid.map(str::to_owned),
2547                verifying_key: self.verifying_key,
2548            }])
2549        }
2550    }
2551
2552    fn empty_iss_token(ca: &SigningKey) -> String {
2553        // iss defaults to empty in Claims::new — the local bare-sub token.
2554        let now = chrono::Utc::now().timestamp();
2555        let claims = Claims::new("alice".to_owned(), now, now + 3600);
2556        assert!(claims.iss.is_empty(), "test token must have empty iss");
2557        crate::auth::jwt::encode(&claims, ca)
2558    }
2559
2560    #[tokio::test]
2561    async fn empty_iss_rejected_for_networked_caller() {
2562        let (svc, ca) = mock_service();
2563        let token = empty_iss_token(&ca);
2564        let mut ctx = ctx_with_token(token, /* is_local_caller */ false);
2565
2566        let result = svc.verify_claims(&mut ctx).await;
2567        assert!(
2568            result.is_err(),
2569            "networked empty-iss token must be rejected"
2570        );
2571        let msg = result.err().map(|e| e.to_string()).unwrap_or_default();
2572        assert!(
2573            msg.contains("empty JWT issuer is only accepted from in-process callers"),
2574            "unexpected error: {msg}"
2575        );
2576    }
2577
2578    #[tokio::test]
2579    async fn empty_iss_accepted_for_inproc_caller() {
2580        let (svc, ca) = mock_service();
2581        let token = empty_iss_token(&ca);
2582        let mut ctx = ctx_with_token(token, /* is_local_caller */ true);
2583
2584        let result = svc.verify_claims(&mut ctx).await;
2585        assert!(
2586            result.is_ok(),
2587            "in-process empty-iss token must pass the gate: {result:?}"
2588        );
2589        // And the local bare-sub subject is resolved.
2590        assert_eq!(ctx.subject().name(), Some("alice"));
2591        assert!(ctx.verified_direct_jwt().is_none());
2592    }
2593
2594    #[tokio::test]
2595    async fn direct_credential_snapshot_is_exposed_only_after_full_network_verification() {
2596        let (mut svc, ca) = mock_service();
2597        svc.key_source = std::sync::Arc::new(ClusterKeySource::new(
2598            ca.verifying_key(),
2599            "https://ordinary.example".into(),
2600        ));
2601        let now = chrono::Utc::now().timestamp();
2602        let mut claims = Claims::new("alice".into(), now, now + 300);
2603        claims.iss = "https://ordinary.example".into();
2604        claims.client_id = Some("ordinary-client".into());
2605        let token = crate::auth::jwt::encode(&claims, &ca);
2606        let mut ctx = ctx_with_token(token.clone(), false);
2607        assert!(ctx.verified_direct_jwt().is_none());
2608        svc.verify_claims(&mut ctx)
2609            .await
2610            .expect("direct credential");
2611        let (verified, exact_token) = ctx.verified_direct_jwt().expect("verified direct token");
2612        assert_eq!(verified.sub, "alice");
2613        assert_eq!(exact_token, token);
2614    }
2615
2616    #[tokio::test]
2617    async fn signed_federate_generation_denies_before_identity_or_key_cache() {
2618        let (svc, ca) = mock_service();
2619        let now = chrono::Utc::now().timestamp();
2620        let claims = Claims::new("alice".into(), now, now + 300)
2621            .with_session_authority_generation([0x42; 32]);
2622        let mut ctx = ctx_with_token(crate::auth::jwt::encode(&claims, &ca), true);
2623        assert!(svc.verify_claims(&mut ctx).await.is_err());
2624        assert!(ctx.subject().is_anonymous());
2625        assert!(ctx.claims().is_none());
2626        assert!(ctx.verified_direct_jwt().is_none());
2627        assert!(svc.cached_subjects.lock().is_empty());
2628    }
2629
2630    #[tokio::test]
2631    async fn isolated_federate_profile_claims_cannot_downgrade_to_generic_jwt() {
2632        let (svc, ca) = mock_service();
2633        let now = chrono::Utc::now().timestamp();
2634        for claims in [
2635            Claims::new("alice".into(), now, now + 300)
2636                .with_federate_signer_suite("fixture-suite".into()),
2637            {
2638                let mut claims = Claims::new("alice".into(), now, now + 300);
2639                claims.hs_profile = Some("federate-session-v1".into());
2640                claims
2641            },
2642            {
2643                let mut claims = Claims::new("alice".into(), now, now + 300);
2644                claims.hs_signer_suite_v1 = Some("fixture-suite".into());
2645                claims
2646            },
2647        ] {
2648            let mut ctx = ctx_with_token(crate::auth::jwt::encode(&claims, &ca), true);
2649            assert!(svc.verify_claims(&mut ctx).await.is_err());
2650            assert!(ctx.subject().is_anonymous());
2651            assert!(ctx.claims().is_none());
2652            assert!(svc.cached_subjects.lock().is_empty());
2653        }
2654    }
2655
2656    #[tokio::test]
2657    async fn reserved_client_without_inventory_cannot_fall_back_to_static_jwt() {
2658        let (mut svc, ca) = mock_service();
2659        svc.key_source = std::sync::Arc::new(ClusterKeySource::new(
2660            ca.verifying_key(),
2661            crate::auth::claims::FEDERATE_STAGING_HOST.into(),
2662        ));
2663        let now = chrono::Utc::now().timestamp();
2664        let mut claims = Claims::new("alice".into(), now, now + 300);
2665        claims.iss = crate::auth::claims::FEDERATE_STAGING_HOST.into();
2666        claims.client_id = Some(crate::auth::claims::FEDERATE_STAGING_CLIENT.into());
2667        let mut ctx = ctx_with_token(crate::auth::jwt::encode(&claims, &ca), false);
2668        assert!(svc.verify_claims(&mut ctx).await.is_err());
2669        assert!(ctx.subject().is_anonymous());
2670        assert!(ctx.claims().is_none());
2671        assert!(svc.cached_subjects.lock().is_empty());
2672    }
2673
2674    #[tokio::test]
2675    async fn opted_in_federate_jwt_is_deferred_and_marker_stripping_denies() {
2676        let (mut svc, ca) = mock_service();
2677        svc.federate_opt_in = true;
2678        svc.audience = Some(crate::auth::claims::FEDERATE_STAGING_HOST.into());
2679        svc.key_source = std::sync::Arc::new(ClusterKeySource::new(
2680            ca.verifying_key(),
2681            crate::auth::claims::FEDERATE_STAGING_HOST.into(),
2682        ));
2683        let holder = SigningKey::from_bytes(&[41; 32]).verifying_key().to_bytes();
2684        let relay = SigningKey::from_bytes(&[42; 32]).verifying_key().to_bytes();
2685        let now = chrono::Utc::now().timestamp();
2686        let claims = Claims::new("alice".into(), now, now + 300)
2687            .with_issuer(crate::auth::claims::FEDERATE_STAGING_HOST.into())
2688            .with_audience(Some(crate::auth::claims::FEDERATE_STAGING_HOST.into()))
2689            .with_client_id(crate::auth::claims::FEDERATE_STAGING_CLIENT)
2690            .with_tenant("tenant-a".into())
2691            .with_sid("sid-a")
2692            .with_scope(Some("query:registry:List".into()))
2693            .with_cnf_jwk(&holder)
2694            .with_federate_signer_suite("fixture-suite".into())
2695            .with_federate_signer_inventory([7; 32]);
2696        let mut ctx = ctx_with_token(crate::auth::jwt::encode(&claims, &ca), false);
2697        ctx.cnf = relay;
2698        svc.verify_claims(&mut ctx)
2699            .await
2700            .expect("reserved JWT snapshot may defer");
2701        assert!(ctx.deferred_federate_credential().is_some());
2702        assert!(ctx.subject().is_anonymous());
2703        assert!(ctx.claims().is_none());
2704        assert!(ctx.verified_direct_jwt().is_none());
2705        assert!(svc.cached_subjects.lock().is_empty());
2706
2707        let mut stripped = claims.clone();
2708        stripped.hs_signer_inventory_v1 = None;
2709        let mut ctx = ctx_with_token(crate::auth::jwt::encode(&stripped, &ca), false);
2710        ctx.cnf = relay;
2711        assert!(svc.verify_claims(&mut ctx).await.is_err());
2712        assert!(ctx.deferred_federate_credential().is_none());
2713        assert!(ctx.subject().is_anonymous());
2714        assert!(svc.cached_subjects.lock().is_empty());
2715
2716        let mut mixed = claims.clone();
2717        mixed.hs_session_authority_generation = Some(URL_SAFE_NO_PAD.encode([8; 32]));
2718        let mut ctx = ctx_with_token(crate::auth::jwt::encode(&mixed, &ca), false);
2719        ctx.cnf = relay;
2720        assert!(svc.verify_claims(&mut ctx).await.is_err());
2721        assert!(ctx.deferred_federate_credential().is_none());
2722        assert!(ctx.subject().is_anonymous());
2723
2724        let mut malformed = claims;
2725        malformed.hs_signer_inventory_v1 =
2726            Some("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=".into());
2727        let mut ctx = ctx_with_token(crate::auth::jwt::encode(&malformed, &ca), false);
2728        ctx.cnf = relay;
2729        assert!(svc.verify_claims(&mut ctx).await.is_err());
2730        assert!(ctx.deferred_federate_credential().is_none());
2731        assert!(ctx.subject().is_anonymous());
2732    }
2733
2734    #[tokio::test]
2735    async fn configured_federate_host_tokens_cannot_cross_or_downgrade() {
2736        for local in ["https://vm-a.example", "https://vm-b.example:8443"] {
2737            let (mut svc, ca) = mock_service();
2738            svc.federate_opt_in = true;
2739            svc.audience = Some(local.into());
2740            svc.key_source =
2741                std::sync::Arc::new(ClusterKeySource::new(ca.verifying_key(), local.into()));
2742            let now = chrono::Utc::now().timestamp();
2743            let claims = Claims::new("alice".into(), now, now + 120)
2744                .with_issuer(local.into())
2745                .with_audience(Some(local.into()))
2746                .with_client_id(crate::auth::claims::FEDERATE_STAGING_CLIENT)
2747                .with_federate_signer_suite("fixture-suite".into())
2748                .with_federate_signer_inventory([7; 32]);
2749            let mut ctx = ctx_with_token(crate::auth::jwt::encode(&claims, &ca), false);
2750            svc.verify_claims(&mut ctx).await.unwrap();
2751            assert!(ctx.deferred_federate_credential().is_some());
2752            for variant in 0..5 {
2753                let mut bad = claims.clone();
2754                match variant {
2755                    0 => {
2756                        bad.iss = "https://other.example".into();
2757                        bad.aud = Some("https://other.example".into());
2758                    }
2759                    1 => {
2760                        bad.hs_profile = None;
2761                        bad.hs_signer_suite_v1 = None;
2762                        bad.hs_signer_inventory_v1 = None;
2763                    }
2764                    2 => bad.hs_signer_inventory_v1 = Some("malformed".into()),
2765                    3 => {
2766                        bad.hs_session_authority_generation = Some(URL_SAFE_NO_PAD.encode([8; 32]));
2767                    }
2768                    _ => bad.aud = Some("https://other.example".into()),
2769                }
2770                let mut ctx = ctx_with_token(crate::auth::jwt::encode(&bad, &ca), false);
2771                assert!(
2772                    svc.verify_claims(&mut ctx).await.is_err(),
2773                    "{local} variant {variant}"
2774                );
2775                assert!(ctx.subject().is_anonymous());
2776                assert!(ctx.deferred_federate_credential().is_none());
2777                assert!(ctx.claims().is_none());
2778                assert!(svc.cached_subjects.lock().is_empty());
2779            }
2780        }
2781    }
2782
2783    #[tokio::test]
2784    async fn hybrid_federate_access_token_passes_production_verification_gate() {
2785        use crate::auth::{
2786            CompositeKeyPair, CompositeKeySet, CompositePairRole, CompositePairState,
2787        };
2788
2789        let (mut svc, ca) = mock_service();
2790        svc.federate_opt_in = true;
2791        svc.audience = Some(crate::auth::claims::FEDERATE_STAGING_HOST.into());
2792        svc.policy = crate::crypto::CryptoPolicy::Hybrid;
2793
2794        let ed = SigningKey::from_bytes(&[61; 32]);
2795        let (pq, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
2796        let proof_pq_public = crate::crypto::pq::ml_dsa_vk_bytes(&pq_vk);
2797        let kid = crate::auth::composite_kid(&pq_vk, &ed.verifying_key());
2798        let key_set = std::sync::Arc::new(CompositeKeySet::default());
2799        key_set
2800            .publish(
2801                1,
2802                "hybrid-federate-verifier-test".to_owned(),
2803                vec![CompositeKeyPair::verifying(
2804                    kid.clone(),
2805                    pq_vk,
2806                    ed.verifying_key(),
2807                    CompositePairRole::OAuth,
2808                    CompositePairState::Active,
2809                    0,
2810                    i64::MAX,
2811                )],
2812            )
2813            .unwrap();
2814        svc.key_source = std::sync::Arc::new(
2815            ClusterKeySource::new(
2816                ca.verifying_key(),
2817                crate::auth::claims::FEDERATE_STAGING_HOST.into(),
2818            )
2819            .with_composite_key_set(key_set),
2820        );
2821
2822        let holder = SigningKey::from_bytes(&[62; 32]).verifying_key().to_bytes();
2823        let suite_thumbprint = crate::auth::signer_suite_thumbprint(
2824            crate::auth::SUITE_HYBRID_ED25519_MLDSA65,
2825            &[&holder, &proof_pq_public],
2826        );
2827        let now = chrono::Utc::now().timestamp();
2828        let mut claims = Claims::new("did:plc:3f7ldey5bivhfjapwqi2sljy".into(), now, now + 300)
2829            .with_issuer(crate::auth::claims::FEDERATE_STAGING_HOST.into())
2830            .with_audience(Some(crate::auth::claims::FEDERATE_STAGING_HOST.into()))
2831            .with_client_id(crate::auth::claims::FEDERATE_STAGING_CLIENT)
2832            .with_tenant("tenant-a".into())
2833            .with_sid("sid-hybrid")
2834            .with_scope(Some("query:registry:List".into()))
2835            .with_cnf_jwk(&holder)
2836            .with_federate_signer_suite(URL_SAFE_NO_PAD.encode(suite_thumbprint))
2837            .with_federate_signer_inventory([7; 32])
2838            .with_jti();
2839        claims.hs_signer_pq_key_v1 = Some(URL_SAFE_NO_PAD.encode(proof_pq_public));
2840        claims.hs_source_issuer_v1 = Some("https://login.federate.to".into());
2841        claims.hs_source_subject_v1 = Some("opaque-atproto-connector-subject".into());
2842        let header = format!(r#"{{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt","kid":"{kid}"}}"#);
2843        let token = composite_token(&header, &claims, &pq, &ed, false);
2844        let mut ctx = ctx_with_token(token, false);
2845        ctx.cnf = SigningKey::from_bytes(&[63; 32]).verifying_key().to_bytes();
2846
2847        svc.verify_claims(&mut ctx)
2848            .await
2849            .expect("hybrid Federate access token should pass Hybrid verification");
2850        let (verified_claims, _) = ctx
2851            .deferred_federate_credential()
2852            .expect("stateless Federate token should be deferred");
2853        assert_eq!(
2854            verified_claims.federate_signer_inventory().unwrap(),
2855            Some([7; 32])
2856        );
2857        assert!(verified_claims
2858            .session_authority_generation()
2859            .unwrap()
2860            .is_none());
2861        assert!(ctx.subject().is_anonymous());
2862        assert!(ctx.claims().is_none());
2863    }
2864
2865    #[tokio::test]
2866    async fn verified_local_did_unknown_jwt_cannot_authenticate() {
2867        let (svc, ca) = mock_service();
2868        let now = chrono::Utc::now().timestamp();
2869        let claims = Claims::new(UNAUTHENTICATED_DID_SENTINEL.to_owned(), now, now + 3600)
2870            .with_tenant("attacker-tenant".to_owned());
2871        let token = crate::auth::jwt::encode(&claims, &ca);
2872        let mut ctx = ctx_with_token(token, /* is_local_caller */ true);
2873
2874        let error = svc
2875            .verify_claims(&mut ctx)
2876            .await
2877            .expect_err("the credential-absence sentinel must not authenticate");
2878
2879        assert!(
2880            error.to_string().contains("cannot authenticate"),
2881            "{error:#}"
2882        );
2883        assert!(ctx.subject().is_anonymous());
2884        assert!(ctx.claims().is_none());
2885        assert_eq!(ctx.verified_tenant(), None);
2886    }
2887
2888    #[tokio::test]
2889    async fn did_unknown_cnf_signer_is_never_cached() {
2890        let (svc, ca) = mock_service();
2891        let signer = SigningKey::from_bytes(&[0x71; 32]);
2892        let now = chrono::Utc::now().timestamp();
2893        let claims = Claims::new(UNAUTHENTICATED_DID_SENTINEL.to_owned(), now, now + 3600)
2894            .with_cnf_jwk(signer.verifying_key().as_bytes());
2895        let token = crate::auth::jwt::encode(&claims, &ca);
2896        let mut ctx = ctx_with_token(token, /* is_local_caller */ true);
2897        ctx.cnf = signer.verifying_key().to_bytes();
2898
2899        svc.verify_claims(&mut ctx)
2900            .await
2901            .expect_err("the sentinel token must be rejected before cnf caching");
2902
2903        assert!(
2904            svc.cached_subjects.lock().is_empty(),
2905            "no signer may be cached for did:unknown"
2906        );
2907    }
2908
2909    // ── #1425 r1 P1#3: the browser exchange mints a `cnf.jkt`-bound token for
2910    //    the SAME Ed25519 key used to sign RPC envelopes (`VfsShell::connect`
2911    //    passes `signer_pubkey` as both the DPoP key and the envelope signer).
2912    //    These tests exercise `verify_claims` — the actual, unmodified server
2913    //    RPC dispatch path every transport (QUIC/UDS/inproc/iroh) runs — with
2914    //    a token shaped exactly like that mint, proving the sender-bound
2915    //    token is usable when the envelope is signed by the matching key and
2916    //    is rejected when signed by a different one. No separate per-request
2917    //    DPoP proof JWT is needed on this transport: the envelope signature
2918    //    itself is the freshly-signed proof of possession for every call.
2919
2920    #[tokio::test]
2921    async fn browser_cnf_jkt_token_succeeds_over_matching_envelope_signer() {
2922        let (svc, ca) = mock_service();
2923        let browser_key = SigningKey::from_bytes(&[0x51; 32]);
2924        let now = chrono::Utc::now().timestamp();
2925        let claims = Claims::new("alice".to_owned(), now, now + 3600)
2926            .with_cnf_jkt(browser_key.verifying_key().as_bytes());
2927        let token = crate::auth::jwt::encode(&claims, &ca);
2928        let mut ctx = ctx_with_token(token, /* is_local_caller */ true);
2929        // The envelope is signed by the SAME key the browser used for DPoP —
2930        // exactly what `VfsShell::connect` arranges by construction.
2931        ctx.cnf = browser_key.verifying_key().to_bytes();
2932
2933        svc.verify_claims(&mut ctx)
2934            .await
2935            .expect("cnf.jkt-bound token over its own signing key must be accepted");
2936        assert_eq!(ctx.subject().name(), Some("alice"));
2937    }
2938
2939    #[tokio::test]
2940    async fn browser_cnf_jkt_token_rejected_over_mismatched_envelope_signer() {
2941        let (svc, ca) = mock_service();
2942        let browser_key = SigningKey::from_bytes(&[0x52; 32]);
2943        let attacker_key = SigningKey::from_bytes(&[0x53; 32]);
2944        let now = chrono::Utc::now().timestamp();
2945        let claims = Claims::new("alice".to_owned(), now, now + 3600)
2946            .with_cnf_jkt(browser_key.verifying_key().as_bytes());
2947        let token = crate::auth::jwt::encode(&claims, &ca);
2948        let mut ctx = ctx_with_token(token, /* is_local_caller */ true);
2949        // An attacker who stole the token string signs the envelope with a
2950        // DIFFERENT key — there is no "present as Bearer" downgrade path on
2951        // this transport: cnf is checked against the actual signer whenever
2952        // it is present, unconditionally.
2953        ctx.cnf = attacker_key.verifying_key().to_bytes();
2954
2955        let err = svc
2956            .verify_claims(&mut ctx)
2957            .await
2958            .expect_err("cnf.jkt-bound token over a foreign envelope signer must be rejected");
2959        assert!(
2960            err.to_string().contains("cnf.jkt"),
2961            "unexpected error: {err:#}"
2962        );
2963    }
2964
2965    #[tokio::test]
2966    async fn delegated_bearer_is_denied_by_default() {
2967        let (svc, ca) = mock_service();
2968        let token = empty_iss_token(&ca);
2969        let relay = [19u8; 32];
2970        let mut ctx = ctx_with_token(token.clone(), /* is_local_caller */ true);
2971        ctx.jwt_token = None;
2972        ctx.delegation_token = Some(token);
2973        ctx.cnf = relay;
2974
2975        let error = svc
2976            .verify_claims(&mut ctx)
2977            .await
2978            .expect_err("services must reject delegated bearers unless explicitly enabled");
2979        assert!(error.to_string().contains("not an authorized relay"));
2980    }
2981
2982    #[tokio::test]
2983    async fn delegated_bearer_is_verified_for_pinned_relay() {
2984        let (mut svc, ca) = mock_service();
2985        let relay = [19u8; 32];
2986        svc.relay = Some(relay);
2987        let token = empty_iss_token(&ca);
2988        let mut ctx = ctx_with_token(token.clone(), /* is_local_caller */ true);
2989        ctx.jwt_token = None;
2990        ctx.delegation_token = Some(token.clone());
2991        ctx.cnf = relay;
2992
2993        svc.verify_claims(&mut ctx)
2994            .await
2995            .expect("the pinned relay may delegate a bearer for re-verification");
2996        assert_eq!(ctx.subject().name(), Some("alice"));
2997        assert_eq!(ctx.jwt_token(), Some(token.as_str()));
2998    }
2999
3000    #[tokio::test]
3001    async fn configured_delegated_resource_audience_keeps_direct_and_wrong_aud_native() {
3002        let (mut svc, ca) = mock_service();
3003        let relay = [19u8; 32];
3004        svc.relay = Some(relay);
3005        svc.audience = Some("https://issuer.example".to_owned());
3006        svc.relay_resource_audience = Some("https://mcp.example".to_owned());
3007        let now = chrono::Utc::now().timestamp();
3008        let user = Claims::new("alice".to_owned(), now, now + 3600)
3009            .with_audience(Some("https://mcp.example".to_owned()));
3010        let token = crate::auth::jwt::encode(&user, &ca);
3011
3012        let mut admitted = ctx_with_token(token.clone(), true);
3013        admitted.jwt_token = None;
3014        admitted.delegation_token = Some(token.clone());
3015        admitted.cnf = relay;
3016        svc.verify_claims(&mut admitted).await.unwrap();
3017        assert_eq!(admitted.subject().name(), Some("alice"));
3018        assert!(admitted.has_delegated_resource_audience());
3019
3020        let mut direct = ctx_with_token(token.clone(), true);
3021        direct.cnf = relay;
3022        assert!(svc.verify_claims(&mut direct).await.is_err());
3023
3024        let mut wrong_relay = ctx_with_token(token.clone(), true);
3025        wrong_relay.jwt_token = None;
3026        wrong_relay.delegation_token = Some(token);
3027        wrong_relay.cnf = [27u8; 32];
3028        assert!(svc.verify_claims(&mut wrong_relay).await.is_err());
3029
3030        let wrong = Claims::new("alice".to_owned(), now, now + 3600)
3031            .with_audience(Some("https://unknown.example".to_owned()));
3032        let mut unknown = ctx_with_token(crate::auth::jwt::encode(&wrong, &ca), true);
3033        unknown.delegation_token = unknown.jwt_token.take();
3034        unknown.cnf = relay;
3035        assert!(svc.verify_claims(&mut unknown).await.is_err());
3036
3037        let native = Claims::new("alice".to_owned(), now, now + 3600)
3038            .with_audience(Some("https://issuer.example".to_owned()));
3039        let mut original = ctx_with_token(crate::auth::jwt::encode(&native, &ca), true);
3040        original.cnf = relay;
3041        svc.verify_claims(&mut original).await.unwrap();
3042        assert!(!original.has_delegated_resource_audience());
3043    }
3044
3045    #[tokio::test]
3046    async fn faulty_relay_selector_cannot_admit_absent_or_wrong_resource_aud() {
3047        let (mut svc, ca) = mock_service();
3048        let relay = [20u8; 32];
3049        svc.relay = Some(relay);
3050        svc.audience = Some("https://issuer.example".to_owned());
3051        svc.relay_resource_audience = Some("https://mcp.example".to_owned());
3052        // Simulate an override that ignores the unverified audience. The
3053        // generic verifier must still reject missing/wrong signed audiences.
3054        svc.unchecked_resource_selector = true;
3055        let now = chrono::Utc::now().timestamp();
3056        for aud in [None, Some("https://unknown.example".to_owned())] {
3057            let token = crate::auth::jwt::encode(
3058                &Claims::new("alice".to_owned(), now, now + 3600).with_audience(aud),
3059                &ca,
3060            );
3061            let mut ctx = ctx_with_token(token.clone(), true);
3062            ctx.jwt_token = None;
3063            ctx.delegation_token = Some(token);
3064            ctx.cnf = relay;
3065            let error = svc.verify_claims(&mut ctx).await.unwrap_err();
3066            assert!(
3067                error.to_string().contains("exact selected audience"),
3068                "{error}"
3069            );
3070            assert!(ctx.claims().is_none());
3071        }
3072    }
3073
3074    #[tokio::test]
3075    async fn signed_resource_audience_is_exact_for_every_jwt_algorithm() {
3076        use crate::auth::{
3077            CompositeKeyPair, CompositeKeySet, CompositePairRole, CompositePairState,
3078        };
3079
3080        let (mut svc, ca) = mock_service();
3081        let relay = [20u8; 32];
3082        let issuer = "https://issuer.example";
3083        let resource = "https://mcp.example";
3084        svc.relay = Some(relay);
3085        svc.audience = Some(issuer.to_owned());
3086        svc.relay_resource_audience = Some(resource.to_owned());
3087        let (pq, pq_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
3088        let composite_ed = SigningKey::from_bytes(&[21; 32]);
3089        let kid = crate::auth::composite_kid(&pq_vk, &composite_ed.verifying_key());
3090        let keys = std::sync::Arc::new(CompositeKeySet::default());
3091        keys.publish(
3092            1,
3093            "resource-audience-test".to_owned(),
3094            vec![CompositeKeyPair::verifying(
3095                kid.clone(),
3096                pq_vk.clone(),
3097                composite_ed.verifying_key(),
3098                CompositePairRole::OAuth,
3099                CompositePairState::Active,
3100                0,
3101                i64::MAX,
3102            )],
3103        )
3104        .unwrap();
3105        struct ResourceKeySource {
3106            cluster: ClusterKeySource,
3107            pq_vk: crate::crypto::pq::MlDsaVerifyingKey,
3108        }
3109        #[async_trait]
3110        impl crate::auth::JwtKeySource for ResourceKeySource {
3111            async fn get_key(
3112                &self,
3113                issuer: &str,
3114                kid: Option<&str>,
3115            ) -> Result<ed25519_dalek::VerifyingKey> {
3116                self.cluster.get_key(issuer, kid).await
3117            }
3118            fn is_trusted(&self, issuer: &str) -> bool {
3119                self.cluster.is_trusted(issuer)
3120            }
3121            fn local_issuers(&self) -> &[String] {
3122                self.cluster.local_issuers()
3123            }
3124            fn ml_dsa_verifying_keys(&self) -> Vec<crate::crypto::pq::MlDsaVerifyingKey> {
3125                vec![self.pq_vk.clone()]
3126            }
3127            fn composite_pair(&self, kid: &str) -> Option<crate::auth::CompositeKeyPair> {
3128                self.cluster.composite_pair(kid)
3129            }
3130        }
3131        svc.key_source = std::sync::Arc::new(ResourceKeySource {
3132            cluster: ClusterKeySource::new(ca.verifying_key(), issuer.to_owned())
3133                .with_composite_key_set(keys),
3134            pq_vk,
3135        });
3136        let now = chrono::Utc::now().timestamp();
3137        for alg in ["EdDSA", "ML-DSA-65", "ML-DSA-65-Ed25519"] {
3138            for (aud, faulty_selector) in [
3139                (Some(resource), false),
3140                (None, true),
3141                (Some("https://other.example"), true),
3142            ] {
3143                svc.unchecked_resource_selector = faulty_selector;
3144                let claims = Claims::new("alice".to_owned(), now, now + 3600)
3145                    .with_issuer(issuer.to_owned())
3146                    .with_client_id("resource-client")
3147                    .with_jti()
3148                    .with_audience(aud.map(str::to_owned));
3149                let token = match alg {
3150                    "EdDSA" => crate::auth::jwt::encode(&claims, &ca),
3151                    "ML-DSA-65" => {
3152                        let header = r#"{"alg":"ML-DSA-65","typ":"at+jwt","kid":"resource-pq"}"#;
3153                        let input = format!(
3154                            "{}.{}",
3155                            URL_SAFE_NO_PAD.encode(header),
3156                            URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap())
3157                        );
3158                        let signature = crate::crypto::pq::ml_dsa_sign(&pq, input.as_bytes());
3159                        format!("{input}.{}", URL_SAFE_NO_PAD.encode(signature))
3160                    }
3161                    _ => {
3162                        let header = format!(
3163                            r#"{{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt","kid":"{kid}"}}"#
3164                        );
3165                        composite_token(&header, &claims, &pq, &composite_ed, false)
3166                    }
3167                };
3168                let mut ctx = ctx_with_token(token.clone(), true);
3169                ctx.jwt_token = None;
3170                ctx.delegation_token = Some(token);
3171                ctx.cnf = relay;
3172                if aud == Some(resource) {
3173                    svc.verify_claims(&mut ctx).await.unwrap_or_else(|error| {
3174                        panic!("{alg}: exact signed resource audience was rejected: {error:#}")
3175                    });
3176                    assert_eq!(ctx.subject().name(), Some("alice"), "{alg}");
3177                    assert_eq!(
3178                        ctx.claims().unwrap().aud.as_deref(),
3179                        Some(resource),
3180                        "{alg}"
3181                    );
3182                    assert!(ctx.has_delegated_resource_audience(), "{alg}");
3183                    let opaque = crate::service::DecodedRequestBody::opaque(vec![0]);
3184                    assert!(
3185                        !svc.accept_delegated_resource_leaf(&ctx, &opaque),
3186                        "{alg}: default decoded leaf must deny"
3187                    );
3188                } else {
3189                    let error = svc.verify_claims(&mut ctx).await.unwrap_err();
3190                    assert!(
3191                        error.to_string().contains("exact selected audience"),
3192                        "{alg}: {error:#}"
3193                    );
3194                    assert!(ctx.claims().is_none(), "{alg}");
3195                    assert!(ctx.subject().is_anonymous(), "{alg}");
3196                }
3197            }
3198        }
3199    }
3200
3201    #[test]
3202    fn delegated_resource_leaf_default_is_denied_even_after_authentication() {
3203        let (svc, _) = mock_service();
3204        let ctx = ctx_with_token(String::new(), true);
3205        let opaque = crate::service::DecodedRequestBody::opaque(vec![0]);
3206        assert!(!svc.accept_delegated_resource_leaf(&ctx, &opaque));
3207    }
3208
3209    #[tokio::test]
3210    async fn delegated_public_service_credential_requires_holder_proof() {
3211        let (mut svc, ca) = mock_service();
3212        let holder = SigningKey::from_bytes(&[21u8; 32]);
3213        let relay = SigningKey::from_bytes(&[22u8; 32]);
3214        svc.relay = Some(relay.verifying_key().to_bytes());
3215        let now = chrono::Utc::now().timestamp();
3216        let claims = crate::auth::Claims::new("service:policy".to_owned(), now, now + 300)
3217            .with_cnf_jwk(&holder.verifying_key().to_bytes());
3218        let token = crate::auth::jwt::encode_service_jwt(&claims, &ca);
3219
3220        // The credential itself is valid when presented by its holder.
3221        let mut direct = ctx_with_token(token.clone(), true);
3222        direct.cnf = holder.verifying_key().to_bytes();
3223        svc.verify_claims(&mut direct)
3224            .await
3225            .expect("valid holder credential");
3226        assert_eq!(direct.subject().name(), Some("service:policy"));
3227
3228        // Service WITs are distributed as key attestations. Relay admission
3229        // cannot turn knowledge of one into proof of the attested private key.
3230        let mut replay = ctx_with_token(token.clone(), true);
3231        replay.jwt_token = None;
3232        replay.delegation_token = Some(token);
3233        replay.cnf = relay.verifying_key().to_bytes();
3234        let error = svc.verify_claims(&mut replay).await.expect_err(
3235            "an admitted relay must not impersonate a published service credential's holder",
3236        );
3237        assert!(error
3238            .to_string()
3239            .contains("requires its bound holder signer"));
3240        assert!(
3241            replay.claims().is_none(),
3242            "rejected relay must not acquire verified claims"
3243        );
3244    }
3245
3246    #[tokio::test]
3247    async fn delegated_service_thumbprint_requires_holder_and_missing_binding_denies() {
3248        let (mut svc, ca) = mock_service();
3249        let holder = SigningKey::from_bytes(&[23u8; 32])
3250            .verifying_key()
3251            .to_bytes();
3252        let foreign = SigningKey::from_bytes(&[24u8; 32])
3253            .verifying_key()
3254            .to_bytes();
3255        let now = chrono::Utc::now().timestamp();
3256        let base = Claims::new("service:policy".to_owned(), now, now + 300);
3257        for (claims, signer, allowed) in [
3258            (base.clone().with_cnf_jkt(&holder), holder, true),
3259            (base.clone().with_cnf_jkt(&holder), foreign, false),
3260            (base, holder, false),
3261        ] {
3262            svc.relay = Some(signer);
3263            let token = crate::auth::jwt::encode_service_jwt(&claims, &ca);
3264            let mut ctx = ctx_with_token(token.clone(), true);
3265            ctx.jwt_token = None;
3266            ctx.delegation_token = Some(token);
3267            ctx.cnf = signer;
3268            let result = svc.verify_claims(&mut ctx).await;
3269            if allowed {
3270                result.expect("thumbprint-bound holder must remain accepted");
3271                assert_eq!(ctx.subject().name(), Some("service:policy"));
3272            } else {
3273                let error = result.expect_err("foreign or unbound service delegation must deny");
3274                assert!(
3275                    error
3276                        .to_string()
3277                        .contains("requires its bound holder signer"),
3278                    "{error:#}"
3279                );
3280                assert!(
3281                    ctx.claims().is_none(),
3282                    "rejected delegation must publish no claims"
3283                );
3284            }
3285        }
3286    }
3287
3288    #[tokio::test]
3289    async fn federated_issuer_cannot_assert_local_tenant() {
3290        ensure_test_revocation_store();
3291        let local_ca = SigningKey::from_bytes(&[9u8; 32]);
3292        let federated_signer = SigningKey::from_bytes(&[10u8; 32]);
3293        let local_issuer = "https://this.node";
3294        let federated_issuer = "https://idp.example.com";
3295        let federation = std::sync::Arc::new(MockFederation {
3296            issuer: federated_issuer.to_owned(),
3297            verifying_key: federated_signer.verifying_key(),
3298        });
3299        let key_source = std::sync::Arc::new(FederatedKeySource::new(
3300            ClusterKeySource::new(local_ca.verifying_key(), local_issuer.to_owned()),
3301            federation,
3302        ));
3303        let svc = MockService {
3304            signing_key: local_ca,
3305            transport: TransportConfig::inproc("mock"),
3306            key_source,
3307            policy: crate::crypto::CryptoPolicy::Classical,
3308            relay: None,
3309            cached_subjects: std::sync::Arc::default(),
3310            internal_controller: None,
3311            federate_opt_in: false,
3312            audience: None,
3313            relay_resource_audience: None,
3314            unchecked_resource_selector: false,
3315        };
3316        let now = chrono::Utc::now().timestamp();
3317        let claims = Claims::new("alice".to_owned(), now, now + 3600)
3318            .with_issuer(federated_issuer.to_owned())
3319            .with_tenant("acme".to_owned())
3320            .with_client_id("hyprstream-oauth-client-1");
3321        let token = crate::auth::jwt::encode(&claims, &federated_signer);
3322        let mut ctx = ctx_with_token(token, /* is_local_caller */ false);
3323
3324        svc.verify_claims(&mut ctx)
3325            .await
3326            .expect("federated identity token should verify");
3327
3328        assert_eq!(ctx.subject().name(), Some("https://idp.example.com:alice"));
3329        assert_ne!(ctx.verified_tenant(), Some("acme"));
3330        assert_eq!(ctx.verified_tenant(), None);
3331        assert!(
3332            ctx.domain().is_err(),
3333            "a stripped federated tenant must fail domain resolution closed"
3334        );
3335    }
3336
3337    #[tokio::test]
3338    async fn local_issuer_preserves_verified_tenant() {
3339        ensure_test_revocation_store();
3340        let local_ca = SigningKey::from_bytes(&[11u8; 32]);
3341        let local_issuer = "https://this.node";
3342        let key_source = std::sync::Arc::new(ClusterKeySource::new(
3343            local_ca.verifying_key(),
3344            local_issuer.to_owned(),
3345        ));
3346        let svc = MockService {
3347            signing_key: local_ca.clone(),
3348            transport: TransportConfig::inproc("mock"),
3349            key_source,
3350            policy: crate::crypto::CryptoPolicy::Classical,
3351            relay: None,
3352            cached_subjects: std::sync::Arc::default(),
3353            internal_controller: None,
3354            federate_opt_in: false,
3355            audience: None,
3356            relay_resource_audience: None,
3357            unchecked_resource_selector: false,
3358        };
3359        let now = chrono::Utc::now().timestamp();
3360        let claims = Claims::new("alice".to_owned(), now, now + 3600)
3361            .with_issuer(local_issuer.to_owned())
3362            .with_tenant("acme".to_owned())
3363            .with_client_id("hyprstream-oauth-client-1");
3364        let token = crate::auth::jwt::encode(&claims, &local_ca);
3365        let mut ctx = ctx_with_token(token, /* is_local_caller */ false);
3366
3367        svc.verify_claims(&mut ctx)
3368            .await
3369            .expect("local identity token should verify");
3370
3371        assert_eq!(ctx.subject().name(), Some("alice"));
3372        assert_eq!(ctx.verified_tenant(), Some("acme"));
3373        assert_eq!(ctx.domain().expect("local tenant domain"), "acme");
3374    }
3375
3376    /// RFC 9068 §2.2.1 (v16 credential profile) at the signed verify boundary:
3377    /// an issuer-scoped `at+jwt` credential MUST carry a non-empty `client_id`.
3378    /// A missing or empty `client_id` is rejected; a `wit+jwt` service
3379    /// credential is positively exempt (it carries no client_id). The
3380    /// federated/nonlocal `at+jwt` path is covered by the sibling
3381    /// `federated_at_jwt_missing_client_id_is_rejected`.
3382    #[tokio::test]
3383    async fn local_at_jwt_requires_client_id_and_wit_jwt_is_exempt() {
3384        let local_ca = SigningKey::from_bytes(&[11u8; 32]);
3385        let local_issuer = "https://this.node";
3386        let key_source = std::sync::Arc::new(ClusterKeySource::new(
3387            local_ca.verifying_key(),
3388            local_issuer.to_owned(),
3389        ));
3390        let svc = MockService {
3391            signing_key: local_ca.clone(),
3392            transport: TransportConfig::inproc("mock"),
3393            key_source,
3394            policy: crate::crypto::CryptoPolicy::Classical,
3395            relay: None,
3396            cached_subjects: std::sync::Arc::default(),
3397            internal_controller: None,
3398            federate_opt_in: false,
3399            audience: None,
3400            relay_resource_audience: None,
3401            unchecked_resource_selector: false,
3402        };
3403        let now = chrono::Utc::now().timestamp();
3404
3405        // Local at+jwt WITHOUT client_id → rejected.
3406        let missing = Claims::new("alice".to_owned(), now, now + 3600)
3407            .with_issuer(local_issuer.to_owned())
3408            .with_tenant("acme".to_owned());
3409        let err = svc
3410            .verify_claims(&mut ctx_with_token(
3411                crate::auth::jwt::encode(&missing, &local_ca),
3412                false,
3413            ))
3414            .await
3415            .expect_err("local at+jwt without client_id must be rejected");
3416        assert!(
3417            err.to_string().contains("client_id"),
3418            "unexpected error for missing client_id: {err}"
3419        );
3420
3421        // Local at+jwt with EMPTY client_id → rejected (set directly, bypassing
3422        // the empty-filtering builder).
3423        let mut empty = Claims::new("alice".to_owned(), now, now + 3600)
3424            .with_issuer(local_issuer.to_owned())
3425            .with_tenant("acme".to_owned());
3426        empty.client_id = Some(String::new());
3427        let err = svc
3428            .verify_claims(&mut ctx_with_token(
3429                crate::auth::jwt::encode(&empty, &local_ca),
3430                false,
3431            ))
3432            .await
3433            .expect_err("local at+jwt with empty client_id must be rejected");
3434        assert!(
3435            err.to_string().contains("client_id"),
3436            "unexpected error for empty client_id: {err}"
3437        );
3438
3439        // A local `wit+jwt` service credential WITHOUT client_id is positively
3440        // exempt — it is ADMITTED (not merely un-rejected-for-client_id). The
3441        // MockService provides a test-local revocation store, so the
3442        // jti-bearing service token verifies.
3443        let service = Claims::new("service:model".to_owned(), now, now + 3600)
3444            .with_issuer(local_issuer.to_owned())
3445            .with_jti();
3446        let mut wit_ctx = ctx_with_token(
3447            crate::auth::jwt::encode_service_jwt(&service, &local_ca),
3448            false,
3449        );
3450        svc.verify_claims(&mut wit_ctx)
3451            .await
3452            .expect("local wit+jwt without client_id must be admitted (type-driven exemption)");
3453        assert_eq!(wit_ctx.subject().name(), Some("service:model"));
3454    }
3455
3456    /// A trusted federated (nonlocal) `at+jwt` without `client_id` is rejected —
3457    /// the requirement is positively typed on `at+jwt` and applies regardless of
3458    /// issuer locality.
3459    #[tokio::test]
3460    async fn federated_at_jwt_missing_or_empty_client_id_is_rejected() {
3461        let local_ca = SigningKey::from_bytes(&[9u8; 32]);
3462        let federated_signer = SigningKey::from_bytes(&[10u8; 32]);
3463        let local_issuer = "https://this.node";
3464        let federated_issuer = "https://idp.example.com";
3465        let federation = std::sync::Arc::new(MockFederation {
3466            issuer: federated_issuer.to_owned(),
3467            verifying_key: federated_signer.verifying_key(),
3468        });
3469        let key_source = std::sync::Arc::new(FederatedKeySource::new(
3470            ClusterKeySource::new(local_ca.verifying_key(), local_issuer.to_owned()),
3471            federation,
3472        ));
3473        let svc = MockService {
3474            signing_key: local_ca,
3475            transport: TransportConfig::inproc("mock"),
3476            key_source,
3477            policy: crate::crypto::CryptoPolicy::Classical,
3478            relay: None,
3479            cached_subjects: std::sync::Arc::default(),
3480            internal_controller: None,
3481            federate_opt_in: false,
3482            audience: None,
3483            relay_resource_audience: None,
3484            unchecked_resource_selector: false,
3485        };
3486        let now = chrono::Utc::now().timestamp();
3487
3488        // Missing client_id → rejected.
3489        let missing = Claims::new("alice".to_owned(), now, now + 3600)
3490            .with_issuer(federated_issuer.to_owned())
3491            .with_tenant("acme".to_owned());
3492        let err = svc
3493            .verify_claims(&mut ctx_with_token(
3494                crate::auth::jwt::encode(&missing, &federated_signer),
3495                false,
3496            ))
3497            .await
3498            .expect_err("federated at+jwt without client_id must be rejected");
3499        assert!(
3500            err.to_string().contains("client_id"),
3501            "unexpected error for federated missing client_id: {err}"
3502        );
3503
3504        // Empty/whitespace client_id → rejected.
3505        let mut empty = Claims::new("alice".to_owned(), now, now + 3600)
3506            .with_issuer(federated_issuer.to_owned())
3507            .with_tenant("acme".to_owned());
3508        empty.client_id = Some("   ".to_owned());
3509        let err = svc
3510            .verify_claims(&mut ctx_with_token(
3511                crate::auth::jwt::encode(&empty, &federated_signer),
3512                false,
3513            ))
3514            .await
3515            .expect_err("federated at+jwt with empty client_id must be rejected");
3516        assert!(
3517            err.to_string().contains("client_id"),
3518            "unexpected error for federated empty client_id: {err}"
3519        );
3520    }
3521
3522    fn composite_token(
3523        header: &str,
3524        claims: &Claims,
3525        pq: &crate::crypto::pq::MlDsaSigningKey,
3526        ed: &SigningKey,
3527        half: bool,
3528    ) -> String {
3529        let header = URL_SAFE_NO_PAD.encode(header);
3530        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).unwrap());
3531        let input = format!("{header}.{payload}");
3532        let mut signature = crate::crypto::pq::ml_dsa_sign(pq, input.as_bytes());
3533        if !half {
3534            signature.extend_from_slice(&ed.sign(input.as_bytes()).to_bytes());
3535        }
3536        format!("{input}.{}", URL_SAFE_NO_PAD.encode(signature))
3537    }
3538
3539    #[tokio::test]
3540    async fn request_service_enforces_exact_pair_and_closed_header() {
3541        let ca = SigningKey::from_bytes(&[41; 32]);
3542        let ed_a = SigningKey::from_bytes(&[42; 32]);
3543        let ed_b = SigningKey::from_bytes(&[43; 32]);
3544        let (pq_a, pq_a_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
3545        let (_pq_b, pq_b_vk) = crate::crypto::pq::ml_dsa_generate_keypair();
3546        let kid_a = crate::auth::jwk_thumbprint(&crate::auth::JwkThumbprintInput::Akp {
3547            alg: "ML-DSA-65-Ed25519",
3548            pub_bytes: &[
3549                crate::crypto::pq::ml_dsa_vk_bytes(&pq_a_vk),
3550                ed_a.verifying_key().to_bytes().to_vec(),
3551            ]
3552            .concat(),
3553        });
3554        let kid_b = crate::auth::jwk_thumbprint(&crate::auth::JwkThumbprintInput::Akp {
3555            alg: "ML-DSA-65-Ed25519",
3556            pub_bytes: &[
3557                crate::crypto::pq::ml_dsa_vk_bytes(&pq_b_vk),
3558                ed_b.verifying_key().to_bytes().to_vec(),
3559            ]
3560            .concat(),
3561        });
3562        let key_set = std::sync::Arc::new(crate::auth::CompositeKeySet::default());
3563        key_set
3564            .publish(
3565                1,
3566                "request-service-test-generation".to_owned(),
3567                vec![
3568                    crate::auth::CompositeKeyPair::verifying(
3569                        kid_a.clone(),
3570                        pq_a_vk,
3571                        ed_a.verifying_key(),
3572                        crate::auth::CompositePairRole::OAuth,
3573                        crate::auth::CompositePairState::Active,
3574                        0,
3575                        i64::MAX,
3576                    ),
3577                    crate::auth::CompositeKeyPair::verifying(
3578                        kid_b,
3579                        pq_b_vk,
3580                        ed_b.verifying_key(),
3581                        crate::auth::CompositePairRole::OAuth,
3582                        crate::auth::CompositePairState::Drain,
3583                        0,
3584                        i64::MAX,
3585                    ),
3586                ],
3587            )
3588            .unwrap();
3589        let key_source = std::sync::Arc::new(
3590            ClusterKeySource::new(ca.verifying_key(), "https://local".to_owned())
3591                .with_composite_key_set(key_set),
3592        );
3593        let svc = MockService {
3594            signing_key: ca,
3595            transport: TransportConfig::inproc("mock"),
3596            key_source,
3597            policy: crate::crypto::CryptoPolicy::Hybrid,
3598            relay: None,
3599            cached_subjects: std::sync::Arc::default(),
3600            internal_controller: None,
3601            federate_opt_in: false,
3602            audience: None,
3603            relay_resource_audience: None,
3604            unchecked_resource_selector: false,
3605        };
3606        let now = chrono::Utc::now().timestamp();
3607        // Local-issuer credentials must carry a credential ID (jti is a
3608        // REQUIRED profile claim); the hand-rolled composite helper does not
3609        // inject one, so set it explicitly.
3610        let claims = Claims::new("alice".to_owned(), now, now + 60)
3611            .with_issuer("https://local".to_owned())
3612            .with_jti()
3613            .with_client_id("hyprstream-oauth-client-1");
3614        for typ in crate::auth::RFC9068_ACCESS_TOKEN_TYPES {
3615            let header = format!(r#"{{"alg":"ML-DSA-65-Ed25519","typ":"{typ}","kid":"{kid_a}"}}"#);
3616            let valid = composite_token(&header, &claims, &pq_a, &ed_a, false);
3617            assert!(
3618                svc.verify_claims(&mut ctx_with_token(valid, false))
3619                    .await
3620                    .is_ok(),
3621                "rejected RFC 9068 access-token type {typ}"
3622            );
3623        }
3624
3625        let valid_header =
3626            format!(r#"{{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt","kid":"{kid_a}"}}"#);
3627
3628        // Exact-one session parsing (v16 §3.3) at the PRIMARY verify boundary: a
3629        // local credential carrying BOTH `sid` and `workload_session_id` is
3630        // ambiguous and rejected before any authorization — an active OIDC sid
3631        // must never mask a revoked/unknown workload session.
3632        let both_sessions = Claims::new("alice".to_owned(), now, now + 60)
3633            .with_issuer("https://local".to_owned())
3634            .with_jti()
3635            .with_sid("s1")
3636            .with_workload_session_id("w1");
3637        let ambiguous_token = composite_token(&valid_header, &both_sessions, &pq_a, &ed_a, false);
3638        let ambiguous_err = svc
3639            .verify_claims(&mut ctx_with_token(ambiguous_token, false))
3640            .await
3641            .expect_err("a credential carrying both sid and workload_session_id must be rejected");
3642        assert!(
3643            ambiguous_err
3644                .to_string()
3645                .contains("malformed session claims"),
3646            "unexpected error for ambiguous session claims: {ambiguous_err}"
3647        );
3648
3649        let mutations = [
3650            (
3651                r#"{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt"}"#.to_owned(),
3652                false,
3653            ),
3654            (
3655                r#"{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt","kid":"unknown"}"#.to_owned(),
3656                false,
3657            ),
3658            (
3659                format!(r#"{{"alg":"ML-DSA-65-Ed25519","typ":"JWT","kid":"{kid_a}"}}"#),
3660                false,
3661            ),
3662            (
3663                format!(r#"{{"alg":"ML-DSA-65-Ed25519","kid":"{kid_a}"}}"#),
3664                false,
3665            ),
3666            (
3667                format!(r#"{{"alg":"ML-DSA-65-Ed25519","typ":7,"kid":"{kid_a}"}}"#),
3668                false,
3669            ),
3670            (
3671                format!(r#"{{"alg":"ML-DSA-65-Ed25519","typ":"AT+JWT","kid":"{kid_a}"}}"#),
3672                false,
3673            ),
3674            (
3675                format!(r#"{{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt ","kid":"{kid_a}"}}"#),
3676                false,
3677            ),
3678            (
3679                format!(
3680                    r#"{{"alg":"ML-DSA-65-Ed25519","typ":"Application/at+jwt","kid":"{kid_a}"}}"#
3681                ),
3682                false,
3683            ),
3684            (
3685                format!(
3686                    r#"{{"alg":"ML-DSA-65-Ed25519","typ":"application/AT+JWT","kid":"{kid_a}"}}"#
3687                ),
3688                false,
3689            ),
3690            (
3691                format!(
3692                    r#"{{"alg":"ML-DSA-65-Ed25519","typ":"application/at+jwt ","kid":"{kid_a}"}}"#
3693                ),
3694                false,
3695            ),
3696            (
3697                format!(r#"{{"alg":"EdDSA","typ":"at+jwt","kid":"{kid_a}"}}"#),
3698                false,
3699            ),
3700            (
3701                format!(
3702                    r#"{{"alg":"EdDSA","alg":"ML-DSA-65-Ed25519","typ":"at+jwt","kid":"{kid_a}"}}"#
3703                ),
3704                false,
3705            ),
3706            (
3707                format!(
3708                    r#"{{"alg":"ML-DSA-65-Ed25519","alg":"EdDSA","typ":"at+jwt","kid":"{kid_a}"}}"#
3709                ),
3710                false,
3711            ),
3712            (
3713                format!(
3714                    r#"{{"alg":"ML-DSA-65-Ed25519","typ":"JWT","typ":"at+jwt","kid":"{kid_a}"}}"#
3715                ),
3716                false,
3717            ),
3718            (
3719                format!(
3720                    r#"{{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt","typ":"JWT","kid":"{kid_a}"}}"#
3721                ),
3722                false,
3723            ),
3724            (
3725                format!(
3726                    r#"{{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt","kid":"other","kid":"{kid_a}"}}"#
3727                ),
3728                false,
3729            ),
3730            (
3731                format!(
3732                    r#"{{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt","kid":"{kid_a}","kid":"other"}}"#
3733                ),
3734                false,
3735            ),
3736            (
3737                format!(
3738                    r#"{{"alg":"ML-DSA-65-Ed25519","typ":"at+jwt","kid":"{kid_a}","crit":["exp"]}}"#
3739                ),
3740                false,
3741            ),
3742            (valid_header.clone(), true),
3743        ];
3744        for (header, half) in mutations {
3745            let token = composite_token(&header, &claims, &pq_a, &ed_a, half);
3746            assert!(
3747                svc.verify_claims(&mut ctx_with_token(token, false))
3748                    .await
3749                    .is_err(),
3750                "accepted {header}"
3751            );
3752        }
3753
3754        let cross = composite_token(&valid_header, &claims, &pq_a, &ed_b, false);
3755        assert!(svc
3756            .verify_claims(&mut ctx_with_token(cross, false))
3757            .await
3758            .is_err());
3759
3760        let missing_issuer = Claims::new("alice".to_owned(), now, now + 60);
3761        let token = composite_token(&valid_header, &missing_issuer, &pq_a, &ed_a, false);
3762        assert!(svc
3763            .verify_claims(&mut ctx_with_token(token, false))
3764            .await
3765            .is_err());
3766        let wrong_issuer = claims.clone().with_issuer("https://other".to_owned());
3767        let token = composite_token(&valid_header, &wrong_issuer, &pq_a, &ed_a, false);
3768        assert!(svc
3769            .verify_claims(&mut ctx_with_token(token, false))
3770            .await
3771            .is_err());
3772    }
3773
3774    #[test]
3775    fn constructor_provenance_flags() {
3776        // from_callback_service is a genuine in-process self-call.
3777        let cb = EnvelopeContext::from_callback_service(1, "inference");
3778        assert!(cb.is_local_caller());
3779    }
3780}
3781
3782/// Service-to-service IPC identity resolution (#446).
3783///
3784/// A signed IPC request carries the caller's verified Ed25519 signer pubkey in
3785/// `cnf` (the `AnySigner` plane used by UDS/iroh verifies the COSE composite
3786/// against it). Without a JWT, `verify_claims` must map that key to its
3787/// authoritative `service:<name>` subject via the process-global key→subject
3788/// resolver (the trust-store seam installed under #441) — instead of falling
3789/// back to `anonymous`. A genuinely anonymous caller (unregistered key) must
3790/// STILL resolve to `anonymous` so policy-gated writes stay denied (fail-closed).
3791#[cfg(test)]
3792#[allow(clippy::unwrap_used, clippy::expect_used)]
3793mod ipc_key_identity_tests {
3794    use super::*;
3795    use crate::auth::key_subject_resolver::{set_global as set_key_resolver, KeySubjectResolver};
3796    use crate::transport::TransportConfig;
3797    use ed25519_dalek::SigningKey;
3798    use std::collections::HashMap;
3799    // Async-aware mutex: these tests hold the serialization guard across
3800    // `verify_claims(..).await`, so a std/parking_lot guard would trip
3801    // clippy's `await_holding_lock` (a real deadlock-risk lint). `tokio::sync::Mutex`
3802    // is designed to be held across `.await`. (#468)
3803    use tokio::sync::Mutex;
3804
3805    /// Serializes tests that install the process-global key→subject resolver.
3806    static RESOLVER_LOCK: Mutex<()> = Mutex::const_new(());
3807
3808    /// Minimal service that uses the DEFAULT `resolve_key_subject` (the #446
3809    /// seam under test) — it does not override identity resolution.
3810    struct PlainService {
3811        signing_key: SigningKey,
3812        transport: TransportConfig,
3813    }
3814
3815    #[async_trait(?Send)]
3816    impl RequestService for PlainService {
3817        async fn handle_request(
3818            &self,
3819            _ctx: &EnvelopeContext,
3820            _body: &crate::service::DecodedRequestBody,
3821        ) -> Result<(Vec<u8>, Option<Continuation>)> {
3822            Ok((vec![], None))
3823        }
3824        fn decode_request_body(
3825            &self,
3826            signed_body: &[u8],
3827        ) -> Result<crate::service::DecodedRequestBody> {
3828            Ok(crate::service::DecodedRequestBody::opaque(
3829                signed_body.to_vec(),
3830            ))
3831        }
3832        fn name(&self) -> &str {
3833            "discovery"
3834        }
3835        fn transport(&self) -> &TransportConfig {
3836            &self.transport
3837        }
3838        fn signing_key(&self) -> SigningKey {
3839            self.signing_key.clone()
3840        }
3841        fn pq_signing_key(&self) -> Option<crate::crypto::pq::MlDsaSigningKey> {
3842            None
3843        }
3844    }
3845
3846    /// Test resolver mapping a fixed set of pubkeys → subjects (the trust store
3847    /// stand-in). Unknown keys resolve to `None`.
3848    struct MapResolver {
3849        bindings: HashMap<[u8; 32], String>,
3850    }
3851
3852    impl KeySubjectResolver for MapResolver {
3853        fn resolve_subject(&self, signer_pubkey: &[u8; 32]) -> Option<Subject> {
3854            self.bindings
3855                .get(signer_pubkey)
3856                .map(|s| Subject::new(s.clone()))
3857        }
3858    }
3859
3860    /// Build a no-JWT context whose `cnf` is the given signer pubkey (the
3861    /// AnySigner/UDS plane: identity carried only by the verified signer key).
3862    fn ctx_for_signer(signer_pubkey: [u8; 32]) -> EnvelopeContext {
3863        EnvelopeContext {
3864            request_id: 1,
3865            claims: None,
3866            verified_tenant: None,
3867            jwt_token: None,
3868            direct_jwt_verified: false,
3869            delegated_resource_audience: false,
3870            deferred_federate: None,
3871            federate_tui_class: false,
3872            federate_holder_ed: None,
3873            federate_request_use: None,
3874            delegation_token: None,
3875            key_derived_subject: Subject::anonymous(),
3876            jwt_subject: None,
3877            cnf: signer_pubkey,
3878            envelope_wit_hash: None,
3879            client_dh_public: None,
3880            client_kem_public: None,
3881            request_iat: 0,
3882            request_nonce: [0; 16],
3883            response_kem_recipient: None,
3884            service_domain: None,
3885            envelope_proof_cwt: None,
3886            original_holder_evidence: None,
3887            browser_method_discriminator: None,
3888            internal_work: None,
3889            // AnySigner / networked-or-UDS plane.
3890            is_local_caller: false,
3891        }
3892    }
3893
3894    #[tokio::test]
3895    async fn registered_service_key_resolves_as_service_subject() {
3896        let _guard = RESOLVER_LOCK.lock().await;
3897
3898        let caller = SigningKey::from_bytes(&[11u8; 32]);
3899        let caller_pub = caller.verifying_key().to_bytes();
3900
3901        // Trust store has the caller's key bound to service:discovery (#441).
3902        let mut bindings = HashMap::new();
3903        bindings.insert(caller_pub, "service:discovery".to_owned());
3904        set_key_resolver(std::sync::Arc::new(MapResolver { bindings }));
3905
3906        let svc = PlainService {
3907            signing_key: SigningKey::from_bytes(&[22u8; 32]),
3908            transport: TransportConfig::inproc("discovery"),
3909        };
3910
3911        let mut ctx = ctx_for_signer(caller_pub);
3912        svc.verify_claims(&mut ctx).await.expect("verify_claims ok");
3913
3914        // The signed IPC caller resolves as its authoritative service identity,
3915        // NOT anonymous — so the existing discovery:* grant applies.
3916        assert_eq!(ctx.subject().to_string(), "service:discovery");
3917        assert!(!ctx.subject().is_anonymous());
3918    }
3919
3920    #[tokio::test]
3921    async fn unregistered_key_stays_anonymous() {
3922        let _guard = RESOLVER_LOCK.lock().await;
3923
3924        // Resolver knows ONLY about some other (registered) key.
3925        let registered = SigningKey::from_bytes(&[33u8; 32])
3926            .verifying_key()
3927            .to_bytes();
3928        let mut bindings = HashMap::new();
3929        bindings.insert(registered, "service:discovery".to_owned());
3930        set_key_resolver(std::sync::Arc::new(MapResolver { bindings }));
3931
3932        let svc = PlainService {
3933            signing_key: SigningKey::from_bytes(&[22u8; 32]),
3934            transport: TransportConfig::inproc("discovery"),
3935        };
3936
3937        // A genuinely anonymous caller signs with an UNREGISTERED key.
3938        let anon_pub = SigningKey::from_bytes(&[44u8; 32])
3939            .verifying_key()
3940            .to_bytes();
3941        let mut ctx = ctx_for_signer(anon_pub);
3942        svc.verify_claims(&mut ctx).await.expect("verify_claims ok");
3943
3944        // Fail-closed: no registered binding → anonymous → still denied writes.
3945        assert!(ctx.subject().is_anonymous());
3946        assert_eq!(ctx.subject().to_string(), "anonymous");
3947    }
3948
3949    #[tokio::test]
3950    async fn no_jwt_recovery_cannot_resurrect_did_unknown() {
3951        let _guard = RESOLVER_LOCK.lock().await;
3952
3953        let caller_pub = SigningKey::from_bytes(&[55u8; 32])
3954            .verifying_key()
3955            .to_bytes();
3956        let mut bindings = HashMap::new();
3957        bindings.insert(
3958            caller_pub,
3959            crate::identity::UNAUTHENTICATED_DID_SENTINEL.to_owned(),
3960        );
3961        set_key_resolver(std::sync::Arc::new(MapResolver { bindings }));
3962
3963        let svc = PlainService {
3964            signing_key: SigningKey::from_bytes(&[22u8; 32]),
3965            transport: TransportConfig::inproc("discovery"),
3966        };
3967        let mut ctx = ctx_for_signer(caller_pub);
3968
3969        svc.verify_claims(&mut ctx)
3970            .await
3971            .expect("reserved recovery binding must collapse to the unauthenticated floor");
3972
3973        assert!(ctx.subject().is_anonymous());
3974        assert_ne!(
3975            ctx.subject().name(),
3976            Some(crate::identity::UNAUTHENTICATED_DID_SENTINEL)
3977        );
3978    }
3979}
3980
3981#[cfg(test)]
3982mod stripping_defense_tests {
3983    use super::{composite_alg_components, jwt_alg_satisfies_policy};
3984    use crate::crypto::CryptoPolicy;
3985
3986    /// stripping_composite_covers_components:
3987    /// `ML-DSA-65-Ed25519` (composite) MUST cover both component algs so a
3988    /// JWKS that lists both `EdDSA` and `ML-DSA-65` under one kid still
3989    /// accepts a composite-signed token.
3990    #[test]
3991    fn stripping_composite_covers_components() {
3992        let c = composite_alg_components("ML-DSA-65-Ed25519");
3993        assert!(c.contains(&"ML-DSA-65"));
3994        assert!(c.contains(&"EdDSA"));
3995        assert!(c.contains(&"ML-DSA-65-Ed25519"));
3996    }
3997
3998    /// stripping_eddsa_does_not_cover_ml_dsa:
3999    /// Classical-only EdDSA must NOT cover ML-DSA-65; this is the core
4000    /// stripping defense — an attacker presenting an EdDSA JWT under a kid
4001    /// that the JWKS lists with ML-DSA-65 (or composite) must be rejected.
4002    #[test]
4003    fn stripping_eddsa_does_not_cover_ml_dsa() {
4004        let c = composite_alg_components("EdDSA");
4005        assert!(!c.contains(&"ML-DSA-65"));
4006        assert!(!c.contains(&"ML-DSA-65-Ed25519"));
4007    }
4008
4009    /// stripping_unknown_alg_is_empty:
4010    /// Unknown algs return an empty component list so the verifier's
4011    /// "all-covered" check fails closed.
4012    #[test]
4013    fn stripping_unknown_alg_is_empty() {
4014        assert!(composite_alg_components("HS256").is_empty());
4015        assert!(composite_alg_components("none").is_empty());
4016    }
4017
4018    // ── Fu4/#677: CryptoPolicy-driven minimum-alg gate ──────────────────────
4019
4020    /// Under Classical policy every alg passes the gate (per-alg decoders do
4021    /// the real checking); the gate is a no-op floor there.
4022    #[test]
4023    fn fu4_classical_accepts_any_alg() {
4024        for alg in ["EdDSA", "ML-DSA-65", "ML-DSA-65-Ed25519", "ES256", "RS256"] {
4025            assert!(
4026                jwt_alg_satisfies_policy(CryptoPolicy::Classical, alg).is_ok(),
4027                "Classical policy must not gate alg {alg}"
4028            );
4029        }
4030    }
4031
4032    /// Under Hybrid policy a classical-only (`EdDSA`) JWT is rejected even
4033    /// though a kid would resolve — the floor Fu4 adds, independent of JWKS
4034    /// `kid_algs` hygiene. ES256/RS256 are likewise classical and rejected.
4035    #[test]
4036    fn fu4_hybrid_rejects_classical_only_alg() {
4037        for alg in ["EdDSA", "ES256", "RS256", "none", "HS256"] {
4038            assert!(
4039                jwt_alg_satisfies_policy(CryptoPolicy::Hybrid, alg).is_err(),
4040                "Hybrid policy must reject classical-only alg {alg}"
4041            );
4042        }
4043    }
4044
4045    /// Under Hybrid policy the post-quantum algs (ML-DSA-65, composite) pass
4046    /// the gate and proceed to per-alg verification.
4047    #[test]
4048    fn fu4_hybrid_accepts_pq_algs() {
4049        for alg in ["ML-DSA-65", "ML-DSA-65-Ed25519"] {
4050            assert!(
4051                jwt_alg_satisfies_policy(CryptoPolicy::Hybrid, alg).is_ok(),
4052                "Hybrid policy must accept post-quantum alg {alg}"
4053            );
4054        }
4055    }
4056
4057    /// A freshly minted hybrid service WIT — the exact pair (derived ML-DSA,
4058    /// CA Ed25519) a clean bootstrap signs with — passes the Hybrid alg gate
4059    /// and round-trips through the real dispatch verification: header-alg
4060    /// gate, composite dispatch, key-source pair resolution, and composite
4061    /// decode. An unknown composite kid still fails to resolve.
4062    #[allow(clippy::unwrap_used, clippy::expect_used)]
4063    #[test]
4064    fn hybrid_service_jwt_passes_gate_and_dispatch_verification() {
4065        use crate::auth::{jwt, ClusterKeySource, JwtKeySource};
4066
4067        let ca_ed = ed25519_dalek::SigningKey::from_bytes(&[0x61; 32]);
4068        let ca_pq = crate::node_identity::derive_mesh_mldsa_key(&ca_ed);
4069        let ca_pq_vk = crate::crypto::pq::ml_dsa_sk_to_vk(&ca_pq);
4070
4071        let issuer = "http://localhost:9080";
4072        let now = chrono::Utc::now().timestamp();
4073        let claims = crate::auth::Claims::new("service:discovery".to_owned(), now, now + 3600)
4074            .with_issuer(issuer.to_owned());
4075        let token = jwt::encode_service_jwt_hybrid(&claims, &ca_ed, &ca_pq, &ca_pq_vk);
4076
4077        // The minted alg satisfies the Hybrid policy floor.
4078        let alg = jwt::header_alg(&token).unwrap().unwrap();
4079        assert!(jwt_alg_satisfies_policy(CryptoPolicy::Hybrid, &alg).is_ok());
4080
4081        // The dispatch path resolves the composite kid to BOTH halves and the
4082        // token verifies against them.
4083        let key_source = ClusterKeySource::new(ca_ed.verifying_key(), issuer.to_owned())
4084            .with_ca_composite_key(ca_pq_vk.clone());
4085        let dispatch = crate::auth::parse_composite_dispatch(&token, &["wit+jwt"]).unwrap();
4086        let pair = key_source
4087            .composite_pair(dispatch.kid())
4088            .expect("CA composite kid must resolve on the dispatch plane");
4089        let verified =
4090            jwt::decode_composite(&token, pair.ml_dsa(), pair.ed25519(), None, &dispatch)
4091                .expect("hybrid service JWT must verify with the resolved pair");
4092        assert_eq!(verified.sub, "service:discovery");
4093
4094        // Unknown kids stay unresolvable — fail closed.
4095        assert!(key_source.composite_pair("some-other-kid").is_none());
4096    }
4097}
4098
4099/// Accounting (#445): the **A** of AAA. `EnvelopeContext::audit_authz` is the
4100/// single chokepoint generated dispatch uses to attribute every authorization
4101/// decision to the cryptographically-verified subject. These tests capture the
4102/// emitted `tracing` events and assert the structured audit record carries the
4103/// right subject + decision for an ALLOWED and a DENIED request.
4104#[cfg(test)]
4105#[allow(clippy::unwrap_used, clippy::expect_used)]
4106mod accounting_audit_tests {
4107    use super::*;
4108    // parking_lot::Mutex — std::sync::Mutex is workspace-disallowed (clippy.toml).
4109    // Held only synchronously here (no `.await` across the guard). (#468)
4110    use parking_lot::Mutex;
4111    use std::sync::Arc;
4112    use tracing::field::{Field, Visit};
4113    use tracing::subscriber::with_default;
4114    use tracing_subscriber::layer::{Context, Layer, SubscriberExt};
4115    use tracing_subscriber::Registry;
4116
4117    /// One captured audit record (the structured fields we care about).
4118    #[derive(Default, Debug, Clone)]
4119    struct AuditRecord {
4120        target: String,
4121        subject: String,
4122        resource: String,
4123        action: String,
4124        decision: String,
4125    }
4126
4127    /// A `tracing` layer that records every event on the `audit` target into a
4128    /// shared buffer so the test can assert on the structured fields.
4129    struct CaptureLayer {
4130        records: Arc<Mutex<Vec<AuditRecord>>>,
4131    }
4132
4133    struct FieldVisitor<'a>(&'a mut AuditRecord);
4134
4135    impl Visit for FieldVisitor<'_> {
4136        fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
4137            // %Display fields arrive here as Debug of the formatted string; strip
4138            // surrounding quotes that the Debug formatter may add.
4139            let raw = format!("{value:?}");
4140            let val = raw.trim_matches('"').to_owned();
4141            match field.name() {
4142                "subject" => self.0.subject = val,
4143                "resource" => self.0.resource = val,
4144                "action" => self.0.action = val,
4145                "decision" => self.0.decision = val,
4146                _ => {}
4147            }
4148        }
4149        fn record_str(&mut self, field: &Field, value: &str) {
4150            match field.name() {
4151                "subject" => self.0.subject = value.to_owned(),
4152                "resource" => self.0.resource = value.to_owned(),
4153                "action" => self.0.action = value.to_owned(),
4154                "decision" => self.0.decision = value.to_owned(),
4155                _ => {}
4156            }
4157        }
4158    }
4159
4160    impl<S: tracing::Subscriber> Layer<S> for CaptureLayer {
4161        fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
4162            let mut rec = AuditRecord {
4163                target: event.metadata().target().to_owned(),
4164                ..Default::default()
4165            };
4166            event.record(&mut FieldVisitor(&mut rec));
4167            self.records.lock().push(rec);
4168        }
4169    }
4170
4171    /// Build a context whose verified subject is the given username (the
4172    /// key-derived path, i.e. cryptographically proven, not caller-asserted).
4173    fn ctx_for_user(name: &str) -> EnvelopeContext {
4174        EnvelopeContext {
4175            request_id: 42,
4176            claims: None,
4177            verified_tenant: None,
4178            jwt_token: None,
4179            direct_jwt_verified: false,
4180            delegated_resource_audience: false,
4181            deferred_federate: None,
4182            federate_tui_class: false,
4183            federate_holder_ed: None,
4184            federate_request_use: None,
4185            delegation_token: None,
4186            key_derived_subject: Subject::new(name),
4187            jwt_subject: None,
4188            cnf: [0u8; 32],
4189            envelope_wit_hash: None,
4190            client_dh_public: None,
4191            client_kem_public: None,
4192            request_iat: 0,
4193            request_nonce: [0; 16],
4194            response_kem_recipient: None,
4195            service_domain: None,
4196            envelope_proof_cwt: None,
4197            original_holder_evidence: None,
4198            browser_method_discriminator: None,
4199            internal_work: None,
4200            is_local_caller: true,
4201        }
4202    }
4203
4204    fn capture<F: FnOnce()>(f: F) -> Vec<AuditRecord> {
4205        let records = Arc::new(Mutex::new(Vec::new()));
4206        let layer = CaptureLayer {
4207            records: records.clone(),
4208        };
4209        let subscriber = Registry::default().with(layer);
4210        with_default(subscriber, f);
4211        let out = records.lock().clone();
4212        out
4213    }
4214
4215    #[test]
4216    fn audit_emits_allow_with_verified_subject() {
4217        let ctx = ctx_for_user("testuser");
4218        let records = capture(|| {
4219            ctx.audit_authz("registry:*", "write", /* allowed */ true);
4220        });
4221
4222        let audit: Vec<_> = records.iter().filter(|r| r.target == "audit").collect();
4223        assert_eq!(
4224            audit.len(),
4225            1,
4226            "exactly one audit record expected: {records:?}"
4227        );
4228        let r = audit[0];
4229        assert_eq!(
4230            r.subject, "testuser",
4231            "subject must be the verified subject"
4232        );
4233        assert_eq!(r.resource, "registry:*");
4234        assert_eq!(r.action, "write");
4235        assert_eq!(r.decision, "allow");
4236    }
4237
4238    #[test]
4239    fn audit_emits_deny_with_verified_subject() {
4240        // anonymous denied a write — the security-relevant deny path.
4241        let ctx = EnvelopeContext {
4242            request_id: 7,
4243            claims: None,
4244            verified_tenant: None,
4245            jwt_token: None,
4246            direct_jwt_verified: false,
4247            delegated_resource_audience: false,
4248            deferred_federate: None,
4249            federate_tui_class: false,
4250            federate_holder_ed: None,
4251            federate_request_use: None,
4252            delegation_token: None,
4253            key_derived_subject: Subject::anonymous(),
4254            jwt_subject: None,
4255            cnf: [0u8; 32],
4256            envelope_wit_hash: None,
4257            client_dh_public: None,
4258            client_kem_public: None,
4259            request_iat: 0,
4260            request_nonce: [0; 16],
4261            response_kem_recipient: None,
4262            service_domain: None,
4263            envelope_proof_cwt: None,
4264            original_holder_evidence: None,
4265            browser_method_discriminator: None,
4266            internal_work: None,
4267            is_local_caller: false,
4268        };
4269        let records = capture(|| {
4270            ctx.audit_authz("registry:*", "write", /* allowed */ false);
4271        });
4272
4273        let audit: Vec<_> = records.iter().filter(|r| r.target == "audit").collect();
4274        assert_eq!(
4275            audit.len(),
4276            1,
4277            "exactly one audit record expected: {records:?}"
4278        );
4279        let r = audit[0];
4280        assert_eq!(
4281            r.subject, "anonymous",
4282            "anonymous deny must be attributed as 'anonymous'"
4283        );
4284        assert_eq!(r.resource, "registry:*");
4285        assert_eq!(r.action, "write");
4286        assert_eq!(r.decision, "deny");
4287    }
4288
4289    #[test]
4290    fn audit_attributes_authenticated_deny() {
4291        // An authenticated-but-unprivileged subject denied a write is still
4292        // attributable to that subject (who attempted what).
4293        let ctx = ctx_for_user("viewer-probe");
4294        let records = capture(|| {
4295            ctx.audit_authz("registry:*", "write", /* allowed */ false);
4296        });
4297        let r = records
4298            .iter()
4299            .find(|r| r.target == "audit")
4300            .expect("audit record");
4301        assert_eq!(r.subject, "viewer-probe");
4302        assert_eq!(r.decision, "deny");
4303    }
4304
4305    // ── S8 (#574): verified_key_material() + two-input security_context() ──
4306
4307    use crate::auth::mac::{Assurance, CompartmentSet, Level, SecurityLabel, VerifiedKeyMaterial};
4308    use crate::crypto::pq::ml_dsa_generate_keypair;
4309    use crate::envelope::{install_verify_config, KeyedPqTrustStore};
4310    use ed25519_dalek::SigningKey;
4311    use rand::rngs::OsRng;
4312
4313    /// Build a context with a specific `cnf` (the cryptographically-verified
4314    /// Ed25519 signer key) and optional clearance claims.
4315    fn ctx_with_cnf(cnf: [u8; 32], clearance: Option<SecurityLabel>) -> EnvelopeContext {
4316        let claims =
4317            clearance.map(|c| crate::auth::Claims::new("sub".to_owned(), 1, 2).with_clearance(c));
4318        EnvelopeContext {
4319            request_id: 1,
4320            claims,
4321            verified_tenant: None,
4322            jwt_token: None,
4323            direct_jwt_verified: false,
4324            delegated_resource_audience: false,
4325            deferred_federate: None,
4326            federate_tui_class: false,
4327            federate_holder_ed: None,
4328            federate_request_use: None,
4329            delegation_token: None,
4330            key_derived_subject: Subject::anonymous(),
4331            jwt_subject: None,
4332            cnf,
4333            envelope_wit_hash: None,
4334            client_dh_public: None,
4335            client_kem_public: None,
4336            request_iat: 0,
4337            request_nonce: [0; 16],
4338            response_kem_recipient: None,
4339            service_domain: None,
4340            envelope_proof_cwt: None,
4341            original_holder_evidence: None,
4342            browser_method_discriminator: None,
4343            internal_work: None,
4344            is_local_caller: false,
4345        }
4346    }
4347
4348    /// A zeroed cnf (the callback-service shape) ⇒ Unverified assurance.
4349    #[test]
4350    fn verified_key_material_zeroed_cnf_is_unverified() {
4351        let ctx = ctx_with_cnf([0u8; 32], None);
4352        assert_eq!(ctx.verified_key_material(), VerifiedKeyMaterial::Unverified);
4353    }
4354
4355    /// A non-zero cnf with NO bound PQ anchor ⇒ Classical (the federation edge).
4356    /// NOT PqHybrid — no silent upgrade.
4357    #[test]
4358    fn verified_key_material_verified_cnf_no_anchor_is_classical() {
4359        let ed = SigningKey::generate(&mut OsRng);
4360        let cnf = ed.verifying_key().to_bytes();
4361        // No global PQ store installed in this test process (or none binding
4362        // this key) ⇒ Classical.
4363        let ctx = ctx_with_cnf(cnf, None);
4364        // The global store may or may not be installed by another test; the
4365        // invariant we assert is that it is NOT PqHybrid (no anchor for a
4366        // random key).
4367        let km = ctx.verified_key_material();
4368        assert_ne!(
4369            km,
4370            VerifiedKeyMaterial::PqHybrid,
4371            "a key with no bound PQ anchor must never derive PqHybrid"
4372        );
4373        let _ = ed; // suppress unused warning when the assertion path differs
4374    }
4375
4376    /// A non-zero cnf WITH a bound PQ anchor (under Hybrid) ⇒ PqHybrid. This is
4377    /// the activation: the assurance derived from the kid-anchored PQ binding.
4378    #[test]
4379    fn verified_key_material_bound_pq_anchor_is_pqhybrid() {
4380        let ed = SigningKey::generate(&mut OsRng);
4381        let cnf = ed.verifying_key().to_bytes();
4382        let (_pq_sk, pq_vk) = ml_dsa_generate_keypair();
4383
4384        // Install a global verify config with a PQ store binding this key.
4385        // `install_verify_config` is first-write-wins; if another test already
4386        // installed one this is a no-op and we verify against whatever store is
4387        // present. To make this test hermetic we use a dedicated store and rely
4388        // on the global accessor. If a store is already installed we cannot
4389        // rebind, so we assert the weaker but still-load-bearing property:
4390        // the accessor returns Classical OR PqHybrid (never Unverified for a
4391        // verified cnf), and is deterministic.
4392        let mut store = KeyedPqTrustStore::new();
4393        store.bind(cnf, &pq_vk);
4394        let _ = install_verify_config(crate::envelope::EnvelopeVerifyConfig {
4395            policy: crate::crypto::CryptoPolicy::Hybrid,
4396            pq_store: Some(std::sync::Arc::new(store)),
4397        });
4398        let ctx = ctx_with_cnf(cnf, None);
4399        let km = ctx.verified_key_material();
4400        // The verified cnf is never Unverified. If our install won (no prior
4401        // config) it is PqHybrid; if a prior test's config is in force it is at
4402        // worst Classical. Either way: NOT Unverified.
4403        assert_ne!(
4404            km,
4405            VerifiedKeyMaterial::Unverified,
4406            "a verified cnf must never derive Unverified"
4407        );
4408    }
4409
4410    /// Two-input ctx: clearance from Claims + assurance derived from the
4411    /// verified cnf. The global `PqTrustStore` is process-global (first-write-
4412    /// wins via `OnceLock`), so concurrent tests may own it; this test asserts
4413    /// the load-bearing invariants that hold regardless of which store won:
4414    /// (1) a verified cnf NEVER derives Unverified, and (2) the derived
4415    /// context's assurance is whatever the verified crypto supports (Classical
4416    /// if no anchor bound this key, PqHybrid if one did), NEVER higher than the
4417    /// clearance. The dedicated `classical_key_subject_clamped_and_denied_on_pq_object`
4418    /// test below pins the fail-closed direction hermetically.
4419    #[test]
4420    fn security_context_verified_cnf_never_unverified_never_exceeds_clearance() {
4421        let ed = SigningKey::generate(&mut OsRng);
4422        let cnf = ed.verifying_key().to_bytes();
4423        let (_pq_sk, pq_vk) = ml_dsa_generate_keypair();
4424        // Attempt to install a store binding this key. If another test already
4425        // installed one, this is a no-op and the lookup returns no anchor.
4426        let mut store = KeyedPqTrustStore::new();
4427        store.bind(cnf, &pq_vk);
4428        let _ = install_verify_config(crate::envelope::EnvelopeVerifyConfig {
4429            policy: crate::crypto::CryptoPolicy::Hybrid,
4430            pq_store: Some(std::sync::Arc::new(store)),
4431        });
4432
4433        let clearance =
4434            SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY);
4435        let ctx = ctx_with_cnf(cnf, Some(clearance));
4436        let sc = ctx
4437            .security_context()
4438            .expect("labeled subject has a context");
4439        assert_ne!(
4440            ctx.verified_key_material(),
4441            VerifiedKeyMaterial::Unverified,
4442            "a verified cnf must never derive Unverified"
4443        );
4444        assert!(
4445            sc.assurance() <= Assurance::PqHybrid,
4446            "assurance must never exceed the clearance"
4447        );
4448        assert_eq!(sc.level(), Level::Secret);
4449    }
4450
4451    /// **Fail-closed (the load-bearing #548 invariant):** a Classical-key
4452    /// subject (verified Ed25519, no bound PQ anchor) carrying a PqHybrid
4453    /// clearance MUST clamp to Classical assurance, and therefore MUST be
4454    /// DENIED on a PqHybrid-required object. No silent upgrade.
4455    #[test]
4456    fn classical_key_subject_clamped_and_denied_on_pq_object() {
4457        let ed = SigningKey::generate(&mut OsRng);
4458        let cnf = ed.verifying_key().to_bytes();
4459        // No PQ binding for this key in any store we install here. If a global
4460        // store happens to bind a random key that is astronomically improbable;
4461        // to be hermetic we install a store that does NOT bind this key.
4462        let store = KeyedPqTrustStore::new(); // empty
4463        let _ = install_verify_config(crate::envelope::EnvelopeVerifyConfig {
4464            policy: crate::crypto::CryptoPolicy::Hybrid,
4465            pq_store: Some(std::sync::Arc::new(store)),
4466        });
4467
4468        // Policy mistakenly assigned a PqHybrid clearance...
4469        let claimed_clearance =
4470            SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY);
4471        let ctx = ctx_with_cnf(cnf, Some(claimed_clearance));
4472        let sc = ctx
4473            .security_context()
4474            .expect("labeled subject has a context");
4475        // ...but the verified key is Classical, so assurance CLAMPS DOWN.
4476        assert_eq!(
4477            sc.assurance(),
4478            Assurance::Classical,
4479            "a Classical key must clamp a PqHybrid clearance down to Classical (no silent upgrade)"
4480        );
4481        // Consequently the MAC floor DENIES access to a PqHybrid object even
4482        // though the level (Secret) dominates.
4483        let pq_object =
4484            SecurityLabel::new(Level::Public, Assurance::PqHybrid, CompartmentSet::EMPTY);
4485        assert!(
4486            !sc.can_access(&pq_object),
4487            "Classical-assurance subject MUST be denied on a PqHybrid object (fail-closed)"
4488        );
4489    }
4490
4491    /// Unlabeled subject (no clearance claim) ⇒ `security_context()` returns
4492    /// None ⇒ the S1 monitor denies (no default clearance).
4493    #[test]
4494    fn unlabeled_subject_has_no_security_context() {
4495        let ed = SigningKey::generate(&mut OsRng);
4496        let cnf = ed.verifying_key().to_bytes();
4497        let ctx = ctx_with_cnf(cnf, None); // no clearance
4498        assert!(
4499            ctx.security_context().is_none(),
4500            "unlabeled subject must have no security context (S1 deny)"
4501        );
4502    }
4503}
4504
4505#[cfg(test)]
4506#[allow(clippy::expect_used)]
4507mod browser_method_commitment_tests {
4508    use super::EnvelopeContext;
4509
4510    #[test]
4511    fn browser_method_commitment_rejects_mismatch_and_accepts_match() {
4512        let mut ctx = EnvelopeContext::from_callback_service(7, "model");
4513        ctx.browser_method_discriminator = Some(3);
4514
4515        ctx.ensure_browser_method(3)
4516            .expect("matching generated method discriminator must pass");
4517        let error = ctx
4518            .ensure_browser_method(4)
4519            .expect_err("cross-method browser commitment must fail closed");
4520        assert!(error
4521            .to_string()
4522            .contains("browser method commitment 3 does not match decoded service method 4"));
4523    }
4524
4525    #[test]
4526    fn non_browser_context_preserves_legacy_dispatch_compatibility() {
4527        let ctx = EnvelopeContext::from_callback_service(7, "model");
4528        ctx.ensure_browser_method(u16::MAX)
4529            .expect("non-browser carriers have no method commitment to compare");
4530    }
4531}
4532
4533/// Internal execution work order (`iw+jwt`) routing tests — the
4534/// single-service Model→Inference boundary's GENERIC pipeline half.
4535///
4536/// The default service posture is deny: `iw+jwt` is authority at NO service
4537/// unless it explicitly operates a pinned execution boundary. The accepting
4538/// shape here mirrors the Inference subprocessor adapter (pinned controller
4539/// key + instance audience + single-use jti) and proves the pipeline installs
4540/// the ORIGINAL caller identity on the context.
4541#[cfg(test)]
4542#[allow(clippy::unwrap_used, clippy::expect_used)]
4543mod internal_work_routing_tests {
4544    use super::*;
4545    use crate::auth::internal_work::{
4546        encode_internal_work, InternalWorkClaims, INTERNAL_WORK_ISSUER,
4547    };
4548    use ed25519_dalek::SigningKey;
4549    use parking_lot::Mutex as PlMutex;
4550
4551    const CONTROLLER: [u8; 32] = [0xC7; 32];
4552    const STRANGER: [u8; 32] = [0xC9; 32];
4553
4554    struct BoundaryMockService {
4555        signing_key: SigningKey,
4556        transport: TransportConfig,
4557        key_source: std::sync::Arc<dyn crate::auth::JwtKeySource>,
4558        internal_controller: Option<ed25519_dalek::VerifyingKey>,
4559        _cached: std::sync::Arc<PlMutex<Vec<String>>>,
4560    }
4561
4562    impl BoundaryMockService {
4563        fn without_boundary() -> Self {
4564            Self {
4565                signing_key: SigningKey::from_bytes(&[8u8; 32]),
4566                transport: TransportConfig::inproc("boundary-mock"),
4567                key_source: std::sync::Arc::new(crate::auth::ClusterKeySource::new(
4568                    SigningKey::from_bytes(&[7u8; 32]).verifying_key(),
4569                    "http://127.0.0.1:1".to_owned(),
4570                )),
4571                internal_controller: None,
4572                _cached: std::sync::Arc::default(),
4573            }
4574        }
4575
4576        fn with_controller(controller: &SigningKey) -> Self {
4577            Self {
4578                internal_controller: Some(controller.verifying_key()),
4579                ..Self::without_boundary()
4580            }
4581        }
4582    }
4583
4584    #[async_trait(?Send)]
4585    impl RequestService for BoundaryMockService {
4586        async fn handle_request(
4587            &self,
4588            _ctx: &EnvelopeContext,
4589            _body: &crate::service::DecodedRequestBody,
4590        ) -> Result<(Vec<u8>, Option<Continuation>)> {
4591            Ok((vec![], None))
4592        }
4593        fn decode_request_body(
4594            &self,
4595            signed_body: &[u8],
4596        ) -> Result<crate::service::DecodedRequestBody> {
4597            Ok(crate::service::DecodedRequestBody::opaque(
4598                signed_body.to_vec(),
4599            ))
4600        }
4601        fn name(&self) -> &str {
4602            "boundary-mock"
4603        }
4604        fn transport(&self) -> &TransportConfig {
4605            &self.transport
4606        }
4607        fn signing_key(&self) -> SigningKey {
4608            self.signing_key.clone()
4609        }
4610        fn jwt_key_source(&self) -> Option<std::sync::Arc<dyn crate::auth::JwtKeySource>> {
4611            Some(self.key_source.clone())
4612        }
4613        fn require_cnf_binding(&self) -> bool {
4614            false
4615        }
4616        fn pq_signing_key(&self) -> Option<crate::crypto::pq::MlDsaSigningKey> {
4617            None
4618        }
4619        async fn verify_internal_work_bearer(
4620            &self,
4621            ctx: &EnvelopeContext,
4622            token: &str,
4623            _protected: &crate::auth::ProtectedHeader,
4624        ) -> anyhow::Result<crate::auth::internal_work::InternalWorkClaims> {
4625            let controller = self.internal_controller.as_ref().ok_or_else(|| {
4626                anyhow::anyhow!("internal work bearer is not accepted by this service")
4627            })?;
4628            anyhow::ensure!(
4629                ctx.cnf == controller.to_bytes(),
4630                "internal work bearer envelope was not signed by the pinned controller"
4631            );
4632            let now = chrono::Utc::now().timestamp();
4633            let claims = crate::auth::internal_work::verify_internal_work(
4634                token,
4635                controller,
4636                "mock-instance-1",
4637                now,
4638            )?;
4639            anyhow::ensure!(
4640                crate::auth::internal_work::admit_internal_work_jti_once(
4641                    &claims.jti,
4642                    claims.exp,
4643                    now,
4644                ),
4645                "internal work token jti was already admitted (replay)"
4646            );
4647            Ok(claims)
4648        }
4649    }
4650
4651    fn fixture_claims(controller: &SigningKey, aud: &str, now: i64) -> InternalWorkClaims {
4652        let caller = crate::auth::Claims::new("alice".to_owned(), now, now + 3600)
4653            .with_tenant("tenant-a".to_owned());
4654        InternalWorkClaims {
4655            iss: INTERNAL_WORK_ISSUER.to_owned(),
4656            sub: "alice".to_owned(),
4657            aud: aud.to_owned(),
4658            tenant: "tenant-a".to_owned(),
4659            model: "qwen3:main".to_owned(),
4660            resource: "inference:generateStream".to_owned(),
4661            operation: "infer".to_owned(),
4662            iat: now,
4663            exp: now + 60,
4664            jti: format!(
4665                "jti-{}-{}",
4666                hex::encode(&controller.verifying_key().as_bytes()[..4]),
4667                std::time::SystemTime::now()
4668                    .duration_since(std::time::UNIX_EPOCH)
4669                    .expect("clock")
4670                    .as_nanos(),
4671            ),
4672            cnf: InternalWorkClaims::controller_cnf(&controller.verifying_key()),
4673            owner_did: Some("did:key:z6Mktest".to_owned()),
4674            caller,
4675        }
4676    }
4677
4678    fn ctx_with_internal_token(token: String, cnf: [u8; 32]) -> EnvelopeContext {
4679        EnvelopeContext {
4680            request_id: 1,
4681            claims: None,
4682            verified_tenant: None,
4683            jwt_token: Some(token),
4684            direct_jwt_verified: false,
4685            delegated_resource_audience: false,
4686            deferred_federate: None,
4687            federate_tui_class: false,
4688            federate_holder_ed: None,
4689            federate_request_use: None,
4690            delegation_token: None,
4691            key_derived_subject: Subject::anonymous(),
4692            jwt_subject: None,
4693            cnf,
4694            envelope_wit_hash: None,
4695            client_dh_public: None,
4696            client_kem_public: None,
4697            request_iat: 0,
4698            request_nonce: [0; 16],
4699            response_kem_recipient: None,
4700            service_domain: None,
4701            envelope_proof_cwt: None,
4702            original_holder_evidence: None,
4703            browser_method_discriminator: None,
4704            internal_work: None,
4705            is_local_caller: false,
4706        }
4707    }
4708
4709    #[tokio::test]
4710    async fn internal_work_denied_at_default_service() {
4711        let controller = SigningKey::from_bytes(&CONTROLLER);
4712        let now = chrono::Utc::now().timestamp();
4713        let token = encode_internal_work(
4714            &fixture_claims(&controller, "mock-instance-1", now),
4715            &controller,
4716        );
4717        let svc = BoundaryMockService::without_boundary();
4718        let mut ctx = ctx_with_internal_token(token, controller.verifying_key().to_bytes());
4719        let error = svc
4720            .verify_claims(&mut ctx)
4721            .await
4722            .expect_err("iw+jwt must deny at a service that operates no execution boundary");
4723        assert!(error.to_string().contains("not accepted"), "{error:#}");
4724        assert!(ctx.claims().is_none(), "no claims may publish on denial");
4725        assert!(ctx.internal_work().is_none());
4726    }
4727
4728    #[tokio::test]
4729    async fn internal_work_admits_original_caller_at_pinned_boundary() {
4730        let controller = SigningKey::from_bytes(&CONTROLLER);
4731        let now = chrono::Utc::now().timestamp();
4732        let token = encode_internal_work(
4733            &fixture_claims(&controller, "mock-instance-1", now),
4734            &controller,
4735        );
4736        let svc = BoundaryMockService::with_controller(&controller);
4737        let mut ctx = ctx_with_internal_token(token, controller.verifying_key().to_bytes());
4738        svc.verify_claims(&mut ctx)
4739            .await
4740            .expect("the pinned controller's work order must be admitted");
4741        assert_eq!(
4742            ctx.subject().name(),
4743            Some("alice"),
4744            "original caller identity"
4745        );
4746        assert_eq!(ctx.verified_tenant(), Some("tenant-a"));
4747        assert_eq!(
4748            ctx.claims().map(|c| c.sub.as_str()),
4749            Some("alice"),
4750            "caller claims snapshot installed for subject-dependent semantics"
4751        );
4752        let work = ctx.internal_work().expect("work order installed");
4753        assert_eq!(work.resource, "inference:generateStream");
4754        assert_eq!(work.operation, "infer");
4755        assert_eq!(work.tenant, "tenant-a");
4756        assert_eq!(work.model, "qwen3:main");
4757        assert_eq!(work.owner_did.as_deref(), Some("did:key:z6Mktest"));
4758    }
4759
4760    #[tokio::test]
4761    async fn internal_work_rejected_from_foreign_envelope_signer() {
4762        let controller = SigningKey::from_bytes(&CONTROLLER);
4763        let stranger = SigningKey::from_bytes(&STRANGER);
4764        let now = chrono::Utc::now().timestamp();
4765        let token = encode_internal_work(
4766            &fixture_claims(&controller, "mock-instance-1", now),
4767            &controller,
4768        );
4769        let svc = BoundaryMockService::with_controller(&controller);
4770        // The token is genuine — but the ENVELOPE was signed by a stranger.
4771        let mut ctx = ctx_with_internal_token(token, stranger.verifying_key().to_bytes());
4772        let error = svc
4773            .verify_claims(&mut ctx)
4774            .await
4775            .expect_err("a stolen work order cannot be replayed under a foreign signer");
4776        assert!(error.to_string().contains("pinned controller"), "{error:#}");
4777        assert!(ctx.claims().is_none());
4778    }
4779
4780    // ── Sol S1: the resolved subject must survive admission EXACTLY ────────
4781    //
4782    // Model mints work.sub from the ALREADY-RESOLVED ctx.subject().to_string()
4783    // of the verified caller envelope. The legacy `Subject::from_str` parser
4784    // strips `local:`/`token:`/`peer:`/`user:` prefixes, so re-normalizing
4785    // here silently changed the principal (cross-principal state keyed at the
4786    // worker and mis-audit). These tests drive the REAL `verify_claims` in the
4787    // AnySigner serving shape (anonymous key-derived subject, so
4788    // `ctx.subject()` is exactly the installed jwt_subject).
4789
4790    fn work_ctx_with_subject(token: String, cnf: [u8; 32]) -> EnvelopeContext {
4791        ctx_with_internal_token(token, cnf)
4792    }
4793
4794    #[tokio::test]
4795    async fn sol_s1_prefixed_subject_survives_internal_work_admission_exactly() {
4796        let controller = SigningKey::from_bytes(&CONTROLLER);
4797        let now = chrono::Utc::now().timestamp();
4798        let mut claims = fixture_claims(&controller, "mock-instance-1", now);
4799        claims.sub = "user:alice".to_owned();
4800        claims.caller.sub = "user:alice".to_owned();
4801        let token = encode_internal_work(&claims, &controller);
4802        let svc = BoundaryMockService::with_controller(&controller);
4803        let mut ctx = work_ctx_with_subject(token, controller.verifying_key().to_bytes());
4804        svc.verify_claims(&mut ctx)
4805            .await
4806            .expect("the pinned controller's work order must be admitted");
4807        // The EXACT resolved identity — no legacy prefix normalization.
4808        assert_eq!(ctx.subject(), crate::envelope::Subject::new("user:alice"));
4809        assert_eq!(ctx.subject().name(), Some("user:alice"));
4810        assert_eq!(
4811            ctx.internal_work().expect("work order").subject,
4812            ctx.subject()
4813        );
4814        assert_eq!(ctx.claims().map(|c| c.sub.as_str()), Some("user:alice"));
4815        assert_eq!(ctx.verified_tenant(), Some("tenant-a"));
4816    }
4817
4818    #[tokio::test]
4819    async fn sol_s1_all_legacy_prefix_families_preserve_exact_identity() {
4820        let controller = SigningKey::from_bytes(&CONTROLLER);
4821        let svc = BoundaryMockService::with_controller(&controller);
4822        for subject_string in ["token:bob", "local:carol", "peer:dave", "user:dave#2"] {
4823            let now = chrono::Utc::now().timestamp();
4824            let mut claims = fixture_claims(&controller, "mock-instance-1", now);
4825            claims.sub = subject_string.to_owned();
4826            claims.caller.sub = subject_string.to_owned();
4827            claims.jti = format!(
4828                "jti-{}-{}",
4829                hex::encode(&controller.verifying_key().as_bytes()[..4]),
4830                std::time::SystemTime::now()
4831                    .duration_since(std::time::UNIX_EPOCH)
4832                    .expect("clock")
4833                    .as_nanos()
4834            );
4835            let token = encode_internal_work(&claims, &controller);
4836            let mut ctx = work_ctx_with_subject(token, controller.verifying_key().to_bytes());
4837            svc.verify_claims(&mut ctx)
4838                .await
4839                .unwrap_or_else(|error| panic!("{subject_string} must be admitted: {error:#}"));
4840            assert_eq!(
4841                ctx.subject(),
4842                crate::envelope::Subject::new(subject_string),
4843                "{subject_string} identity must survive admission verbatim"
4844            );
4845        }
4846    }
4847
4848    #[tokio::test]
4849    async fn sol_s1_bare_subject_remains_compatible() {
4850        let controller = SigningKey::from_bytes(&CONTROLLER);
4851        let now = chrono::Utc::now().timestamp();
4852        let claims = fixture_claims(&controller, "mock-instance-1", now); // sub "alice"
4853        let token = encode_internal_work(&claims, &controller);
4854        let svc = BoundaryMockService::with_controller(&controller);
4855        let mut ctx = work_ctx_with_subject(token, controller.verifying_key().to_bytes());
4856        svc.verify_claims(&mut ctx)
4857            .await
4858            .expect("bare subject stays admitted");
4859        assert_eq!(ctx.subject(), crate::envelope::Subject::new("alice"));
4860    }
4861
4862    #[tokio::test]
4863    async fn sol_s1_empty_anonymous_and_sentinel_subjects_deny() {
4864        let controller = SigningKey::from_bytes(&CONTROLLER);
4865        let svc = BoundaryMockService::with_controller(&controller);
4866        for bad in ["", "anonymous", UNAUTHENTICATED_DID_SENTINEL] {
4867            let now = chrono::Utc::now().timestamp();
4868            let mut claims = fixture_claims(&controller, "mock-instance-1", now);
4869            claims.sub = bad.to_owned();
4870            claims.caller.sub = bad.to_owned();
4871            claims.jti = format!(
4872                "jti-{}-{}",
4873                hex::encode(&controller.verifying_key().as_bytes()[..4]),
4874                std::time::SystemTime::now()
4875                    .duration_since(std::time::UNIX_EPOCH)
4876                    .expect("clock")
4877                    .as_nanos()
4878            );
4879            let token = encode_internal_work(&claims, &controller);
4880            let mut ctx = work_ctx_with_subject(token, controller.verifying_key().to_bytes());
4881            let error = svc
4882                .verify_claims(&mut ctx)
4883                .await
4884                .expect_err("a subject-less work order must deny");
4885            assert!(
4886                !error.to_string().is_empty(),
4887                "denial must carry the reason for {bad:?}"
4888            );
4889            assert!(ctx.claims().is_none());
4890            assert!(ctx.internal_work().is_none());
4891        }
4892    }
4893
4894    #[tokio::test]
4895    async fn internal_work_snapshot_subject_disagreement_denies() {
4896        // K3 finding m1: the controller authors both the subject and the
4897        // caller snapshot; production mints them identical (resolved form),
4898        // and admission enforces the coherence so audit and subject-keyed
4899        // state cannot diverge.
4900        let controller = SigningKey::from_bytes(&CONTROLLER);
4901        let now = chrono::Utc::now().timestamp();
4902        let mut claims = fixture_claims(&controller, "mock-instance-1", now);
4903        claims.caller.sub = "someone-else".to_owned();
4904        let token = encode_internal_work(&claims, &controller);
4905        let svc = BoundaryMockService::with_controller(&controller);
4906        let mut ctx = ctx_with_internal_token(token, controller.verifying_key().to_bytes());
4907        let error = svc
4908            .verify_claims(&mut ctx)
4909            .await
4910            .expect_err("an incoherent snapshot must deny");
4911        assert!(
4912            error.to_string().contains("snapshot subject disagrees"),
4913            "{error:#}"
4914        );
4915        assert!(ctx.claims().is_none());
4916        assert!(ctx.internal_work().is_none());
4917    }
4918
4919    #[tokio::test]
4920    async fn internal_work_replayed_jti_denies_on_second_admission() {
4921        let controller = SigningKey::from_bytes(&CONTROLLER);
4922        let now = chrono::Utc::now().timestamp();
4923        let token = encode_internal_work(
4924            &fixture_claims(&controller, "mock-instance-1", now),
4925            &controller,
4926        );
4927        let svc = BoundaryMockService::with_controller(&controller);
4928        let admit =
4929            |token: String| ctx_with_internal_token(token, controller.verifying_key().to_bytes());
4930        let mut first = admit(token.clone());
4931        svc.verify_claims(&mut first)
4932            .await
4933            .expect("first admission of a fresh work order");
4934        let mut second = admit(token);
4935        let error = svc
4936            .verify_claims(&mut second)
4937            .await
4938            .expect_err("the same work order jti must not admit twice");
4939        assert!(error.to_string().contains("replay"), "{error:#}");
4940        assert!(second.claims().is_none(), "no claims on replay denial");
4941    }
4942}