hyprstream_rpc/auth/mac/dispatch_pep.rs
1//! **The mandatory RPC dispatch PEP** (epic #1267 T3, #1268).
2//!
3//! This is the single mandatory, unavoidable MAC gate between claims
4//! verification and handler invocation in [`crate::service::dispatch::
5//! process_request`]. It is the RPC-plane analogue of the 9P
6//! `NinePAccessDecider` (`hyprstream/src/mac/pep.rs`): both resolve a
7//! trusted object label and check `clearance.can_access(label)` before
8//! the data reaches the handler.
9//!
10//! ## Why this exists
11//!
12//! `process_request` verifies the caller's identity and JWT claims, then
13//! invokes `handle_request` with **no object-label resolution, no lattice
14//! floor check, and no `can_access`** (issue #1268). Method-level Casbin
15//! (`#[authorize]`) is discretionary — a handler that forgets the attribute
16//! is unmediated. This PEP is the **mandatory floor** no handler can bypass.
17//!
18//! ## The three-step check (per design §10, S1 interface contract)
19//!
20//! ```text
21//! 1. Subject: ctx.security_context() → Option<SecurityContext>
22//! None ⇒ Deny(NoClearance)
23//! 2. Object: resolver.resolve(svc, method) → Option<SecurityLabel>
24//! None ⇒ Deny(UnlabeledObject)
25//! 3. Decision: ctx.can_access(label) → bool
26//! false ⇒ Deny(FloorDeny)
27//! ```
28//!
29//! Once a PEP is installed, every `None` or `false` produced by that PEP is a
30//! hard deny. There is **no permissive mode inside an active PEP** (epic #547
31//! invariant: "no unlabeled-default-allow").
32//!
33//! ## Clearance provenance (#698 dependency)
34//!
35//! `EnvelopeContext::security_context()` already composes `Claims ×
36//! VerifiedKeyMaterial` via the S1 `SubjectContextClaims` trait — this IS the
37//! clearance seam. Until #698 wires the `clearance` field onto `Claims` in
38//! production, `security_context()` resolves to `None` and the PEP denies
39//! every request — which is correct fail-closed behavior, not a bug.
40//!
41//! ## Process-global installation
42//!
43//! Like the PQ trust store and compiled MAC policy, the PEP is installed at
44//! startup via [`install_mac_dispatch_pep`]. Until installed, dispatch denies
45//! with [`MacDenyReason::NoPepInstalled`]. Once installed, every request is
46//! mediated and every installed-PEP denial is authoritative.
47
48use std::sync::Arc;
49
50use super::label::SecurityLabel;
51use crate::service::EnvelopeContext;
52
53// ── Decision types ────────────────────────────────────────────────────────
54
55/// The MAC decision returned by the dispatch PEP.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum MacDecision {
58 /// Access permitted — proceed to handler.
59 Permit,
60 /// Access denied — handler MUST NOT be called.
61 Deny(MacDenyReason),
62}
63
64impl MacDecision {
65 /// Returns `true` if the decision is `Permit`.
66 #[inline]
67 #[must_use]
68 pub const fn is_permit(self) -> bool {
69 matches!(self, Self::Permit)
70 }
71}
72
73/// Why a MAC decision denied. Auditable and testable.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum MacDenyReason {
76 /// The process-global PEP has not been installed, or an operator
77 /// deliberately installed [`DenyAllMacPep`] as a fail-closed sentinel.
78 NoPepInstalled,
79 /// Subject has no derivable clearance (unlabeled subject).
80 ///
81 /// #698 is merged: production clearance resolves through the signed boot
82 /// policy's enrollment table (`EnrollmentSubjectContextResolver`), so this
83 /// deny now means the subject is not enrolled in the installed policy
84 /// generation — including the accepted enrollment-distribution lag, which
85 /// must never be bypassed.
86 NoClearance,
87 /// Object has no trusted label (unlabeled object).
88 ///
89 /// The `RpcObjectLabelResolver` returned `None` for this service+method.
90 /// Per D2/D3, objects deny/clamp — never default-allow.
91 UnlabeledObject,
92 /// Clearance does not dominate the object label (lattice floor deny).
93 ///
94 /// The subject's clearance exists and the object label exists, but
95 /// `SecurityContext::can_access` returned `false`.
96 FloorDeny,
97 /// Stale continuation authority (streaming re-check failed).
98 ///
99 /// A streaming continuation was re-checked and the subject's authority
100 /// has been revoked or the policy generation has rolled.
101 StaleAuthority,
102}
103
104// ── Object-label resolution seam ──────────────────────────────────────────
105
106/// Resolve the trusted [`SecurityLabel`] for the concrete object a
107/// dispatching RPC acts on.
108///
109/// `None` ⇒ unlabeled ⇒ the PEP **denies** (D2/D3 — objects deny/clamp,
110/// never default-allow). Implementors must NOT manufacture a permissive
111/// default.
112///
113/// `service_domain` is the canonical service name ("model", "registry", …).
114/// `method` is the full numeric method leaf path derived from the ONE decode
115/// of the signed request body (v16 §5.1) — the same identity the generated
116/// method policy resolved — else `None` when the dispatching service has no
117/// Cap'n Proto request schema (opaque bodies).
118///
119/// Production implementations will map static schema nodes (S3, #569) and
120/// content-addressed manifests to labels. The default implementation
121/// ([`DenyAllObjectResolver`]) returns `None` for everything — fail-closed.
122pub trait RpcObjectLabelResolver: Send + Sync {
123 fn resolve(&self, service_domain: &str, method: Option<&[u16]>) -> Option<SecurityLabel>;
124}
125
126/// Fail-closed object resolver: every object is unlabeled ⇒ deny.
127///
128/// This is the default when no production resolver has been wired. It makes
129/// the "no permissive default" invariant structural: a node that has not
130/// installed a resolver denies every request, regardless of clearance.
131#[derive(Debug, Default, Clone, Copy)]
132pub struct DenyAllObjectResolver;
133
134impl RpcObjectLabelResolver for DenyAllObjectResolver {
135 #[inline]
136 fn resolve(&self, _service_domain: &str, _method: Option<&[u16]>) -> Option<SecurityLabel> {
137 None
138 }
139}
140
141// ── The mandatory PEP trait ───────────────────────────────────────────────
142
143/// The mandatory, unavoidable RPC dispatch PEP for native MAC (epic #547,
144/// activation-gate T3, #1268).
145///
146/// Called by [`process_request`](crate::service::dispatch::process_request)
147/// after `verify_claims` and **before** `handle_request`. If the PEP returns
148/// [`MacDecision::Deny`], the handler is never invoked — the error payload
149/// is signed and returned to the caller.
150///
151/// If no PEP is installed process-globally, the dispatch wrapper denies with
152/// [`MacDenyReason::NoPepInstalled`]. Once installed, this check remains
153/// mandatory and cannot be bypassed.
154pub trait MacDispatchPep: Send + Sync {
155 /// Check mandatory MAC access before handler dispatch.
156 ///
157 /// `ctx` — the verified envelope context. The PEP derives the subject
158 /// clearance via [`EnvelopeContext::security_context`] (Claims ×
159 /// VerifiedKeyMaterial, S1 invariant). No schema change.
160 ///
161 /// `service_domain` — the canonical service name being dispatched to.
162 /// `method` — the full numeric method leaf path derived from the single
163 /// decode of the signed request body, else `None` for opaque bodies.
164 #[must_use]
165 fn check(
166 &self,
167 ctx: &EnvelopeContext,
168 service_domain: &str,
169 method: Option<&[u16]>,
170 ) -> MacDecision;
171}
172
173// ── Default PEP: clearance + object-label + can_access ────────────────────
174
175/// The production-shaped MAC dispatch PEP wiring the three-step check.
176///
177/// Composes:
178/// 1. [`EnvelopeContext::security_context`] (subject clearance — the #698
179/// seam; returns `None` until production clearance is wired),
180/// 2. an [`RpcObjectLabelResolver`] (trusted object label — stubbed with
181/// [`DenyAllObjectResolver`] until S3/#569 schema annotations land),
182/// 3. [`SecurityContext::can_access`] (the lattice floor).
183///
184/// Every missing input denies. There is no constructor that can produce a
185/// permissive PEP from these inputs.
186pub struct DefaultMacDispatchPep {
187 resolver: Box<dyn RpcObjectLabelResolver>,
188 activation_controlled: bool,
189}
190
191impl DefaultMacDispatchPep {
192 /// Construct with a specific object-label resolver.
193 pub fn new(resolver: Box<dyn RpcObjectLabelResolver>) -> Self {
194 Self {
195 resolver,
196 activation_controlled: false,
197 }
198 }
199
200 /// Select subject contexts through the process-global coverage gate.
201 ///
202 /// Production constructors opt into this explicitly. Direct unit-test
203 /// and embedding constructors retain their historical identity-aware
204 /// behavior so the operator gate cannot make unrelated PEP tests
205 /// order-dependent.
206 pub fn with_activation_control(mut self) -> Self {
207 self.activation_controlled = true;
208 self
209 }
210
211 /// Construct with the fail-closed [`DenyAllObjectResolver`].
212 ///
213 /// Every object resolves to `None` ⇒ every request denies
214 /// `UnlabeledObject`. This is the honest default until a production
215 /// resolver is wired.
216 pub fn fail_closed() -> Self {
217 Self::new(Box::new(DenyAllObjectResolver))
218 }
219}
220
221impl MacDispatchPep for DefaultMacDispatchPep {
222 fn check(
223 &self,
224 ctx: &EnvelopeContext,
225 service_domain: &str,
226 method: Option<&[u16]>,
227 ) -> MacDecision {
228 // Preserve the verified context for the direct VFS/CAS/MoQ PEPs, whose
229 // low-level APIs carry Subject but not the full verified envelope.
230 super::activation::remember_verified_subject(ctx);
231
232 // 1. Subject clearance selected by the coverage-gated activation
233 // control. Floor-only uses anonymous_floor; identity-aware consumes the
234 // two-input Claims × VerifiedKeyMaterial derivation.
235 let subject_ctx = if self.activation_controlled {
236 super::activation::global_mac_activation_control()
237 .select_context(ctx.security_context())
238 } else {
239 ctx.security_context()
240 };
241 let Some(subject_ctx) = subject_ctx else {
242 return MacDecision::Deny(MacDenyReason::NoClearance);
243 };
244
245 // 2. Trusted object label (never from a token/UCAN/caveat — design §3).
246 let Some(object_label) = self.resolver.resolve(service_domain, method) else {
247 return MacDecision::Deny(MacDenyReason::UnlabeledObject);
248 };
249
250 // 3. Lattice floor (intrinsic dominance check — no policy argument).
251 if subject_ctx.can_access(&object_label) {
252 MacDecision::Permit
253 } else {
254 MacDecision::Deny(MacDenyReason::FloorDeny)
255 }
256 }
257}
258
259/// A PEP that unconditionally denies.
260///
261/// Install this explicitly when dispatch must fail closed before a real
262/// object-label resolver is available. Leaving the global PEP uninstalled is
263/// also fail-closed.
264#[derive(Debug, Default, Clone, Copy)]
265pub struct DenyAllMacPep;
266
267impl MacDispatchPep for DenyAllMacPep {
268 #[inline]
269 fn check(
270 &self,
271 _ctx: &EnvelopeContext,
272 _service_domain: &str,
273 _method: Option<&[u16]>,
274 ) -> MacDecision {
275 MacDecision::Deny(MacDenyReason::NoPepInstalled)
276 }
277}
278
279// ── Process-global installation ───────────────────────────────────────────
280
281static GLOBAL_PEP: parking_lot::RwLock<Option<Arc<dyn MacDispatchPep>>> =
282 parking_lot::RwLock::new(None);
283
284/// Install the node's MAC dispatch PEP.
285///
286/// Production calls this exactly once at startup with a
287/// [`DefaultMacDispatchPep`] (or a production resolver). Until this is
288/// called, [`global_mac_dispatch_pep`] returns `None` and
289/// [`process_request`](crate::service::dispatch::process_request) denies.
290///
291/// Backed by `parking_lot::RwLock` (no poisoning). Production callers SHOULD
292/// install exactly once; the security boundary is the PEP trait itself (a PEP
293/// that denies is correct regardless of how many times it has been set).
294///
295/// # Activation gate (epic #1267)
296///
297/// Identity-aware subject selection remains a deliberate operator choice, but
298/// mediation is never off. Before installation the structural sentinel denies;
299/// after installation the production PEP remains mandatory.
300pub fn install_mac_dispatch_pep(pep: Arc<dyn MacDispatchPep>) {
301 *GLOBAL_PEP.write() = Some(pep);
302}
303
304/// The installed MAC dispatch PEP, if any.
305///
306/// `None` on a node that omitted installation. Dispatch treats this as a hard
307/// deny; installation is not an enforcement bypass boundary.
308#[must_use]
309pub fn global_mac_dispatch_pep() -> Option<Arc<dyn MacDispatchPep>> {
310 GLOBAL_PEP.read().clone()
311}
312
313/// Check the installed dispatch PEP, or deny if installation was omitted.
314///
315/// Once a PEP is installed, its result is returned unchanged: an installed
316/// fail-closed PEP cannot be bypassed by this wrapper.
317#[must_use]
318pub fn check_dispatch_mac(
319 ctx: &EnvelopeContext,
320 service_domain: &str,
321 method: Option<&[u16]>,
322) -> MacDecision {
323 match global_mac_dispatch_pep() {
324 Some(pep) => pep.check(ctx, service_domain, method),
325 None => MacDecision::Deny(MacDenyReason::NoPepInstalled),
326 }
327}
328
329// ── Tests ─────────────────────────────────────────────────────────────────
330
331#[cfg(test)]
332#[allow(clippy::unwrap_used, clippy::expect_used)]
333mod tests {
334 use super::*;
335 use crate::auth::mac::{Assurance, CompartmentSet, Level, SecurityLabel};
336
337 // ── test helpers ──────────────────────────────────────────────────
338
339 fn ctx_with_clearance(label: Option<SecurityLabel>) -> EnvelopeContext {
340 // Non-zero cnf so verified_key_material() returns Classical (not
341 // Unverified), and the given clearance on Claims.
342 EnvelopeContext::for_mac_test([1u8; 32], label)
343 }
344
345 fn public_label() -> SecurityLabel {
346 SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY)
347 }
348
349 fn secret_label() -> SecurityLabel {
350 SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY)
351 }
352
353 struct StaticResolver {
354 labels: std::collections::HashMap<String, SecurityLabel>,
355 }
356
357 impl RpcObjectLabelResolver for StaticResolver {
358 fn resolve(&self, service_domain: &str, _method: Option<&[u16]>) -> Option<SecurityLabel> {
359 self.labels.get(service_domain).copied()
360 }
361 }
362
363 // ── DenyAllObjectResolver ─────────────────────────────────────────
364
365 #[test]
366 fn deny_all_resolver_returns_none_for_everything() {
367 let r = DenyAllObjectResolver;
368 assert!(r.resolve("model", None).is_none());
369 assert!(r.resolve("anything", Some(&[42][..])).is_none());
370 }
371
372 // ── DenyAllMacPep ─────────────────────────────────────────────────
373
374 #[test]
375 fn deny_all_pep_denies_everything() {
376 let pep = DenyAllMacPep;
377 let ctx = ctx_with_clearance(Some(secret_label()));
378 let decision = pep.check(&ctx, "model", None);
379 assert_eq!(decision, MacDecision::Deny(MacDenyReason::NoPepInstalled));
380 assert!(!decision.is_permit());
381 }
382
383 // ── DefaultMacDispatchPep ─────────────────────────────────────────
384
385 #[test]
386 fn default_pep_permits_when_clearance_dominates_object_label() {
387 let resolver = Box::new(StaticResolver {
388 labels: [("model".to_owned(), public_label())].into(),
389 });
390 let pep = DefaultMacDispatchPep::new(resolver);
391 let ctx = ctx_with_clearance(Some(secret_label())); // Secret ⊒ Public
392
393 let decision = pep.check(&ctx, "model", None);
394 assert_eq!(decision, MacDecision::Permit);
395 }
396
397 #[test]
398 fn default_pep_denies_floor_when_clearance_does_not_dominate() {
399 let resolver = Box::new(StaticResolver {
400 labels: [("model".to_owned(), secret_label())].into(),
401 });
402 let pep = DefaultMacDispatchPep::new(resolver);
403 let ctx = ctx_with_clearance(Some(public_label())); // Public ⊉ Secret
404
405 let decision = pep.check(&ctx, "model", None);
406 assert_eq!(decision, MacDecision::Deny(MacDenyReason::FloorDeny));
407 }
408
409 #[test]
410 fn default_pep_denies_no_clearance_when_subject_has_none() {
411 let resolver = Box::new(StaticResolver {
412 labels: [("model".to_owned(), public_label())].into(),
413 });
414 let pep = DefaultMacDispatchPep::new(resolver);
415 let ctx = ctx_with_clearance(None); // unlabeled subject
416
417 let decision = pep.check(&ctx, "model", None);
418 assert_eq!(decision, MacDecision::Deny(MacDenyReason::NoClearance));
419 }
420
421 #[test]
422 fn default_pep_denies_unlabeled_object_when_resolver_returns_none() {
423 let pep = DefaultMacDispatchPep::fail_closed();
424 let ctx = ctx_with_clearance(Some(secret_label()));
425
426 let decision = pep.check(&ctx, "anything", None);
427 assert_eq!(decision, MacDecision::Deny(MacDenyReason::UnlabeledObject));
428 }
429
430 #[test]
431 fn default_pep_denies_for_unmapped_service() {
432 let resolver = Box::new(StaticResolver {
433 labels: [("model".to_owned(), public_label())].into(),
434 });
435 let pep = DefaultMacDispatchPep::new(resolver);
436 let ctx = ctx_with_clearance(Some(secret_label()));
437
438 let decision = pep.check(&ctx, "other_service", None);
439 assert_eq!(decision, MacDecision::Deny(MacDenyReason::UnlabeledObject));
440 }
441
442 // ── Process-global installation ───────────────────────────────────
443
444 /// Reset the global PEP to None for isolated testing of the no-PEP path.
445 fn reset_global_pep() {
446 *GLOBAL_PEP.write() = None;
447 }
448
449 #[test]
450 fn check_dispatch_mac_denies_while_pep_is_uninstalled() {
451 reset_global_pep();
452 assert!(global_mac_dispatch_pep().is_none());
453
454 let ctx = ctx_with_clearance(Some(secret_label()));
455 let decision = check_dispatch_mac(&ctx, "model", None);
456 assert_eq!(decision, MacDecision::Deny(MacDenyReason::NoPepInstalled));
457 }
458
459 #[test]
460 fn install_mac_dispatch_pep_is_swappable() {
461 reset_global_pep();
462
463 let pep1: Arc<dyn MacDispatchPep> = Arc::new(DefaultMacDispatchPep::fail_closed());
464 install_mac_dispatch_pep(pep1);
465 assert!(global_mac_dispatch_pep().is_some());
466
467 // Verify the installed PEP actually runs and fails closed.
468 let ctx = ctx_with_clearance(Some(secret_label()));
469 assert_eq!(
470 check_dispatch_mac(&ctx, "model", None),
471 MacDecision::Deny(MacDenyReason::UnlabeledObject),
472 "installed PEP must fail closed on an unlabeled object"
473 );
474
475 // Swap to a deny-all PEP — the RwLock allows replacement.
476 let pep2: Arc<dyn MacDispatchPep> = Arc::new(DenyAllMacPep);
477 install_mac_dispatch_pep(pep2);
478 assert_eq!(
479 check_dispatch_mac(&ctx, "model", None),
480 MacDecision::Deny(MacDenyReason::NoPepInstalled),
481 "DenyAllMacPep must deny after swap"
482 );
483
484 reset_global_pep();
485 }
486 // ── MacDecision helpers ───────────────────────────────────────────
487
488 #[test]
489 fn permit_is_permit() {
490 assert!(MacDecision::Permit.is_permit());
491 assert!(!MacDecision::Deny(MacDenyReason::FloorDeny).is_permit());
492 }
493}