Skip to main content

hyprstream_core/mac/
pep.rs

1//! Authoritative 9P policy-enforcement point.
2//!
3//! The translator supplies the verified caller context and walked object
4//! reference. This decider resolves the content-truth label, applies the
5//! intrinsic lattice dominance rule (read-direction `can_access` for reads,
6//! write-direction `can_write_to` for writes), and records every outcome
7//! through the existing tamper-evident MAC audit sink.
8//!
9//! ## Activation (#1269)
10//!
11//! [`production_ninep_reference_monitor`] assembles the full
12//! [`ReferenceMonitor`](hyprstream_9p::ReferenceMonitor) from the mandatory
13//! decider, the genesis content-truth resolver, and an attach authenticator.
14//! Production 9P constructors install the monitor via
15//! `Translator::with_reference_monitor`. HTTP and WebTransport attach paths
16//! now supply one unified verified attach bundle; transports without a
17//! credential carrier explicitly retain the deny-only authenticator. The
18//! operator gate selects floor-only or identity-aware context without removing
19//! this monitor.
20
21use std::sync::Arc;
22use std::time::{SystemTime, UNIX_EPOCH};
23
24use anyhow::Context;
25use hyprstream_9p::{
26    AccessDecider, Action as NinePAction, AnonymousAuthenticator, AttachAuthenticator,
27    ReferenceMonitor, ReferenceMonitorDenyReason, SessionContext, VerifiedAttachIdentity,
28};
29use hyprstream_rpc::auth::mac::{
30    MacDecision, MacDenyReason, ObjectLabelResolver, ObjectRef, SecurityContext, SecurityLabel,
31};
32use hyprstream_rpc::SigningKey;
33
34use crate::mac::audit::{AuditRecord, AuditSink, DecisionReason};
35use crate::mac::te::{Action, Decision, ObjectType, ScopeAction, SubjectType};
36
37/// Reserved audit identities for 9P PEP decisions. Real compiled-policy type
38/// ids grow upward from zero; these sentinels live below the grant-path
39/// `u32::MAX` sentinels and cannot collide.
40const NINEP_SUBJECT_TYPE: SubjectType = SubjectType(u32::MAX - 1);
41const NINEP_OBJECT_TYPE: ObjectType = ObjectType(u32::MAX - 1);
42
43/// Resolver-backed, audited 9P access decider.
44pub struct NinePAccessDecider {
45    resolver: Arc<dyn ObjectLabelResolver + Send + Sync>,
46    sink: Arc<dyn AuditSink>,
47}
48
49impl NinePAccessDecider {
50    pub fn new(
51        resolver: Arc<dyn ObjectLabelResolver + Send + Sync>,
52        sink: Arc<dyn AuditSink>,
53    ) -> Self {
54        Self { resolver, sink }
55    }
56
57    fn audit(
58        &self,
59        ctx: &SecurityContext,
60        label: Option<SecurityLabel>,
61        action: NinePAction,
62        decision: Decision,
63        reason: DecisionReason,
64    ) -> bool {
65        let policy = crate::mac::compiled_policy();
66        let generation = policy.as_ref().map_or(0, |p| p.generation);
67        let policy_hash = policy.as_ref().and_then(|p| p.policy_hash().ok());
68        let record = AuditRecord {
69            seq: 0,
70            prev_hash: [0; 32],
71            ts_unix_nanos: SystemTime::now()
72                .duration_since(UNIX_EPOCH)
73                .map_or(0, |d| d.as_nanos()),
74            decision,
75            generation,
76            policy_hash,
77            subject_type: NINEP_SUBJECT_TYPE,
78            subject_clearance: *ctx.clearance(),
79            on_behalf_of: None,
80            object_type: NINEP_OBJECT_TYPE,
81            // No label exists on an unresolved decision. The bottom value is
82            // an audit-schema placeholder only; `UnlabeledObject` is the
83            // authoritative reason and the value never enters authorization.
84            object_label: label.unwrap_or_else(SecurityLabel::bottom),
85            action: audit_action(action),
86            reason,
87            subject_id: None,
88            object_id: None,
89        };
90
91        match self.sink.record(&record) {
92            Ok(()) => decision.is_permit(),
93            Err(error) => {
94                let deny_record = AuditRecord {
95                    decision: Decision::Deny,
96                    reason: DecisionReason::AuditFailClosed,
97                    ..record
98                };
99                let _ = self.sink.record(&deny_record);
100                tracing::error!(
101                    target: "hyprstream.mac.audit",
102                    %error,
103                    reason = DecisionReason::AuditFailClosed.as_str(),
104                    "9P decision could not be durably audited; enforcing deny"
105                );
106                false
107            }
108        }
109    }
110}
111
112/// Build the production resolver-backed 9P PEP and its tamper-evident WAL.
113///
114/// The audit signer is mandatory under the active crypto policy. Callers must
115/// propagate an error from this function and refuse to construct a 9P-serving
116/// component; substituting [`hyprstream_9p::DenyAllDecider`] would both outage
117/// legitimate attaches and bypass the hash-chained MAC audit trail.
118pub async fn production_ninep_decider(
119    signing_key: SigningKey,
120    oauth: &crate::config::OAuthConfig,
121    audit_stream: &str,
122) -> anyhow::Result<Arc<dyn AccessDecider>> {
123    anyhow::ensure!(
124        !audit_stream.is_empty()
125            && audit_stream
126                .bytes()
127                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_'),
128        "invalid 9P MAC audit stream name"
129    );
130
131    let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir()?;
132    let ml_dsa_store = crate::auth::key_rotation::global_ml_dsa_key_store(&secrets_dir, oauth);
133    let signer = crate::mac::audit::cose::OwnedCoseAuditSigner::new(
134        Arc::new(signing_key),
135        ml_dsa_store.active_key().await,
136        hyprstream_rpc::envelope::mandatory_envelope_policy(),
137    );
138    anyhow::ensure!(
139        signer.can_sign(),
140        "9P MAC PEP audit signer unavailable under mandatory Hybrid policy"
141    );
142
143    let audit_store = crate::mac::audit::WalAuditStore::open(
144        secrets_dir.join("mac-audit").join(audit_stream),
145        signer,
146    )
147    .context("open 9P MAC audit store")?;
148    let resolver = crate::mac::GenesisGate::production().into_resolver();
149
150    Ok(Arc::new(NinePAccessDecider::new(
151        Arc::new(resolver),
152        Arc::new(audit_store),
153    )))
154}
155
156// ─────────────────────────────────────────────────────────────────────────────
157// #1269 — ReferenceMonitor activation: clearance seam, authenticator, assembler
158// ─────────────────────────────────────────────────────────────────────────────
159
160/// Clearance provenance seam for the 9P MAC PEP (#698 dependency).
161///
162/// The production reference monitor derives a subject's [`SecurityContext``
163/// from **verified attach credentials** — not from a caller-supplied label.
164/// Until #698 wires the real clearance-issuance path, the production impl
165/// resolves clearance from the compiled policy's enrollment table keyed by
166/// the verified subject DID ([`EnrollmentClearanceSource`]). An unenrolled DID
167/// or absent compiled policy resolves to `None` → mandatory deny (there is no
168/// permissive default per #547).
169///
170/// This trait is the **clean clearance-input seam** the fleet-coordination
171/// contract asks each activation lane to expose: plane-specific label
172/// resolution and the clearance source are the two independent inputs the
173/// monitor needs, and this is the clearance one.
174pub trait NinePClearanceSource: Send + Sync {
175    /// Derive the verified subject's clearance context from `verified_subject`
176    /// (a DID or stable credential fingerprint obtained from verified attach
177    /// material, **never** an unverified `Tattach.uname` string).
178    ///
179    /// Returns `None` to deny — the monitor constructs [`SessionContext::deny`]
180    /// or a token-less fail-closed session.
181    fn clearance_for(&self, verified_subject: &str) -> Option<SecurityContext>;
182}
183
184/// Production clearance source backed by the compiled policy's enrollment
185/// table via [`crate::mac::exchange_enrollment_resolver`] (#698 Decision D).
186///
187/// Assurance is floored at `Classical` unconditionally — the truthful label for
188/// what the enrollment crypto proves. Raising an actor above Classical is the
189/// enrollment-key-registration follow-up (#718).
190///
191/// When no compiled policy is installed (early boot / dormant node), the
192/// resolver returns `None` for every DID → fail-closed.
193#[derive(Debug, Default, Clone, Copy)]
194pub struct EnrollmentClearanceSource;
195
196impl NinePClearanceSource for EnrollmentClearanceSource {
197    fn clearance_for(&self, verified_subject: &str) -> Option<SecurityContext> {
198        let resolver = crate::mac::exchange_enrollment_resolver();
199        resolver.resolve(verified_subject)
200    }
201}
202
203/// Constructs a 9P [`SessionContext`] from an identity that an attach
204/// credential verifier has already authenticated and tenant-bound.
205///
206/// **Fail-closed by construction** — there is no permissive path:
207/// - An unresolvable clearance (unenrolled DID, no policy) →
208///   [`SessionContext::deny`].
209/// - A resolvable clearance but **no S6 sender-bound token** (the token path
210///   is not yet wired into 9P `Tattach`) →
211///   [`SessionContext::from_verified_clearance`], which denies every op at the
212///   token gate.
213///
214/// This type deliberately does **not** implement [`AttachAuthenticator`]:
215/// that trait receives raw `Tattach` fields, while this factory accepts only a
216/// [`VerifiedAttachIdentity`] produced after credential verification. This
217/// prevents raw `uname` from silently becoming a verified identity when S6 is
218/// wired.
219pub struct VerifiedClearanceSessionFactory<C: NinePClearanceSource> {
220    clearance: Arc<C>,
221}
222
223impl<C: NinePClearanceSource> VerifiedClearanceSessionFactory<C> {
224    pub fn new(clearance: Arc<C>) -> Self {
225        Self { clearance }
226    }
227
228    /// Derive a token-less, fail-closed session from a credential-verified,
229    /// tenant-bound identity.
230    pub fn session_for(&self, identity: VerifiedAttachIdentity) -> SessionContext {
231        let Some(security_context) = self.clearance.clearance_for(identity.subject()) else {
232            return SessionContext::deny();
233        };
234        SessionContext::from_verified_clearance(identity, security_context)
235    }
236}
237
238/// Assemble the production 9P [`ReferenceMonitor`] from the mandatory audited
239/// decider, the genesis content-truth label resolver, and a clearance source.
240///
241/// All three seams are required (all-or-nothing enforcement). The caller must
242/// supply an authenticator that verifies the attach credential itself; passing
243/// [`AnonymousAuthenticator`] explicitly selects the fail-closed state for
244/// transports whose verified attach-credential path is not yet wired.
245pub fn production_ninep_reference_monitor(
246    decider: Arc<dyn AccessDecider>,
247    authenticator: Arc<dyn AttachAuthenticator>,
248) -> Arc<ReferenceMonitor> {
249    let resolver = crate::mac::GenesisGate::production().into_resolver();
250    Arc::new(ReferenceMonitor::new(
251        authenticator,
252        Arc::new(resolver),
253        decider,
254    ))
255}
256
257/// Assemble the production reference monitor in its current fail-closed state.
258///
259/// The raw 9P attach fields are not credential proof. This helper therefore
260/// refuses to derive an identity or tenant from them; a later S6 integration
261/// must replace the authenticator with one backed by verified attach material.
262pub fn enrollment_ninep_reference_monitor(
263    decider: Arc<dyn AccessDecider>,
264) -> Arc<ReferenceMonitor> {
265    // No production 9P transport currently passes a verified, sender-bound S6
266    // credential into the monitor. Raw `Tattach.uname` is untrusted, so the
267    // only safe activation state is an explicit deny-only authenticator.
268    production_ninep_reference_monitor(decider, Arc::new(AnonymousAuthenticator))
269}
270
271impl AccessDecider for NinePAccessDecider {
272    fn check(&self, ctx: &SecurityContext, object: ObjectRef<'_>, action: NinePAction) -> bool {
273        let Some(label) = self.resolver.resolve(object) else {
274            return self.audit(
275                ctx,
276                None,
277                action,
278                Decision::Deny,
279                DecisionReason::UnlabeledObject,
280            );
281        };
282
283        // Read-direction IFC: no-read-up (simple security / dominance).
284        // Write-direction IFC: no-write-down (*-property / confinement).
285        // The assurance axis is a crypto floor in both directions.
286        let permitted = if matches!(action, NinePAction::Write) {
287            ctx.can_write_to(&label)
288        } else {
289            ctx.can_access(&label)
290        };
291        self.audit(
292            ctx,
293            Some(label),
294            action,
295            if permitted {
296                Decision::Permit
297            } else {
298                Decision::Deny
299            },
300            if permitted {
301                DecisionReason::Permit
302            } else {
303                DecisionReason::FloorDeny
304            },
305        )
306    }
307
308    fn audit_denial(
309        &self,
310        ctx: &SecurityContext,
311        _object: ObjectRef<'_>,
312        object_label: Option<SecurityLabel>,
313        action: NinePAction,
314        reason: ReferenceMonitorDenyReason,
315    ) {
316        let reason = match reason {
317            ReferenceMonitorDenyReason::UnlabeledObject => DecisionReason::UnlabeledObject,
318            ReferenceMonitorDenyReason::TokenGate => DecisionReason::TokenGate,
319            ReferenceMonitorDenyReason::FloorDeny => DecisionReason::FloorDeny,
320        };
321        let _ = self.audit(ctx, object_label, action, Decision::Deny, reason);
322    }
323}
324
325const fn audit_action(action: NinePAction) -> Action {
326    match action {
327        NinePAction::Write => Action::from_scope_action(ScopeAction::Write),
328        NinePAction::Attach
329        | NinePAction::Walk
330        | NinePAction::Open
331        | NinePAction::Read
332        | NinePAction::Getattr
333        | NinePAction::Readdir => Action::from_scope_action(ScopeAction::Query),
334    }
335}
336
337// ─────────────────────────────────────────────────────────────────────────────
338// VFS-plane PEP — the direct `Namespace` API reference monitor (#1272).
339//
340// Mirrors `NinePAccessDecider` for the *in-process* direct API: the 9P
341// translator decider authorizes wire ops; this decider authorizes the
342// `Namespace::cat`/`echo`/`create`/`ls`/`ctl` convenience methods (and the
343// `mount`/`bind_mount`/`unmount` mutation surface) once a `NamespacePep` is
344// installed. It reuses the SAME `ObjectLabelResolver` (the genesis composite),
345// the SAME `AuditSink` (the WAL), and the SAME `can_access` floor — it does
346// not reinvent any MAC primitive, only adapts the action surface.
347// ─────────────────────────────────────────────────────────────────────────────
348
349use hyprstream_vfs::{NamespaceAccessDecider, NamespaceAction, SubjectContextResolver};
350
351/// Reserved audit subject/object type ids for VFS-PEP decisions (distinct from
352/// the 9P sentinels above so audit consumers can distinguish the plane).
353const VFS_SUBJECT_TYPE: SubjectType = SubjectType(u32::MAX - 2);
354const VFS_OBJECT_TYPE: ObjectType = ObjectType(u32::MAX - 2);
355
356/// Audited `NamespaceAccessDecider` for the direct VFS API (#1272).
357///
358/// This is the production impl of [`hyprstream_vfs::NamespaceAccessDecider`]:
359/// it applies the intrinsic lattice dominance rule for read-class operations,
360/// denies write-class pending the VFS IFC write-direction decision, and records
361/// every outcome through the MAC audit sink. It
362/// receives the attempted subject context and label resolution from
363/// [`hyprstream_vfs::NamespacePep`], including `None` for missing clearance or
364/// labels, so fail-closed precondition denials cannot bypass the audit WAL.
365pub struct VfsAccessDecider {
366    sink: Arc<dyn AuditSink>,
367}
368
369impl VfsAccessDecider {
370    /// Wrap the process-wide MAC audit sink. The sink is mandatory; a decision
371    /// that cannot be durably audited is downgraded to Deny (fail-closed),
372    /// exactly as the 9P decider does.
373    pub fn new(sink: Arc<dyn AuditSink>) -> Self {
374        Self { sink }
375    }
376
377    fn audit(
378        &self,
379        ctx: Option<&SecurityContext>,
380        label: Option<SecurityLabel>,
381        action: NamespaceAction,
382        decision: Decision,
383        reason: DecisionReason,
384    ) -> bool {
385        let policy = crate::mac::compiled_policy();
386        let generation = policy.as_ref().map_or(0, |p| p.generation);
387        let policy_hash = policy.as_ref().and_then(|p| p.policy_hash().ok());
388        let record = AuditRecord {
389            seq: 0,
390            prev_hash: [0; 32],
391            ts_unix_nanos: SystemTime::now()
392                .duration_since(UNIX_EPOCH)
393                .map_or(0, |d| d.as_nanos()),
394            decision,
395            generation,
396            policy_hash,
397            subject_type: VFS_SUBJECT_TYPE,
398            // Bottom is an audit-schema placeholder when clearance could not
399            // be proven. `NoClearance` is authoritative and the placeholder
400            // never enters authorization.
401            subject_clearance: ctx.map_or_else(SecurityLabel::bottom, |ctx| *ctx.clearance()),
402            on_behalf_of: None,
403            object_type: VFS_OBJECT_TYPE,
404            // Likewise, an unresolved object is represented only in the audit
405            // schema; `UnlabeledObject` remains the authoritative reason.
406            object_label: label.unwrap_or_else(SecurityLabel::bottom),
407            action: vfs_audit_action(action),
408            reason,
409            subject_id: None,
410            object_id: None,
411        };
412
413        match self.sink.record(&record) {
414            Ok(()) => decision.is_permit(),
415            Err(error) => {
416                let deny_record = AuditRecord {
417                    decision: Decision::Deny,
418                    reason: DecisionReason::AuditFailClosed,
419                    ..record
420                };
421                let _ = self.sink.record(&deny_record);
422                tracing::error!(
423                    target: "hyprstream.mac.audit",
424                    %error,
425                    reason = DecisionReason::AuditFailClosed.as_str(),
426                    "VFS PEP decision could not be durably audited; enforcing deny"
427                );
428                false
429            }
430        }
431    }
432}
433
434const fn vfs_audit_action(action: NamespaceAction) -> Action {
435    match action {
436        NamespaceAction::Read => Action::from_scope_action(ScopeAction::Query),
437        // Write/create + namespace mutation (mount/bind/unmount) and raw-handle
438        // extraction are all write-capable operations over an object — audited
439        // as Write. The deny-on-write-direction pause applies to all of them
440        // until IFC lands.
441        NamespaceAction::Write
442        | NamespaceAction::Create
443        | NamespaceAction::Mount
444        | NamespaceAction::BindMount
445        | NamespaceAction::Unmount
446        | NamespaceAction::ResolveHandle => Action::from_scope_action(ScopeAction::Write),
447    }
448}
449
450impl NamespaceAccessDecider for VfsAccessDecider {
451    fn check(
452        &self,
453        ctx: Option<&SecurityContext>,
454        object_label: Option<SecurityLabel>,
455        action: NamespaceAction,
456    ) -> MacDecision {
457        let Some(ctx) = ctx else {
458            self.audit(
459                None,
460                object_label,
461                action,
462                Decision::Deny,
463                DecisionReason::NoClearance,
464            );
465            return MacDecision::Deny(MacDenyReason::NoClearance);
466        };
467        let Some(object_label) = object_label else {
468            self.audit(
469                Some(ctx),
470                None,
471                action,
472                Decision::Deny,
473                DecisionReason::UnlabeledObject,
474            );
475            return MacDecision::Deny(MacDenyReason::UnlabeledObject);
476        };
477
478        // Write/create/mutate deny pending the VFS IFC write-direction
479        // decision.
480        let is_write_class = matches!(
481            action,
482            NamespaceAction::Write
483                | NamespaceAction::Create
484                | NamespaceAction::Mount
485                | NamespaceAction::BindMount
486                | NamespaceAction::Unmount
487                | NamespaceAction::ResolveHandle
488        );
489        if is_write_class {
490            self.audit(
491                Some(ctx),
492                Some(object_label),
493                action,
494                Decision::Deny,
495                DecisionReason::WriteDirectionUndecided,
496            );
497            return MacDecision::Deny(MacDenyReason::FloorDeny);
498        }
499
500        let permitted = ctx.can_access(&object_label);
501        let audited_permit = self.audit(
502            Some(ctx),
503            Some(object_label),
504            action,
505            if permitted {
506                Decision::Permit
507            } else {
508                Decision::Deny
509            },
510            if permitted {
511                DecisionReason::Permit
512            } else {
513                DecisionReason::FloorDeny
514            },
515        );
516        if permitted && audited_permit {
517            MacDecision::Permit
518        } else {
519            MacDecision::Deny(MacDenyReason::FloorDeny)
520        }
521    }
522}
523
524/// Production VFS resolver backed by contexts derived only at verified
525/// `Claims × VerifiedKeyMaterial` boundaries. Missing, expired, or
526/// tenant-incompatible entries deny; the activation control supplies the
527/// anonymous floor until an operator-approved widening.
528#[derive(Debug, Default, Clone, Copy)]
529pub struct VerifiedClaimsSubjects;
530
531#[async_trait::async_trait]
532impl SubjectContextResolver for VerifiedClaimsSubjects {
533    async fn resolve(&self, subject: &hyprstream_rpc::Subject) -> Option<SecurityContext> {
534        hyprstream_rpc::auth::mac::subject_context(subject, None).await
535    }
536}
537
538/// Assemble the production VFS-plane PEP from the genesis label resolver and
539/// the tamper-evident MAC audit sink (#1272).
540///
541/// This is the `hyprstream`-crate wiring that satisfies the
542/// [`hyprstream_vfs::NamespacePep`] contract: the genesis composite
543/// `RpcObjectLabelResolver` (carriers (a)+(c), #1228) feeds label resolution, a
544/// [`VfsAccessDecider`] over the WAL audit sink evaluates the policy, and
545/// [`VerifiedClaimsSubjects`] supplies the activation-controlled subject
546/// context.
547///
548/// Callers propagate the error and refuse to arm a `Namespace` with a
549/// permissive fallback; there is no permissive arm path.
550pub async fn production_vfs_pep(
551    signing_key: SigningKey,
552    oauth: &crate::config::OAuthConfig,
553    audit_stream: &str,
554) -> anyhow::Result<std::sync::Arc<hyprstream_vfs::NamespacePep>> {
555    anyhow::ensure!(
556        !audit_stream.is_empty()
557            && audit_stream
558                .bytes()
559                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_'),
560        "invalid VFS MAC audit stream name"
561    );
562
563    let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir()?;
564    let ml_dsa_store = crate::auth::key_rotation::global_ml_dsa_key_store(&secrets_dir, oauth);
565    let signer = crate::mac::audit::cose::OwnedCoseAuditSigner::new(
566        Arc::new(signing_key),
567        ml_dsa_store.active_key().await,
568        hyprstream_rpc::envelope::mandatory_envelope_policy(),
569    );
570    anyhow::ensure!(
571        signer.can_sign(),
572        "VFS MAC PEP audit signer unavailable under mandatory Hybrid policy"
573    );
574
575    let audit_store = crate::mac::audit::WalAuditStore::open(
576        secrets_dir.join("mac-audit").join(audit_stream),
577        signer,
578    )
579    .context("open VFS MAC audit store")?;
580    let resolver = crate::mac::GenesisGate::production().into_resolver();
581
582    Ok(std::sync::Arc::new(hyprstream_vfs::NamespacePep::new(
583        std::sync::Arc::new(VerifiedClaimsSubjects),
584        std::sync::Arc::new(resolver),
585        std::sync::Arc::new(VfsAccessDecider::new(std::sync::Arc::new(audit_store))),
586    )))
587}
588
589#[cfg(test)]
590mod tests {
591    use std::time::{Duration, Instant};
592
593    use parking_lot::Mutex;
594
595    use hyprstream_rpc::auth::mac::{Assurance, CompartmentSet, Level, VerifiedKeyMaterial};
596
597    use super::*;
598    use crate::mac::audit::{AuditError, AuditRecord};
599
600    struct FixtureResolver {
601        public: SecurityLabel,
602        secret: SecurityLabel,
603    }
604
605    impl ObjectLabelResolver for FixtureResolver {
606        fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
607            match object {
608                ObjectRef::Path(["public"]) => Some(self.public),
609                ObjectRef::Path(["secret"]) => Some(self.secret),
610                // Existing-but-unlabeled CIDs and unknown paths both resolve
611                // to absence, which is denial at the PEP boundary.
612                _ => None,
613            }
614        }
615    }
616
617    struct MonitorResolver {
618        public: SecurityLabel,
619        secret: SecurityLabel,
620    }
621
622    impl ObjectLabelResolver for MonitorResolver {
623        fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
624            match object {
625                ObjectRef::Path(["public"] | ["decider-deny"]) => Some(self.public),
626                ObjectRef::Path(["secret"]) => Some(self.secret),
627                _ => None,
628            }
629        }
630    }
631
632    #[derive(Default)]
633    struct SpySink {
634        records: Mutex<Vec<AuditRecord>>,
635    }
636
637    impl AuditSink for SpySink {
638        fn record(&self, record: &AuditRecord) -> Result<(), AuditError> {
639            self.records.lock().push(record.clone());
640            Ok(())
641        }
642    }
643
644    struct FixtureVfsSubjects {
645        name: &'static str,
646        ctx: SecurityContext,
647    }
648
649    #[async_trait::async_trait]
650    impl SubjectContextResolver for FixtureVfsSubjects {
651        async fn resolve(&self, subject: &hyprstream_rpc::Subject) -> Option<SecurityContext> {
652            (subject.name() == Some(self.name)).then(|| self.ctx.clone())
653        }
654    }
655
656    struct FixtureVfsLabels {
657        public: SecurityLabel,
658        secret: SecurityLabel,
659    }
660
661    impl hyprstream_rpc::auth::mac::RpcObjectLabelResolver for FixtureVfsLabels {
662        fn resolve(&self, service_domain: &str, _method: Option<&[u16]>) -> Option<SecurityLabel> {
663            match service_domain {
664                "/public" => Some(self.public),
665                "/secret" => Some(self.secret),
666                _ => None,
667            }
668        }
669    }
670
671    fn label(level: Level) -> SecurityLabel {
672        SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY)
673    }
674
675    fn context(level: Level) -> SecurityContext {
676        SecurityContext::from_clearance(label(level), VerifiedKeyMaterial::Classical)
677    }
678
679    fn identity(tenant: &str) -> VerifiedAttachIdentity {
680        VerifiedAttachIdentity::from_verified_credential("did:key:alice", tenant)
681    }
682
683    fn read_token() -> hyprstream_9p::VerifiedTokenScope {
684        hyprstream_9p::VerifiedTokenScope::from_verified_token(
685            label(Level::Secret),
686            Arc::from([NinePAction::Read]),
687            Instant::now() + Duration::from_secs(60),
688        )
689    }
690
691    #[test]
692    fn reads_fail_closed_and_every_decision_is_audited() {
693        let sink = Arc::new(SpySink::default());
694        let decider = NinePAccessDecider::new(
695            Arc::new(FixtureResolver {
696                public: label(Level::Public),
697                secret: label(Level::Secret),
698            }),
699            sink.clone(),
700        );
701
702        assert!(decider.check(
703            &context(Level::Secret),
704            ObjectRef::Path(&["public"]),
705            NinePAction::Read,
706        ));
707        assert!(!decider.check(
708            &context(Level::Public),
709            ObjectRef::Path(&["secret"]),
710            NinePAction::Read,
711        ));
712        assert!(!decider.check(
713            &context(Level::Secret),
714            ObjectRef::Cid(b"unlabeled"),
715            NinePAction::Read,
716        ));
717        assert!(!decider.check(
718            &context(Level::Secret),
719            ObjectRef::Path(&["does-not-exist"]),
720            NinePAction::Read,
721        ));
722
723        let records = sink.records.lock();
724        assert_eq!(records.len(), 4);
725        assert_eq!(records[0].decision, Decision::Permit);
726        assert_eq!(records[1].reason, DecisionReason::FloorDeny);
727        assert_eq!(records[2].reason, DecisionReason::UnlabeledObject);
728        assert_eq!(records[3].reason, DecisionReason::UnlabeledObject);
729    }
730
731    #[test]
732    fn writes_use_no_write_down_ifc() {
733        let sink = Arc::new(SpySink::default());
734        let decider = NinePAccessDecider::new(
735            Arc::new(FixtureResolver {
736                public: label(Level::Public),
737                secret: label(Level::Secret),
738            }),
739            sink.clone(),
740        );
741
742        // Write to a same-level object: permitted (no-write-down satisfied).
743        assert!(decider.check(
744            &context(Level::Secret),
745            ObjectRef::Path(&["secret"]),
746            NinePAction::Write,
747        ));
748        // Write-down (Secret→Public): denied by *-property.
749        assert!(!decider.check(
750            &context(Level::Secret),
751            ObjectRef::Path(&["public"]),
752            NinePAction::Write,
753        ));
754        let records = sink.records.lock();
755        assert_eq!(records.len(), 2);
756        assert_eq!(records[0].decision, Decision::Permit);
757        assert_eq!(records[1].reason, DecisionReason::FloorDeny);
758    }
759
760    #[test]
761    fn every_reference_monitor_deny_stage_is_audited() {
762        let sink = Arc::new(SpySink::default());
763        let decider: Arc<dyn AccessDecider> = Arc::new(NinePAccessDecider::new(
764            Arc::new(FixtureResolver {
765                public: label(Level::Public),
766                secret: label(Level::Secret),
767            }),
768            sink.clone(),
769        ));
770        let monitor = ReferenceMonitor::new(
771            Arc::new(AnonymousAuthenticator),
772            Arc::new(MonitorResolver {
773                public: label(Level::Public),
774                secret: label(Level::Secret),
775            }),
776            decider,
777        );
778        let permitted = SessionContext::from_verified_token(
779            identity("tenant-a"),
780            context(Level::Secret),
781            read_token(),
782        );
783
784        assert!(!monitor.authorize(&permitted, &["unlabeled".to_owned()], NinePAction::Read,));
785        assert!(!monitor.authorize(
786            &SessionContext::from_verified_clearance(identity("tenant-a"), context(Level::Secret),),
787            &["public".to_owned()],
788            NinePAction::Read,
789        ));
790        assert!(!monitor.authorize(
791            &SessionContext::from_verified_token(
792                identity("tenant-a"),
793                context(Level::Public),
794                read_token(),
795            ),
796            &["secret".to_owned()],
797            NinePAction::Read,
798        ));
799        assert!(!monitor.authorize(&permitted, &["decider-deny".to_owned()], NinePAction::Read,));
800
801        let records = sink.records.lock();
802        assert_eq!(records.len(), 4, "one WAL record per denied operation");
803        assert_eq!(records[0].reason, DecisionReason::UnlabeledObject);
804        assert_eq!(records[1].reason, DecisionReason::TokenGate);
805        assert_eq!(records[2].reason, DecisionReason::FloorDeny);
806        assert_eq!(records[3].reason, DecisionReason::UnlabeledObject);
807        assert!(records
808            .iter()
809            .all(|record| record.decision == Decision::Deny));
810    }
811
812    #[tokio::test]
813    async fn raw_attach_uname_never_becomes_verified_identity_or_tenant() {
814        let sink = Arc::new(SpySink::default());
815        let decider: Arc<dyn AccessDecider> = Arc::new(NinePAccessDecider::new(
816            Arc::new(FixtureResolver {
817                public: label(Level::Public),
818                secret: label(Level::Secret),
819            }),
820            sink,
821        ));
822        let monitor = enrollment_ninep_reference_monitor(decider);
823
824        let denied = monitor
825            .authenticate("did:key:victim", "tenant-victim")
826            .await;
827        assert!(
828            denied.is_err(),
829            "unverified Tattach fields must not mint an attach bundle"
830        );
831    }
832
833    #[tokio::test]
834    async fn vfs_fail_closed_denies_are_audited() {
835        let sink = Arc::new(SpySink::default());
836        let pep = hyprstream_vfs::NamespacePep::new(
837            Arc::new(FixtureVfsSubjects {
838                name: "alice",
839                ctx: context(Level::Public),
840            }),
841            Arc::new(FixtureVfsLabels {
842                public: label(Level::Public),
843                secret: label(Level::Secret),
844            }),
845            Arc::new(VfsAccessDecider::new(sink.clone())),
846        );
847
848        // Missing verified clearance, missing content label, lattice-floor
849        // denial, and the write-direction pause must all cross the same audit
850        // sink before the VFS reference monitor returns Deny.
851        assert_eq!(
852            pep.check(
853                &hyprstream_rpc::Subject::new("mallory"),
854                "/public",
855                NamespaceAction::Read,
856            )
857            .await,
858            MacDecision::Deny(MacDenyReason::NoClearance)
859        );
860        assert_eq!(
861            pep.check(
862                &hyprstream_rpc::Subject::new("alice"),
863                "/missing",
864                NamespaceAction::Read,
865            )
866            .await,
867            MacDecision::Deny(MacDenyReason::UnlabeledObject)
868        );
869        assert_eq!(
870            pep.check(
871                &hyprstream_rpc::Subject::new("alice"),
872                "/secret",
873                NamespaceAction::Read,
874            )
875            .await,
876            MacDecision::Deny(MacDenyReason::FloorDeny)
877        );
878        assert_eq!(
879            pep.check(
880                &hyprstream_rpc::Subject::new("alice"),
881                "/public",
882                NamespaceAction::Write,
883            )
884            .await,
885            MacDecision::Deny(MacDenyReason::FloorDeny)
886        );
887
888        let records = sink.records.lock();
889        assert_eq!(records.len(), 4);
890        assert!(records
891            .iter()
892            .all(|record| record.decision == Decision::Deny));
893        assert_eq!(records[0].reason, DecisionReason::NoClearance);
894        assert_eq!(records[1].reason, DecisionReason::UnlabeledObject);
895        assert_eq!(records[2].reason, DecisionReason::FloorDeny);
896        assert_eq!(records[3].reason, DecisionReason::WriteDirectionUndecided);
897    }
898}