hyprstream_vfs/mac_pep.rs
1//! **MAC PEP for the direct Namespace API** (#1272, epic #1267 T3).
2//!
3//! The 9P *translator* already mediates every wire op through
4//! `hyprstream_9p::AccessDecider` (implemented by `hyprstream::mac::pep`).
5//! But the **direct in-process `Namespace` API** — `cat`/`echo`/`create` and
6//! `mount`/`bind_mount`/`unmount` — forwards a plain [`Subject`] to the
7//! resolving [`Mount`](crate::Mount) with no mandatory label lookup or
8//! reference monitor, bypassing the translator PEP entirely. This module is
9//! that missing reference monitor: the contract the `Namespace` invokes per
10//! op, plus its fail-closed defaults.
11//!
12//! ## Dependency-direction (mirrors the 9P split)
13//!
14//! The *trait* (the contract the low-level `Namespace` consumes) lives here in
15//! `hyprstream-vfs`, exactly as `hyprstream_9p::AccessDecider` lives in the 9P
16//! crate. The *production audited implementation* — bridging to the real
17//! `RpcObjectLabelResolver`, `SecurityContext::can_access`, and the
18//! tamper-evident MAC audit sink — lives in `hyprstream::mac::pep`, alongside
19//! `NinePAccessDecider`. This keeps the dependency direction one-way
20//! (`hyprstream` → `hyprstream-vfs`) and **does not reinvent label resolution,
21//! clearance, or `can_access`**; those are S1/S4 primitives re-exported from
22//! `hyprstream_rpc::auth::mac`.
23//!
24//! ## Fail-closed by construction; no permissive mode (#547)
25//!
26//! Every seam has an explicit deny-all default. A [`NamespacePep`] authorizes
27//! an op only when ALL of:
28//! 1. the caller's [`Subject`] resolves to a verified [`SecurityContext`]
29//! (clearance provenance — #698; `None` ⇒ deny),
30//! 2. the walked object resolves to a [`SecurityLabel`] via the injected
31//! [`RpcObjectLabelResolver`] (`None` ⇒ deny — "no unlabeled-default-allow"),
32//! 3. `clearance.can_access(object_label)` (BLP dominance) AND the
33//! [`NamespaceAccessDecider`] permit.
34//! There is no permissive path *inside* the PEP.
35//!
36//! ## Activation posture (dormant structure)
37//!
38//! A [`Namespace`](crate::Namespace) built with [`Namespace::new`] carries
39//! `pep: None` and behaves exactly as before — the un-enforced status quo,
40//! matching the rest of MAC enforcement being dormant today (CLAUDE.md "MAC
41//! current status"). Installing a PEP via
42//! [`Namespace::with_pep`](crate::Namespace::with_pep) arms the fail-closed
43//! monitor: every mediated op then requires a proven subject, and the
44//! subject-less `mount`/`bind_mount`/`unmount` deny (use the `_as` variants).
45//! Flipping the default at construction sites is the separately-gated
46//! activation B-lane (#1267), not this PR.
47
48#[cfg(not(target_arch = "wasm32"))]
49use std::sync::Arc;
50
51#[cfg(not(target_arch = "wasm32"))]
52pub use hyprstream_rpc::auth::mac::{
53 MacDecision, MacDenyReason, RpcObjectLabelResolver, SecurityContext, SecurityLabel,
54};
55#[cfg(not(target_arch = "wasm32"))]
56use hyprstream_rpc::Subject;
57
58#[cfg(not(target_arch = "wasm32"))]
59use crate::NamespaceError;
60
61/// The direct-`Namespace`-API operation a [`NamespaceAccessDecider`] is asked
62/// to authorize.
63///
64/// This is the VFS-plane action surface — broader than the 9P translator's
65/// `hyprstream_9p::Action` because the direct API also mutates the namespace
66/// itself (`Mount`/`BindMount`/`Unmount`), ops the wire translator never
67/// dispatches. Mirrors [`Namespace`](crate::Namespace)'s convenience methods.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69pub enum NamespaceAction {
70 /// `cat` / `read_one` / `ls` — read-class.
71 Read,
72 /// `echo` / `ctl` — write-class.
73 Write,
74 /// `create` — new-object creation.
75 Create,
76 /// `mount` — install/replace a mount point (namespace mutation).
77 Mount,
78 /// `bind_mount` — union-bind a target (namespace mutation).
79 BindMount,
80 /// `unmount` — remove a mount point (namespace mutation).
81 Unmount,
82 /// Extract raw mount targets from the namespace.
83 ///
84 /// A returned [`crate::MountTarget`] can invoke the complete `Mount`
85 /// surface, including writes, without re-entering [`crate::Namespace`].
86 /// This is therefore a privileged, write-capable action rather than a
87 /// read-only path lookup.
88 ResolveHandle,
89}
90
91/// Plane-specific clearance-input seam: resolve a direct-API [`Subject`] to the
92/// verified [`SecurityContext`] that authorizes it.
93///
94/// This is the VFS-plane half of **#698** (production clearance provenance).
95/// The companion RPC-dispatch seam (claims → `SecurityContext` threading at
96/// dispatch) is owned by **#1268**, which will publish its interface to
97/// `.fleet-coord/mac-pep-contract.md`. Until that lands, this trait is the
98/// plane-specific resolution point: a `Subject` (the only identity the direct
99/// API carries — no verified `EnvelopeContext` crosses it) becomes a clearance
100/// only through verified credential material this resolver consults.
101///
102/// **Returning `None` is the mandatory fail-closed contract** — a subject
103/// whose clearance cannot be established from verified credential material
104/// MUST NOT be authorized; there is no permissive default (#547).
105/// Implementations MUST NOT derive clearance from an unverified,
106/// caller-supplied label (D1 — labels in wire schemas are hints; here the
107/// `Subject` name is even weaker: an unauthenticated string).
108///
109/// Async because the production resolver revalidates credential-bearing
110/// cached subject contexts against the canonical revocation authority on
111/// every read.
112#[cfg(not(target_arch = "wasm32"))]
113#[async_trait::async_trait]
114pub trait SubjectContextResolver: Send + Sync {
115 /// Resolve `subject` to its verified security context, or `None` if its
116 /// clearance cannot be proven — which the PEP treats as deny.
117 async fn resolve(&self, subject: &Subject) -> Option<SecurityContext>;
118}
119
120/// Fail-closed resolver: no subject resolves to a clearance.
121///
122/// This is the default a [`NamespacePep`] uses for the subject seam when no
123/// production resolver (#698) has been wired — every mediated op denies.
124#[cfg(not(target_arch = "wasm32"))]
125#[derive(Debug, Default, Clone, Copy)]
126pub struct DenyAllSubjects;
127
128#[cfg(not(target_arch = "wasm32"))]
129#[async_trait::async_trait]
130impl SubjectContextResolver for DenyAllSubjects {
131 async fn resolve(&self, _subject: &Subject) -> Option<SecurityContext> {
132 // No SubjectContextResolver wired (#698 not landed). The authorize()
133 // path passes `None` to the authoritative decider, which audits the
134 // no-clearance denial before returning it. This low-level crate does
135 // not own the audit WAL or a tracing dependency.
136 None
137 }
138}
139
140/// Authorizes one direct-`Namespace` operation against the attempted subject
141/// context and object label.
142///
143/// Label resolution is centralized in [`NamespacePep::authorize`] (the
144/// reference monitor), which calls the injected [`RpcObjectLabelResolver`] and
145/// hands the result here. Missing clearance and missing labels are deliberately
146/// represented as `None` so the authoritative implementation in the
147/// `hyprstream` crate can write those fail-closed decisions to the same
148/// tamper-evident WAL as policy-floor denials. No deny may return before this
149/// audit boundary.
150#[cfg(not(target_arch = "wasm32"))]
151pub trait NamespaceAccessDecider: Send + Sync {
152 /// Return the canonical MAC decision and record every outcome through the
153 /// MAC audit sink.
154 ///
155 /// `None` inputs are mandatory denials: an absent `ctx` means clearance
156 /// could not be proven, while an absent `object_label` means the object is
157 /// unlabeled. Implementations use bottom labels only as audit-schema
158 /// placeholders; placeholders must never participate in authorization.
159 fn check(
160 &self,
161 ctx: Option<&SecurityContext>,
162 object_label: Option<SecurityLabel>,
163 action: NamespaceAction,
164 ) -> MacDecision;
165}
166
167/// Fail-closed decider for a [`NamespacePep`] whose production audited decider
168/// is unavailable. Every op denies.
169#[cfg(not(target_arch = "wasm32"))]
170#[derive(Debug, Default, Clone, Copy)]
171pub struct DenyAllNamespace;
172
173#[cfg(not(target_arch = "wasm32"))]
174impl NamespaceAccessDecider for DenyAllNamespace {
175 fn check(
176 &self,
177 _ctx: Option<&SecurityContext>,
178 _object_label: Option<SecurityLabel>,
179 _action: NamespaceAction,
180 ) -> MacDecision {
181 MacDecision::Deny(MacDenyReason::NoPepInstalled)
182 }
183}
184
185/// Fail-closed label resolver: no object resolves. Mirrors
186/// `hyprstream_9p::DenyUnlabeledResolver`. Returning `None` is a mandatory
187/// deny (design §1 invariant 2) — the PEP refuses to authorize any op whose
188/// object has no trusted label.
189#[cfg(not(target_arch = "wasm32"))]
190#[derive(Debug, Default, Clone, Copy)]
191pub struct DenyUnlabeledResolver;
192
193#[cfg(not(target_arch = "wasm32"))]
194impl RpcObjectLabelResolver for DenyUnlabeledResolver {
195 fn resolve(&self, _service_domain: &str, _method: Option<&[u16]>) -> Option<SecurityLabel> {
196 None
197 }
198}
199
200/// The mandatory, all-or-nothing reference monitor a
201/// [`Namespace`](crate::Namespace) mediates every direct-API op through once
202/// installed.
203///
204/// There is no permissive or partial construction: each of the three seams is
205/// required, and the crate's fail-closed defaults ([`DenyAllSubjects`],
206/// [`DenyAllNamespace`], and the `None`-returning
207/// [`hyprstream_rpc::auth::mac`] `RpcObjectLabelResolver` the `hyprstream` crate
208/// supplies) are the explicit choices for a seam the application does not yet
209/// populate. Building a `NamespacePep` is therefore always fail-closed;
210/// "unenforced" is represented by *not installing* one on the `Namespace`
211/// (the dormant status quo), never by a permissive PEP.
212#[cfg(not(target_arch = "wasm32"))]
213pub struct NamespacePep {
214 subjects: Arc<dyn SubjectContextResolver>,
215 labels: Arc<dyn RpcObjectLabelResolver>,
216 decider: Arc<dyn NamespaceAccessDecider>,
217}
218
219#[cfg(not(target_arch = "wasm32"))]
220impl std::fmt::Debug for NamespacePep {
221 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222 f.debug_struct("NamespacePep").finish_non_exhaustive()
223 }
224}
225
226#[cfg(not(target_arch = "wasm32"))]
227impl NamespacePep {
228 /// Assemble the monitor from its three mandatory seams.
229 ///
230 /// Callers that lack a production seam pass the crate's deny-all default
231 /// for it — the resulting PEP denies every op, which is the correct
232 /// posture for "structure present, inputs not yet wired" (the #698 /
233 /// #1268 dependency window). There is no `new_permissive`.
234 pub fn new(
235 subjects: Arc<dyn SubjectContextResolver>,
236 labels: Arc<dyn RpcObjectLabelResolver>,
237 decider: Arc<dyn NamespaceAccessDecider>,
238 ) -> Self {
239 Self {
240 subjects,
241 labels,
242 decider,
243 }
244 }
245
246 /// Authorize `action` by `subject` against `object`.
247 ///
248 /// Fail-closed sequence (any deny ⇒ [`NamespaceError::Denied`]):
249 /// 1. resolve `subject` → optional `SecurityContext`,
250 /// 2. resolve `object` → `SecurityLabel` via the injected
251 /// [`RpcObjectLabelResolver`] (missing means no unlabeled-default-allow;
252 /// design §1 invariant 2),
253 /// 3. `decider.check(ctx, label, action)` — audit every outcome, including
254 /// missing-clearance and missing-label denials, then apply
255 /// `can_access` + TE floor; canonical [`MacDecision::Deny`] ⇒ deny,
256 /// 4. permit.
257 ///
258 /// `object_path` is the canonical normalized VFS path. It occupies the
259 /// canonical resolver's `service_domain` slot; VFS has no browser method
260 /// discriminator, so `method` is always `None`. The caller never supplies a
261 /// label (D1 — caller labels are forbidden).
262 pub async fn authorize(
263 &self,
264 subject: &Subject,
265 object_path: &str,
266 action: NamespaceAction,
267 ) -> Result<(), NamespaceError> {
268 match self.check(subject, object_path, action).await {
269 MacDecision::Permit => Ok(()),
270 MacDecision::Deny(reason) => Err(NamespaceError::Denied(
271 action,
272 denial_detail(subject, deny_reason_detail(reason)),
273 )),
274 }
275 }
276
277 /// Evaluate one VFS operation using the canonical shared MAC decision
278 /// contract. An installed `NamespacePep` is always fail-closed.
279 pub async fn check(
280 &self,
281 subject: &Subject,
282 object_path: &str,
283 action: NamespaceAction,
284 ) -> MacDecision {
285 let ctx = self.subjects.resolve(subject).await;
286 let label = self.labels.resolve(object_path, None);
287 self.decider.check(ctx.as_ref(), label, action)
288 }
289
290 /// Record and return the mandatory no-clearance denial for a subject-less
291 /// namespace mutation.
292 ///
293 /// Armed construction APIs have no caller to resolve, but their forced
294 /// denial must still cross the same audit boundary as every subjectful
295 /// operation. The decider contract requires `ctx=None` to deny and record
296 /// the attempt; a non-conforming permit is nevertheless downgraded to
297 /// `NoClearance`.
298 pub(crate) fn deny_uncredentialed(
299 &self,
300 object_path: &str,
301 action: NamespaceAction,
302 ) -> NamespaceError {
303 let label = self.labels.resolve(object_path, None);
304 let reason = match self.decider.check(None, label, action) {
305 MacDecision::Deny(reason) => reason,
306 MacDecision::Permit => MacDenyReason::NoClearance,
307 };
308 NamespaceError::Denied(
309 action,
310 denial_detail(&Subject::anonymous(), deny_reason_detail(reason)),
311 )
312 }
313}
314
315#[cfg(not(target_arch = "wasm32"))]
316fn denial_detail(subject: &Subject, reason: &str) -> String {
317 match subject.name() {
318 Some(n) => format!("'{n}': {reason}"),
319 None => format!("<anonymous>: {reason}"),
320 }
321}
322
323#[cfg(not(target_arch = "wasm32"))]
324const fn deny_reason_detail(reason: MacDenyReason) -> &'static str {
325 match reason {
326 MacDenyReason::NoPepInstalled => "explicit deny-all PEP installed",
327 MacDenyReason::NoClearance => "subject clearance unprovable",
328 MacDenyReason::UnlabeledObject => "object unlabeled",
329 MacDenyReason::FloorDeny => "MAC floor denied",
330 MacDenyReason::StaleAuthority => "stale authority",
331 }
332}
333
334#[cfg(all(test, not(target_arch = "wasm32")))]
335mod tests {
336 use super::*;
337 use hyprstream_rpc::auth::mac::{
338 Assurance, CompartmentSet, Level, SecurityLabel, VerifiedKeyMaterial,
339 };
340
341 fn ctx(level: Level) -> SecurityContext {
342 SecurityContext::from_clearance(label(level), VerifiedKeyMaterial::Classical)
343 }
344 fn label(level: Level) -> SecurityLabel {
345 SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY)
346 }
347 fn subject(name: &str) -> Subject {
348 Subject::new(name)
349 }
350
351 /// A resolver that maps one subject name to a fixed clearance; all others
352 /// `None` (deny).
353 struct OneSubject {
354 name: &'static str,
355 ctx: SecurityContext,
356 }
357 #[async_trait::async_trait]
358 impl SubjectContextResolver for OneSubject {
359 async fn resolve(&self, s: &Subject) -> Option<SecurityContext> {
360 (s.name() == Some(self.name)).then(|| self.ctx.clone())
361 }
362 }
363
364 /// A decider that permits reads at-or-below the subject's level and denies
365 /// everything else (write-class = deny, mirroring the IFC write-direction
366 /// pause the 9P PEP enforces).
367 struct ReadFloorDecider;
368 impl NamespaceAccessDecider for ReadFloorDecider {
369 fn check(
370 &self,
371 ctx: Option<&SecurityContext>,
372 object_label: Option<SecurityLabel>,
373 action: NamespaceAction,
374 ) -> MacDecision {
375 let Some(ctx) = ctx else {
376 return MacDecision::Deny(MacDenyReason::NoClearance);
377 };
378 let Some(object_label) = object_label else {
379 return MacDecision::Deny(MacDenyReason::UnlabeledObject);
380 };
381 if action != NamespaceAction::Read {
382 return MacDecision::Deny(MacDenyReason::FloorDeny);
383 }
384 if ctx.clearance().can_access(&object_label) {
385 MacDecision::Permit
386 } else {
387 MacDecision::Deny(MacDenyReason::FloorDeny)
388 }
389 }
390 }
391
392 /// A resolver that labels the first path component as a level (test-only).
393 struct PathLevelResolver;
394 impl RpcObjectLabelResolver for PathLevelResolver {
395 fn resolve(&self, service_domain: &str, _method: Option<&[u16]>) -> Option<SecurityLabel> {
396 match service_domain {
397 "/public" => Some(label(Level::Public)),
398 "/secret" => Some(label(Level::Secret)),
399 _ => None,
400 }
401 }
402 }
403
404 #[tokio::test]
405 async fn deny_all_pep_denies_every_subject() {
406 // All three seams deny: subject unresolvable ⇒ DenyAllSubjects ⇒ None
407 // ⇒ the PEP returns Err before the decider is even consulted.
408 let pep = NamespacePep::new(
409 Arc::new(DenyAllSubjects),
410 Arc::new(DenyUnlabeledResolver),
411 Arc::new(DenyAllNamespace),
412 );
413 let err = pep
414 .authorize(&subject("anyone"), "/x", NamespaceAction::Read)
415 .await
416 .unwrap_err();
417 assert!(matches!(err, NamespaceError::Denied(_, _)));
418 }
419
420 #[tokio::test]
421 async fn deny_unlabeled_object_denies_even_with_a_valid_subject() {
422 // Subject resolves, but the object is unlabeled ⇒ deny (invariant 2).
423 let pep = NamespacePep::new(
424 Arc::new(OneSubject {
425 name: "alice",
426 ctx: ctx(Level::Secret),
427 }),
428 Arc::new(DenyUnlabeledResolver),
429 Arc::new(ReadFloorDecider),
430 );
431 assert!(pep
432 .authorize(&subject("alice"), "/secret", NamespaceAction::Read)
433 .await
434 .is_err());
435 }
436
437 #[tokio::test]
438 async fn pep_permits_read_when_clearance_dominates_and_denies_otherwise() {
439 let pep = NamespacePep::new(
440 Arc::new(OneSubject {
441 name: "alice",
442 ctx: ctx(Level::Secret),
443 }),
444 Arc::new(PathLevelResolver),
445 Arc::new(ReadFloorDecider),
446 );
447
448 // alice (Secret) reading /secret ⇒ permit.
449 assert!(pep
450 .authorize(&subject("alice"), "/secret", NamespaceAction::Read)
451 .await
452 .is_ok());
453 // Write ⇒ deny (write-direction pause).
454 assert!(pep
455 .authorize(&subject("alice"), "/public", NamespaceAction::Write)
456 .await
457 .is_err());
458 // Unenrolled subject ⇒ deny (fail-closed clearance).
459 assert!(pep
460 .authorize(&subject("mallory"), "/public", NamespaceAction::Read)
461 .await
462 .is_err());
463 }
464}