Skip to main content

hyprstream_rpc/service/
dispatch.rs

1//! Transport-neutral request dispatch core (#148).
2//!
3//! `process_request` is the single envelope-verify → JWT/DPoP → Casbin →
4//! `handle_request` → signed-response pipeline shared by every front-end:
5//! the ZMQ `RequestLoop`, the WebTransport server, and the generic RPC plane's
6//! `LocalServiceBridge`. It contains no transport-specific code (no ZMQ, no
7//! quinn) — extracted out of `transport/zmtp_quic.rs` so the ZMQ-specific
8//! remainder of that file can be deleted in #138 without touching this.
9
10use anyhow::{Context, Result};
11use capnp::message::Builder;
12use capnp::serialize;
13use tracing::{debug, error, warn};
14
15use crate::envelope::ResponseEnvelope;
16use crate::ToCapnp;
17
18/// Envelope signer verification mode (re-exported from `crate::envelope`).
19///
20/// - **FixedSigner**: internal service-to-service — envelope signer must match
21///   a known `server_pubkey` for mutual authentication. Peers pre-share keys.
22/// - **AnySigner**: external clients (e.g. browser over WebTransport) — any
23///   valid signer accepted; transport TLS provides peer authentication.
24pub use crate::envelope::EnvelopeVerification;
25
26/// The one externally visible pre-handler denial (§14.2 `DispatchDenied`).
27///
28/// Every pre-handler denial carries exactly this text, so the external surface
29/// is uniform and the internal cause is confined to the operator's log. It is
30/// paired with the server's current challenge in the response's fixed slot,
31/// which is likewise attached to every denial regardless of cause.
32pub const DISPATCH_DENIED: &str = "dispatch denied";
33
34/// Process a request through the full envelope verification pipeline.
35///
36/// Unified handler for all transport front-ends. The only difference between
37/// them is envelope signer verification, controlled by `verification`.
38///
39/// # Pipeline
40///
41/// 1. Unwrap `SignedEnvelope` and verify the signature (mode-dependent), under
42///    the process-global verify policy + kid-anchored PQ trust store.
43/// 2. Verify JWT claims (`sub`, `exp`, `aud`, `scope`, downgrade protection).
44/// 3. Dispatch to `service.handle_request()` with a verified `EnvelopeContext`.
45/// 4. Sign the response with the server's `signing_key`.
46///
47/// # Streaming
48///
49/// A streaming handler returns a `Continuation` (the server-side streaming
50/// response that runs after the reply). As of #186 that task is spawned
51/// **here**, via [`crate::streaming::spawn_streaming_response`], rather than
52/// handed back to the transport front-end — so every front-end (ZMQ
53/// `RequestLoop`, WebTransport server, generic-plane `LocalServiceBridge`) is
54/// uniform "bytes in → bytes out" and the generic plane no longer has to spawn
55/// (or, worse, reject) continuations itself. **Invariant:** `process_request`
56/// must therefore run on a `tokio::task::LocalSet` (it already did —
57/// `RequestService` is `?Send`); the spawned task is `?Send`.
58///
59/// # Returns
60///
61/// * `Ok(response_bytes)` - Signed response. Any streaming pump has already been
62///   spawned onto the current `LocalSet`.
63/// * `Err(e)` - Processing error (already logged)
64pub async fn process_request<S>(
65    raw_bytes: &[u8],
66    service: &S,
67    verification: EnvelopeVerification<'_>,
68    signing_key: &ed25519_dalek::SigningKey,
69    nonce_cache: &crate::envelope::InMemoryNonceCache,
70    carrier: crate::transport::carrier::CarrierContext,
71) -> Result<Vec<u8>>
72where
73    S: crate::service::RequestService,
74{
75    // 1. Unwrap, verify, and optionally decrypt the SignedEnvelope.
76    //    The verify policy + kid-anchored PQ trust store come from the
77    //    process-global verify configuration installed at startup (Hybrid
78    //    ENFORCED in the daemon). This closes the prior fail-open where the
79    //    site hardcoded Classical / no PQ store.
80    let pq_store_holder = crate::envelope::global_pq_store();
81    let base = match verification {
82        EnvelopeVerification::FixedSigner(pubkey) => {
83            crate::envelope::UnwrapOptions::fixed_signer(pubkey, nonce_cache)
84        }
85        EnvelopeVerification::AnySigner => crate::envelope::UnwrapOptions::any_signer(nonce_cache),
86    }
87    .with_decryption_key(signing_key)
88    .require_encrypted(carrier.forbids_cleartext_envelope());
89    let opts = crate::envelope::apply_global_verify_config(base, &pq_store_holder);
90
91    let (mut ctx, payload) = match crate::envelope::unwrap_envelope(raw_bytes, &opts) {
92        Ok(result) => result,
93        Err(e) => {
94            warn!("{} envelope verification failed: {}", service.name(), e);
95            // Never sign a response to unauthenticated input. The transport
96            // boundary treats this error as a silent stream reset/drop on
97            // untrusted carriers, preventing a signing oracle/amplifier.
98            return Err(e).with_context(|| format!("{} envelope admission failed", service.name()));
99        }
100    };
101
102    let request_id = ctx.request_id;
103    let actual_service_domain = service.name();
104
105    // Refuse before dispatch if the service cannot emit the mandatory pinned
106    // hybrid response suite. Missing key material is never a signal to
107    // construct a classical response. Deliberately checked only after envelope
108    // authentication: the default `pq_signing_key()` derives an ML-DSA key per
109    // call, and unauthenticated input must not be able to trigger that work.
110    //
111    // This is a server-configuration fault, not a per-request denial, and it
112    // is not attacker-controlled: without a response signing key there is no
113    // way to emit ANY signed response — denial or success — so this drops
114    // rather than routing through the uniform surface below.
115    let response_pq_key = service.pq_signing_key().ok_or_else(|| {
116        anyhow::anyhow!("service has no ML-DSA-65 response signing key (mandatory Hybrid suite)")
117    })?;
118    let response_recipient = ctx.response_kem_recipient.clone();
119    let request_iat = ctx.request_iat;
120    let request_nonce = ctx.request_nonce;
121    let sign_response_with_challenge =
122        |payload: Vec<u8>, server_challenge: Option<Vec<u8>>| -> Result<ResponseEnvelope> {
123            if carrier.forbids_cleartext_envelope() {
124                let recipient = response_recipient
125                    .as_ref()
126                    .ok_or_else(|| anyhow::anyhow!("missing authenticated response recipient"))?;
127                ResponseEnvelope::new_signed_encrypted_with_challenge(
128                    request_id,
129                    payload,
130                    server_challenge,
131                    signing_key,
132                    &response_pq_key,
133                    recipient,
134                    request_iat,
135                    &request_nonce,
136                    actual_service_domain,
137                )
138                .map_err(Into::into)
139            } else {
140                ResponseEnvelope::new_signed_with_challenge(
141                    request_id,
142                    payload,
143                    server_challenge,
144                    signing_key,
145                    Some(&response_pq_key),
146                    crate::crypto::CryptoPolicy::Hybrid,
147                )
148            }
149        };
150    let sign_response = |payload: Vec<u8>| sign_response_with_challenge(payload, None);
151
152    /// Serialize a signed response envelope to wire bytes.
153    fn serialize_response(signed: &ResponseEnvelope) -> Result<Vec<u8>> {
154        let mut message = Builder::new_default();
155        let mut builder = message.init_root::<crate::common_capnp::response_envelope::Builder>();
156        signed.write_to(&mut builder);
157        let mut bytes = Vec::new();
158        serialize::write_message(&mut bytes, &message)?;
159        Ok(bytes)
160    }
161
162    // Every pre-handler denial goes out through this one path (§14.2): the
163    // same shape, and always carrying the server's current challenge in the
164    // fixed response slot (§4.7). Because every denial carries one, its
165    // presence reveals nothing about the internal cause, and a client that
166    // has no challenge yet obtains a usable one from its first denial and
167    // retries exactly once with a fresh request_id.
168    //
169    // When rotation cannot produce a usable challenge the denial still goes
170    // out — it simply advertises none, which is service refusal rather than
171    // an unusable challenge the client would burn its one retry on.
172    let dispatch_denied = |cause: &str| -> Result<Vec<u8>> {
173        // The cause is for the operator's log, never for the payload. Unknown
174        // service/method, malformed body, invalid credential, missing session,
175        // revocation, replay, signature-threshold failure, resource limit, and
176        // policy absence are externally indistinguishable (§14.2): no response
177        // reveals whether a credential ID, session, subject, signer, or label
178        // exists.
179        debug!(
180            "{} pre-handler denial (id={request_id}): {cause}",
181            service.name()
182        );
183        let now_secs = std::time::SystemTime::now()
184            .duration_since(std::time::UNIX_EPOCH)
185            .map(|d| d.as_secs())
186            .unwrap_or(0);
187        let challenge = crate::proof::admission::global_challenge_manager()
188            .and_then(|mgr| mgr.current_or_rotate(now_secs))
189            .map(|c| c.value);
190        let payload = service.build_error_payload(request_id, DISPATCH_DENIED);
191        let signed = sign_response_with_challenge(payload, challenge)?;
192        serialize_response(&signed)
193    };
194
195    // Post-authentication pre-handler gates (§14.2). Every one of these — a
196    // non-canonical or mismatched service domain, an absent domain on an
197    // encrypted carrier, a browser carrier-recovery failure, an absent
198    // response recipient, a browser binding/currentness failure — now leaves
199    // through the ONE uniform `dispatch_denied` surface, so it is externally
200    // indistinguishable from a claims/proof/policy/MAC/replay denial and
201    // carries the same challenge slot. Before v16 these returned `Err` and
202    // dropped the connection, which was an observable oracle distinguishing
203    // "which gate failed". The unauthenticated envelope-verification failure
204    // above remains a silent drop (the ratified INV-2 anti-oracle boundary):
205    // uniform denial begins only once a request is authenticated.
206    if crate::envelope::validate_service_domain(actual_service_domain).is_err() {
207        return dispatch_denied(&format!(
208            "service exposes non-canonical domain '{actual_service_domain}'"
209        ));
210    }
211    match ctx.service_domain.as_deref() {
212        Some(expected) if expected != actual_service_domain => {
213            return dispatch_denied(&format!(
214                "request service domain '{expected}' does not match dispatcher '{actual_service_domain}'"
215            ));
216        }
217        None if carrier.forbids_cleartext_envelope() => {
218            return dispatch_denied("authenticated network request omitted serviceDomain");
219        }
220        _ => {}
221    }
222
223    let transcript_policy = if carrier.requires_browser_provisioning() {
224        crate::browser_provisioning::BrowserTranscriptPolicy::Required {
225            request_id,
226            service_name: actual_service_domain,
227            carrier_profile:
228                crate::browser_provisioning::BrowserCarrierProfile::OwnedHybridWebTransport,
229        }
230    } else {
231        crate::browser_provisioning::BrowserTranscriptPolicy::NotBrowserCarrier
232    };
233    let (browser_transcript, payload) =
234        match crate::browser_provisioning::recover_request_payload(&payload, transcript_policy) {
235            Ok(recovered) => recovered,
236            Err(e) => return dispatch_denied(&format!("browser carrier recovery: {e:#}")),
237        };
238
239    ctx.browser_method_discriminator = browser_transcript
240        .as_ref()
241        .map(|transcript| transcript.method_discriminator);
242    if carrier.forbids_cleartext_envelope() && ctx.response_kem_recipient.is_none() {
243        return dispatch_denied("authenticated network request omitted responseKemRecipient");
244    }
245    if carrier.requires_browser_provisioning() {
246        let recovered = match browser_transcript.as_ref() {
247            Some(transcript) => &transcript.binding,
248            None => {
249                return dispatch_denied(
250                    "authenticated WebTransport request omitted browser binding",
251                )
252            }
253        };
254        let binding = recovered;
255        if binding.service_name != actual_service_domain {
256            return dispatch_denied(&format!(
257                "browser provisioning service '{}' does not match dispatcher '{}'",
258                binding.service_name, actual_service_domain
259            ));
260        }
261        if !(binding.capability == "hyprstream-rpc/1"
262            && binding.scope == actual_service_domain
263            && binding.carrier_profile
264                == crate::browser_provisioning::BrowserCarrierProfile::OwnedHybridWebTransport)
265        {
266            return dispatch_denied(
267                "browser provisioning capability/scope/carrier misclassification",
268            );
269        }
270        let verifier = match crate::envelope::global_browser_currentness_verifier() {
271            Some(verifier) => verifier,
272            None => {
273                return dispatch_denied(
274                    "checkpoint-backed browser currentness verifier is not installed",
275                )
276            }
277        };
278        if let Err(e) = verifier.ensure_current(binding).await {
279            return dispatch_denied(&format!(
280                "browser accepted-current evidence rejected: {e:#}"
281            ));
282        }
283    }
284
285    debug!(
286        "{} verified request from {} (id={})",
287        service.name(),
288        ctx.subject(),
289        request_id
290    );
291
292    // 2. Verify claims (E2E JWT, downgrade protection)
293    if let Err(e) = service.verify_claims(&mut ctx).await {
294        warn!(
295            "{} claims verification failed for {} (id={}): {}",
296            service.name(),
297            ctx.subject(),
298            request_id,
299            e
300        );
301        return dispatch_denied(&format!("claims verification: {e}"));
302    }
303    let deferred_federate = ctx.deferred_federate_credential().is_some();
304
305    // Proof-CWT structural parse and profile gates (§5.2: parse canonical COSE
306    // and proof payload under bounds, then bind the service coordinate and
307    // freshness). Cryptographic verification and replay admission follow.
308    //
309    // Deliberately placed after the denial surface exists: a structural,
310    // audience, freshness, or body-binding failure is a pre-handler denial
311    // like any other, and must leave through the same uniform response rather
312    // than dropping the connection and telling the client nothing.
313    let parsed_proof = {
314        let parsed = (|| -> Result<Option<crate::proof::parser::ParsedProof>> {
315            // Proof-CWT structural parse (v16 §5.2 pipeline: parse canonical COSE
316            // and proof payload under bounds). This runs the bounded parser which
317            // validates the profile's structural rules (typ, hs_domain, crit,
318            // signature plan, claims, key set) but does NOT verify cryptographic
319            // signatures. Signature verification and replay admission run after
320            // policy evaluation, immediately before handler entry.
321            let parsed = if let Some(proof_cwt) = &ctx.envelope_proof_cwt {
322                let proof = if deferred_federate {
323                    crate::proof::parser::ParsedProof::parse_deferred_federate_request(proof_cwt)
324                } else {
325                    crate::proof::parser::ParsedProof::parse(proof_cwt)
326                }
327                .with_context(|| format!("{} proof-CWT parse failed", service.name()))?;
328
329                // CRITICAL: only request proofs are valid in request dispatch.
330                if proof.kind != crate::proof::ProofKind::Request {
331                    warn!(
332                        "{} rejected {} proof in request dispatch",
333                        service.name(),
334                        match proof.kind {
335                            crate::proof::ProofKind::Response => "response",
336                            crate::proof::ProofKind::Request => "request",
337                        }
338                    );
339                    anyhow::bail!("proof kind mismatch: only request proofs accepted in dispatch");
340                }
341
342                // The proof's aud MUST match the service domain.
343                if proof.claims.aud != actual_service_domain {
344                    warn!(
345                        "{} proof aud mismatch: '{}' vs '{}'",
346                        service.name(),
347                        proof.claims.aud,
348                        actual_service_domain
349                    );
350                    anyhow::bail!("proof aud mismatch");
351                }
352
353                // Freshness: per-disposition bounds against verifier clock.
354                let now_secs = std::time::SystemTime::now()
355                    .duration_since(std::time::UNIX_EPOCH)
356                    .map(|d| d.as_secs())
357                    .unwrap_or(0);
358                let skew_tolerance_secs: u64 = 30;
359                let max_lifetime_secs: u64 = match proof.disposition {
360                    crate::proof::ProofDisposition::Authenticated => 300, // 5 min
361                    crate::proof::ProofDisposition::Unattributed => 30,   // seconds-scale
362                };
363                if proof.claims.iat.abs_diff(now_secs) > skew_tolerance_secs {
364                    anyhow::bail!("proof freshness: iat outside {skew_tolerance_secs}s tolerance");
365                }
366                if proof.claims.exp <= now_secs {
367                    anyhow::bail!("proof freshness: exp expired");
368                }
369                if proof.claims.exp > now_secs + max_lifetime_secs {
370                    anyhow::bail!(
371                        "proof freshness: exp exceeds {max_lifetime_secs}s max lifetime for {:?}",
372                        proof.disposition
373                    );
374                }
375
376                // Anti-stockpiling challenge pre-check (§4.7). The server challenge
377                // is a plaintext claim available at parse time, so a stale or
378                // unknown unattributed challenge is rejected HERE — before the
379                // expensive hybrid Ed25519 + ML-DSA-65 verification — so an
380                // unattributed flood cannot force per-request crypto with a
381                // guessed/expired challenge. This is the challenge's stated role:
382                // a rejection handle that costs no signature verification and no
383                // replay-store entry. The authoritative, TOCTOU-free `validate()`
384                // that yields the matched `accept_until` still runs atomically at
385                // replay admission below; this early call is a load-shedding
386                // pre-filter and is intentionally non-consuming.
387                if proof.disposition == crate::proof::ProofDisposition::Unattributed {
388                    let challenge =
389                        proof.claims.nonce.as_ref().ok_or_else(|| {
390                            anyhow::anyhow!("unattributed proof missing Nonce claim")
391                        })?;
392                    match crate::proof::admission::global_challenge_manager() {
393                        Some(mgr) => {
394                            if mgr.validate(challenge, now_secs).is_none() {
395                                anyhow::bail!(
396                                "unattributed proof challenge invalid/expired (pre-verification)"
397                            );
398                            }
399                        }
400                        None => {
401                            anyhow::bail!(
402                                "unattributed proof requires a challenge manager to be installed"
403                            );
404                        }
405                    }
406                }
407
408                debug!(
409                    "{} proof-CWT parsed (not yet crypto-verified): disposition={:?} request_id={}",
410                    service.name(),
411                    proof.disposition,
412                    hex::encode(proof.claims.request_id)
413                );
414                Some(proof)
415            } else {
416                None
417            };
418            // After carrier recovery: verify proof body bytes match the ONE decoded
419            // request body that feeds both PEP and handler (v16 §5.1 invariant).
420            if let Some(ref proof) = parsed {
421                if proof.claims.capnp_body_bytes != payload {
422                    warn!(
423                        "{} proof body mismatch after carrier recovery: {} vs {} bytes",
424                        service.name(),
425                        proof.claims.capnp_body_bytes.len(),
426                        payload.len()
427                    );
428                    anyhow::bail!("proof body bytes do not match decoded request body");
429                }
430            }
431            Ok(parsed)
432        })();
433        match parsed {
434            Ok(parsed) => parsed,
435            Err(e) => {
436                warn!(
437                    "{} proof admission denied (id={}): {e:#}",
438                    service.name(),
439                    request_id
440                );
441                return dispatch_denied(&format!("proof gate: {e:#}"));
442            }
443        }
444    };
445
446    // 2c. Proof authority (v16 §5.2 pipeline step 3). The credential was
447    // parsed and verified above (step 2); this cryptographically verifies the
448    // signer entries and the credential hash/cnf binding BEFORE the decoded
449    // leaf's generated policy and before dispatch MAC, so no unverified proof
450    // claim can influence authorization.
451    //
452    // Denials leave through the one uniform DispatchDenied surface, so a proof
453    // denial is externally indistinguishable from any other pre-handler denial
454    // and still hands the client a usable challenge to retry with.
455    let now_secs = std::time::SystemTime::now()
456        .duration_since(std::time::UNIX_EPOCH)
457        .map(|d| d.as_secs())
458        .unwrap_or(0);
459    let mut verified_proof = if deferred_federate {
460        None
461    } else {
462        match parsed_proof.as_ref() {
463            None => None,
464            Some(proof) => {
465                let authority = (|| -> Result<crate::proof::verify::VerifiedProof> {
466                    // Every required component MUST cryptographically verify under
467                    // the key its own enrolled signer-suite record pins.
468                    // Verification also yields the replay namespace this proof is
469                    // admitted under; it is never derived from wire material.
470                    let cnf_key = ctx.authenticated_signer_key();
471                    let verified = crate::proof::verify::verify_proof_signatures(
472                        proof,
473                        cnf_key.as_ref(),
474                        crate::proof::enrollment::global_enrollment_resolver(),
475                        now_secs,
476                    )
477                    .with_context(|| {
478                        format!("{} proof signature verification failed", service.name())
479                    })?;
480
481                    // Credential hash binding. Presenting a credential never
482                    // leaves the proof in the unattributed branch (§4.4): hash
483                    // absence is permitted only when no credential is presented,
484                    // so a credential alongside an unattributed proof denies
485                    // rather than silently dropping to system-low.
486                    if proof.disposition == crate::proof::ProofDisposition::Unattributed
487                        && ctx.jwt_token().is_some()
488                    {
489                        anyhow::bail!(
490                            "credential presented with a proof carrying no credential_hash"
491                        );
492                    }
493                    // Missing credential MUST deny — no skip/downgrade.
494                    if proof.disposition == crate::proof::ProofDisposition::Authenticated {
495                        let expected_hash = proof.claims.credential_hash.ok_or_else(|| {
496                            anyhow::anyhow!("authenticated proof missing credential_hash")
497                        })?;
498                        let jwt = ctx.jwt_token().ok_or_else(|| {
499                            anyhow::anyhow!(
500                                "authenticated proof: no credential (JWT) resolved from claims"
501                            )
502                        })?;
503                        use sha2::{Digest, Sha256};
504                        let actual_hash = Sha256::digest(jwt.as_bytes());
505                        if actual_hash.as_slice() != expected_hash {
506                            anyhow::bail!(
507                                "proof credential hash does not match presented credential"
508                            );
509                        }
510
511                        // A proof must not outlive the credential that authorizes
512                        // it (§4.5). The enrollment record bounds the enrollment's
513                        // own validity; this bounds the presented credential
514                        // instance, so an admin-anchored enrollment with no expiry
515                        // cannot extend a short-lived token's reach.
516                        if let Some(credential_exp) =
517                            ctx.claims().map(|claims| claims.exp).filter(|exp| *exp > 0)
518                        {
519                            let credential_exp = credential_exp as u64;
520                            if proof.claims.exp > credential_exp {
521                                anyhow::bail!(
522                                "proof exp {} exceeds the presented credential's exp {credential_exp}",
523                                proof.claims.exp
524                            );
525                            }
526                        }
527                    }
528                    Ok(verified)
529                })();
530                match authority {
531                    Ok(verified) => Some(verified),
532                    Err(e) => {
533                        warn!(
534                            "{} proof authority denied (id={}): {e:#}",
535                            service.name(),
536                            request_id
537                        );
538                        return dispatch_denied("dispatch denied");
539                    }
540                }
541            }
542        }
543    };
544
545    // 2d. The ONE bounded decode of the request body (§5.2 step 4). The
546    // service's generated decoder decodes the signed bytes exactly once and
547    // derives the full nested numeric leaf path; the same `DecodedRequestBody`
548    // then feeds the generated method policy below, the dispatch MAC PEP, and
549    // finally the handler — no dispatch component re-reads discriminants and
550    // no second decode with different traversal or resource limits can select
551    // a handler. Ordinary requests reach this after proof verification.
552    // Deferred Federate requests have a verified host JWT and signed envelope;
553    // the narrow hook below verifies the original holder against this body.
554    let decoded_body = match service.decode_request_body(&payload) {
555        Ok(body) => body,
556        Err(e) => {
557            warn!(
558                "{} request body decode failed (id={}): {e:#}",
559                service.name(),
560                request_id
561            );
562            return dispatch_denied("dispatch denied");
563        }
564    };
565    if ctx.has_delegated_resource_audience()
566        && !service.accept_delegated_resource_leaf(&ctx, &decoded_body)
567    {
568        return dispatch_denied("delegated resource audience not admitted for decoded leaf");
569    }
570
571    // Federate TUI-class dispatch fence (W1.3). A TUI-classified credential
572    // (marker set, or the authority-owned deployment class pin — classified
573    // by verify_claims, never caller-supplied) dispatches only on:
574    //   * the tui service — the consumer gate there enforces the exact
575    //     class and the per-operation scope map; and
576    //   * the policy service's read-only check leaf (policy.capnp
577    //     `check @1`, union discriminant 0) and only as the delegated
578    //     subject of an authenticated
579    //     service mediator — the TUI service's per-operation Casbin
580    //     authorization. Mutation/issuance leaves and direct holder calls
581    //     are never admitted.
582    // A classified credential with the marker set stripped is denied
583    // unconditionally: the mint stamps all four markers, so that shape is
584    // never legitimate. The class carries no registry|model consumer
585    // authority, and per-service Casbin checks do not intersect credential
586    // scopes — without this fence a TUI credential would act as a generic
587    // identity credential for its DID wherever that DID has independent
588    // grants and clearance.
589    if ctx.is_federate_tui_class() {
590        let complete = ctx
591            .claims()
592            .is_some_and(crate::auth::Claims::has_complete_federate_tui_profile);
593        // policy.capnp: `check @1` is union discriminant 0 (the leaf path is
594        // the discriminant, per the generated decoder).
595        const POLICY_CHECK_LEAF: &[u16] = &[0u16];
596        let allowed = complete
597            && (actual_service_domain == "tui"
598                || (actual_service_domain == "policy"
599                    && decoded_body.leaf_path() == Some(POLICY_CHECK_LEAF)
600                    && ctx.is_delegated_bearer()));
601        if !allowed {
602            return dispatch_denied("federate TUI credential class not dispatchable here");
603        }
604    }
605
606    let mut deferred_federate_replay = None;
607    if deferred_federate {
608        let Some(proof) = parsed_proof.as_ref() else {
609            return dispatch_denied("Federate holder proof missing");
610        };
611        let recipients_match = proof
612            .claims
613            .federate_recipient_binding
614            .as_ref()
615            .is_some_and(|binding| {
616                binding.matches(
617                    ctx.response_kem_recipient(),
618                    ctx.stream_kem_recipient(),
619                    ctx.ephemeral_pubkey(),
620                )
621            });
622        if !recipients_match {
623            return dispatch_denied("Federate recipient binding denied");
624        }
625        let (verified, holder_ed, resource, operation, replay_key, replay_expiry) = match service
626            .admit_deferred_federate_request(&ctx, &decoded_body, proof)
627            .await
628        {
629            Ok(admitted) => admitted,
630            Err(_) => return dispatch_denied("Federate request admission denied"),
631        };
632        if ctx
633            .commit_deferred_federate(&verified, holder_ed, resource.clone(), operation.clone())
634            .is_err()
635        {
636            return dispatch_denied("Federate holder/subject mismatch");
637        }
638        deferred_federate_replay = Some((replay_key, replay_expiry, resource, operation));
639        verified_proof = Some(verified);
640    }
641
642    // 2e. Generated per-method signature policy (§5.2 step 5, §4.4). The
643    // decoded leaf — not the caller — decides whether this method may be
644    // dispatched unattributed at all, which cryptographic suite its primary
645    // logical signer must use, and which enrolled approvers must sign.
646    // Enrollment says who signed; this says what the method requires.
647    //
648    // A leaf the generated table does not list is unlisted and denies. This
649    // gate runs only for proof-bearing requests: the pre-v16 path has no
650    // signed leaf to resolve, and is governed by the legacy checks below until
651    // the migration completes.
652    if let (Some(proof), Some(verified)) = (parsed_proof.as_ref(), verified_proof.as_ref()) {
653        // The leaf comes from the signed body, decoded by the service's own
654        // generated decoder — not from a transport-specific hint such as the
655        // browser transcript's method commitment, which does not exist on
656        // other carriers. An undecodable body, an unknown discriminant, or an
657        // empty path is a denial, never a fall back to a coarser row.
658        let leaf_path = match decoded_body.leaf_path_string() {
659            Some(path) => path,
660            None => {
661                return dispatch_denied(
662                    "no method leaf derivable from the signed body for this service",
663                );
664            }
665        };
666        let decision = match crate::proof::policy::global_method_policy() {
667            Some(table) => match table.policy_for(actual_service_domain, &leaf_path) {
668                Some(policy) => {
669                    crate::proof::policy::evaluate(&policy, proof.disposition, verified)
670                }
671                None => Err(anyhow::anyhow!(
672                    "unlisted (service, leaf) row for '{actual_service_domain}':'{leaf_path}'"
673                )),
674            },
675            None => Err(anyhow::anyhow!(
676                "no generated method policy table installed; proof-bearing dispatch denies"
677            )),
678        };
679        if let Err(e) = decision {
680            warn!(
681                "{} generated method policy denied (id={}): {e:#}",
682                service.name(),
683                request_id
684            );
685            return dispatch_denied("dispatch denied");
686        }
687    }
688
689    // 2b. Mandatory native-MAC dispatch PEP (epic #1267 T3, #1268).
690    //
691    // This is the mandatory, unavoidable gate between claims verification
692    // and handler invocation — the RPC-plane analogue of the 9P
693    // `NinePAccessDecider`. It composes the S1 two-input clearance derivation
694    // (Claims × VerifiedKeyMaterial via `EnvelopeContext::security_context`)
695    // with a trusted object-label resolver and the intrinsic `can_access`
696    // lattice floor. Once installed, the PEP fails closed: missing clearance,
697    // missing label, or lattice-floor deny ⇒ handler is never called.
698    //
699    // **Activation gate (#1267):** identity-aware subject selection remains
700    // operator-gated, but mediation is mandatory at rest. Until a node installs
701    // a PEP process-globally via `install_mac_dispatch_pep`, this gate denies
702    // with `NoPepInstalled`; after installation its decision is authoritative.
703    //
704    // **Typed method identity (#1499):** the PEP evaluates the typed
705    // `(service, leaf/method)` identity of the call. The leaf is the canonical
706    // request-union discriminant, decoded once here from the verified payload
707    // (a bounded structural read of the signed body — the value the generated
708    // handler will independently decode and act on). A payload that does not
709    // decode to a canonical request union contributes no method identity:
710    // `None` matches no declared row, so the call fails closed below rather
711    // than at the handler's own decode. The browser commitment
712    // (`browser_method_discriminator`) remains the cross-check input to
713    // `ensure_browser_method` and is unchanged by this decode.
714    //
715    // Streaming continuations: the continuation produced by a permitted
716    // handler inherits this dispatch-time Permit. Explicit re-check of
717    // long-running continuations against revoked authority is a DEFERRED
718    // follow-up (#1267 scope expansion — `StaleAuthority` variant is reserved
719    // for that future gate, not used today).
720    // The MAC object coordinate is the same decoded leaf the generated policy
721    // consumed — never a transport-specific hint such as the browser
722    // transcript's method commitment (v16 §5.1: one derived method identity
723    // feeds policy, PEP, and handler).
724    let mac_decision =
725        crate::auth::mac::check_dispatch_mac(&ctx, actual_service_domain, decoded_body.leaf_path());
726    if let crate::auth::mac::MacDecision::Deny(reason) = mac_decision {
727        let mac_resource = match decoded_body.leaf_path_string() {
728            Some(leaf) => format!("{actual_service_domain}:method:{leaf}"),
729            None => format!("{actual_service_domain}:*"),
730        };
731        // S7/#1274: a mandatory-MAC rejection is an authorization decision,
732        // not merely a diagnostic warning. Emit it on the unified MAC audit
733        // target before returning the signed deny response so the RPC and 9P
734        // planes have the same fail-closed audit contract.
735        warn!(
736            target: "hyprstream.mac.audit",
737            decision = "deny",
738            subject = %ctx.subject(),
739            resource = %mac_resource,
740            action = "rpc-dispatch",
741            request_id,
742            plane = "rpc",
743            reason = ?reason,
744            "authorization decision"
745        );
746        warn!(
747            "{} MAC dispatch PEP denied {} (id={}, reason={:?})",
748            service.name(),
749            ctx.subject(),
750            request_id,
751            reason,
752        );
753        return dispatch_denied(&format!("MAC deny: {reason:?}"));
754    }
755
756    // 2e. Replay admission (§5.2 step 7). Deliberately last: the pipeline
757    // admits the replay key only after policy evaluation, so rejected and
758    // denied requests never consume store capacity.
759    // Federate's original-holder proof is admitted by the request-local
760    // serving adapter after its fresh Policy check; it uses this same shared
761    // replay store with the signed hybrid-key namespace.
762    if !deferred_federate {
763        if let (Some(proof), Some(verified)) = (parsed_proof.as_ref(), verified_proof.as_ref()) {
764            let proof_admission = (|| -> Result<()> {
765                // Gate 3: Challenge validation (unattributed proofs only).
766                // validate() atomically returns the matched challenge's accept_until
767                // so we can compute replay expiry without a TOCTOU race.
768                let challenge_accept_until: Option<u64> =
769                    if proof.disposition == crate::proof::ProofDisposition::Unattributed {
770                        let challenge = proof.claims.nonce.as_ref().ok_or_else(|| {
771                            anyhow::anyhow!("unattributed proof missing Nonce claim")
772                        })?;
773                        match crate::proof::admission::global_challenge_manager() {
774                            Some(mgr) => {
775                                let accept_until =
776                                    mgr.validate(challenge, now_secs).ok_or_else(|| {
777                                        warn!(
778                                            "{} unattributed proof challenge invalid/expired",
779                                            service.name()
780                                        );
781                                        anyhow::anyhow!("proof challenge validation failed")
782                                    })?;
783                                Some(accept_until)
784                            }
785                            None => {
786                                warn!(
787                                    "{} no challenge manager installed; denying unattributed proof",
788                                    service.name()
789                                );
790                                anyhow::bail!(
791                                "unattributed proof requires a challenge manager to be installed"
792                            );
793                            }
794                        }
795                    } else {
796                        None
797                    };
798
799                // Gate 4: Replay admission using the process-global ProofReplayStore.
800                // No auto-install: the store must be explicitly installed at startup.
801                // If absent, deny fail-closed.
802                let replay_store = crate::proof::admission::global_proof_replay_store()
803            .ok_or_else(|| {
804                anyhow::anyhow!("no ProofReplayStore installed; install via set_global_proof_replay_store at startup")
805            })?;
806
807                // Compute replay expiry using the atomically-returned challenge
808                // accept_until (no TOCTOU race).
809                let replay_expiry = match challenge_accept_until {
810                    Some(au) => proof.claims.exp.min(au),
811                    None => proof.claims.exp,
812                };
813
814                // v16 credentials are Reusable-only (OneShotTransaction cut from scope,
815                // operator decision 2026-08-20): replay admission is keyed by the proof,
816                // so many fresh proofs may use one credential. There is no per-credential
817                // consume-once path.
818                //
819                // The replay namespace comes from verification, not from wire
820                // material: the credential-bound primary signer-suite thumbprint
821                // (exact suite ID, ordered pinned component keys, enrollment epoch)
822                // for authenticated proofs, and the (plan, key set) thumbprint for
823                // unattributed ones.
824                let replay_key = crate::proof::admission::ProofReplayKey {
825                    signer_thumbprint: verified.replay_thumbprint,
826                    request_id: proof.claims.request_id,
827                };
828
829                match crate::proof::admission::admit_request_proof(
830                    replay_store,
831                    proof.disposition,
832                    &replay_key,
833                    replay_expiry,
834                ) {
835                    crate::proof::admission::ProofAdmissionResult::Admitted => {
836                        debug!("{} proof replay admission: admitted", service.name());
837                    }
838                    crate::proof::admission::ProofAdmissionResult::Replayed => {
839                        warn!("{} proof replay detected", service.name());
840                        anyhow::bail!("proof replay detected");
841                    }
842                    crate::proof::admission::ProofAdmissionResult::Failed => {
843                        // Capacity, backend unavailability, or a namespace this node
844                        // holds no history for. Every one of them is a denial.
845                        warn!(
846                    "{} proof replay admission failed closed (capacity, backend, or namespace affinity)",
847                    service.name()
848                );
849                        anyhow::bail!("proof replay admission could not be guaranteed");
850                    }
851                }
852                Ok(())
853            })();
854
855            if let Err(e) = proof_admission {
856                warn!(
857                    "{} proof admission denied (id={}): {e:#}",
858                    service.name(),
859                    request_id
860                );
861                return dispatch_denied("dispatch denied");
862            }
863        }
864    }
865
866    // Fresh Policy authorization and the durable session-bound replay consume
867    // are one transaction in Policy. Defer that call until every local method
868    // and MAC gate has passed, so an otherwise valid proof denied here remains
869    // retryable. It is the final authorization gate before handler dispatch.
870    if deferred_federate {
871        let Some((replay_key, replay_expiry, resource, operation)) =
872            deferred_federate_replay.as_ref()
873        else {
874            return dispatch_denied("Federate replay admission unavailable");
875        };
876        if service
877            .commit_deferred_federate_request(&ctx, resource, operation, replay_key, *replay_expiry)
878            .await
879            .is_err()
880        {
881            warn!("{} Federate Policy/replay admission denied", service.name());
882            return dispatch_denied("dispatch denied");
883        }
884        let Some(replay_store) = crate::proof::admission::global_proof_replay_store() else {
885            return dispatch_denied("Federate replay admission unavailable");
886        };
887        let Some(proof) = parsed_proof.as_ref() else {
888            return dispatch_denied("Federate holder proof missing");
889        };
890        match crate::proof::admission::admit_request_proof(
891            replay_store,
892            proof.disposition,
893            replay_key,
894            *replay_expiry,
895        ) {
896            crate::proof::admission::ProofAdmissionResult::Admitted => {}
897            crate::proof::admission::ProofAdmissionResult::Replayed => {
898                warn!("{} Federate proof replay detected", service.name());
899                return dispatch_denied("dispatch denied");
900            }
901            crate::proof::admission::ProofAdmissionResult::Failed => {
902                warn!(
903                    "{} Federate proof replay admission failed closed",
904                    service.name()
905                );
906                return dispatch_denied("dispatch denied");
907            }
908        }
909    }
910
911    // 3. Handle request — from the same decoded body the policy and MAC
912    //    gates consumed (v16 §5.1: signed == decoded == handler body).
913    let (response_payload, continuation) = match service.handle_request(&ctx, &decoded_body).await {
914        Ok((resp, cont)) => (resp, cont),
915        Err(e) => {
916            error!("{} request handling error: {}", service.name(), e);
917            (
918                service.build_error_payload(request_id, &e.to_string()),
919                None,
920            )
921        }
922    };
923
924    // 4. Sign and serialize response
925    let signed_response = sign_response(response_payload)?;
926
927    let mut message = Builder::new_default();
928    let mut builder = message.init_root::<crate::common_capnp::response_envelope::Builder>();
929    signed_response.write_to(&mut builder);
930
931    let mut bytes = Vec::new();
932    serialize::write_message(&mut bytes, &message)?;
933
934    // 5. Spawn the server-side streaming response (if any) onto the current
935    //    LocalSet, so the reply is all the transport front-end has to deal with
936    //    (#186). Bounded by a per-service admission permit; see
937    //    spawn_streaming_response.
938    if let Some(cont) = continuation {
939        crate::streaming::spawn_streaming_response(service.name(), cont);
940    }
941
942    Ok(bytes)
943}