Skip to main content

hyprstream_core/mac/
cas_pep.rs

1//! CAS-native MAC Policy Enforcement Point (#1270, epic #1267 T3).
2//!
3//! The CAS data plane — substrate ingest, `CasMount` read, registry streaming
4//! continuation, and xet HTTP — had **no native-MAC PEP** and no trusted label
5//! at seal (T2 audit `.fleet-coord/mac-pep-audit.md`, rows "CAS substrate
6//! ingest" / "CAS substrate read" / "`CasMount` object/xorb open/read/stat" /
7//! "Registry CAS read continuation" / "Xet HTTP CAS read"). Every read was
8//! either unmediated or gated only by `BootstrapCasAuthorizer` ("any
9//! authenticated caller"), with labels caller-asserted or absent.
10//!
11//! This module provides the CAS-plane PEP that all CAS read paths consume. It
12//! uses the canonical RPC MAC contract's [`MacDecision`], [`MacDenyReason`],
13//! and [`RpcObjectLabelResolver`] seam while deliberately not implementing
14//! [`MacDispatchPep`](hyprstream_rpc::auth::mac::MacDispatchPep), whose
15//! `EnvelopeContext` input is RPC-plane-specific.
16//!
17//! - **Trusted content-bound label at seal** ([`domain_label`] /
18//!   [`seal_label`]): derived from the [`DedupDomain`]'s structural properties
19//!   (trust boundary → level axis), **not** caller-asserted. The domain is the
20//!   content's provenance — it encodes *where the content lives* (local vs
21//!   shared-remote) and *which tenant it belongs to* (compartment). The staging
22//!   path's joined hint label is a D1 hint trusted only from our own ingest
23//!   service; the domain label is authoritative and the effective seal label is
24//!   the restrict-only `join` of the two.
25//!
26//! - **Clearance-input seam** ([`CasClearanceSource`]): consumes authority-bound
27//!   subject + `verified_tenant` inputs. Until a production CAS adapter is
28//!   installed, [`DenyAllClearanceSource`] returns `None` for every subject —
29//!   **fail-closed**, never a permissive default. There is no permissive mode
30//!   (per #547).
31//!
32//! - **Per-op enforcement** ([`CasPep`]): resolves the subject clearance via
33//!   the seam, checks `clearance.can_access(object_label)`, and records every
34//!   decision through the existing tamper-evident MAC audit sink. Missing
35//!   subject, missing clearance, missing label, or audit failure → deny.
36//!
37//! - **`CasMount` integration** ([`MacCasAuthorizer`]): implements
38//!   [`CasMountAuthorizer`](`crate::storage::cas::mount::CasMountAuthorizer`)
39//!   so that the existing per-op authorization hook in `CasMount::open`/
40//!   `read`/`stat` delegates to the MAC PEP without adding a new enforcement
41//!   surface.
42//!
43//! ## What this module does NOT do
44//!
45//! - It does not author, derive, or enforce MAC policy from the `Compartment`
46//!   string in [`DedupDomain`] — that requires lattice internment which lives
47//!   in the policy layer. Compartment isolation is already structural (distinct
48//!   physical storage roots per domain); the label's level axis is the
49//!   load-bearing enforcement here. Enriching the seal label with compartment
50//!   bits via the lattice is a follow-up gated on threading the lattice to the
51//!   CAS layer.
52//!
53//! - It does not fake a clearance for any subject. If the clearance source
54//!   returns `None`, the installed PEP denies. The #698 clearance primitives
55//!   have landed, but a plane-specific adapter must still be installed before
56//!   a CAS subject can pass.
57
58use std::sync::Arc;
59
60use anyhow::Context as _;
61use ed25519_dalek::SigningKey;
62use hyprstream_rpc::auth::mac::{
63    MacDecision, MacDenyReason, RpcObjectLabelResolver, SecurityContext, SecurityLabel,
64};
65use hyprstream_vfs::Subject;
66
67use crate::mac::audit::{AuditRecord, AuditSink, DecisionReason};
68use crate::mac::te::{Decision, ObjectType, SubjectType};
69use crate::storage::cas::{DedupDomain, TrustBoundary};
70
71/// Reserved audit type ids for CAS PEP decisions (below the grant-path
72/// `u32::MAX` sentinels, above the 9P sentinels).
73const CAS_SUBJECT_TYPE: SubjectType = SubjectType(u32::MAX - 3);
74const CAS_OBJECT_TYPE: ObjectType = ObjectType(u32::MAX - 3);
75const CAS_SERVICE_DOMAIN: &str = "cas";
76
77// ────────────────────────────────────────────────────────────────────────────
78// Trusted content-bound label derivation
79// ────────────────────────────────────────────────────────────────────────────
80
81/// Derive a **trusted, content-bound** [`SecurityLabel`] from a [`DedupDomain`].
82///
83/// The label is derived from the domain's structural properties — the trust
84/// boundary determines the level axis, and the assurance floors at `Classical`
85/// (the substrate cannot prove PQ-hybrid for stored content). This is **not**
86/// caller-asserted: the domain is the content's physical provenance, set by the
87/// storage layer at domain construction, not by the ingest caller.
88///
89/// Mapping:
90/// - [`TrustBoundary::Local`] → [`Level::Internal`](hyprstream_rpc::auth::mac::Level::Internal):
91///   node-local content is at least org-internal.
92/// - [`TrustBoundary::SharedRemote`] → [`Level::Confidential`](hyprstream_rpc::auth::mac::Level::Confidential):
93///   federated/remote content carries higher sensitivity.
94///
95/// Compartment bits are **not** populated here: the lattice internment lives in
96/// the policy layer, not the storage layer. Compartment isolation is already
97/// structural — each domain maps to a distinct physical storage root
98/// ([`DedupDomain::relative_path`]) — so cross-compartment content leakage is
99/// physically impossible at the substrate level. The MAC label's level axis
100/// provides the independent clearance enforcement on top.
101///
102/// Enriching the seal label with interned compartment bits is a follow-up gated
103/// on threading the [`Lattice`](hyprstream_rpc::auth::mac::Lattice) to the CAS
104/// layer.
105pub fn domain_label(domain: &DedupDomain) -> SecurityLabel {
106    use hyprstream_rpc::auth::mac::{Assurance, CompartmentSet, Level};
107    let level = match domain.trust_boundary {
108        TrustBoundary::Local => Level::Internal,
109        TrustBoundary::SharedRemote => Level::Confidential,
110    };
111    SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY)
112}
113
114/// Compute the **effective seal label**: `join(domain_label(domain), hint)`.
115///
116/// The domain label is authoritative (content-bound). The `hint` is a D1 label
117/// from our own staging path — trusted as a *restrict-only* input, never
118/// permissive. `join` (BLP least-upper-bound) can only make the effective label
119/// *more* restrictive than either input, never less.
120///
121/// Callers:
122/// - [`CasSubstrate::put`](crate::storage::CasSubstrate::put) calls this when a
123///   staging hint is supplied, stamping the result on the
124///   [`BlobManifest`](crate::storage::cas::BlobManifest) carrier field.
125/// - The seal path in `CasMount::seal_slot` passes the staging-joined label as
126///   the hint.
127pub fn seal_label(domain: &DedupDomain, hint: Option<SecurityLabel>) -> SecurityLabel {
128    let base = domain_label(domain);
129    match hint {
130        Some(h) => base.join(&h),
131        None => base,
132    }
133}
134
135// ────────────────────────────────────────────────────────────────────────────
136// Canonical object-label resolver seam
137// ────────────────────────────────────────────────────────────────────────────
138
139/// Adapt a trusted CAS carrier label to the canonical object-label resolver.
140///
141/// CAS supplies the concrete label from either a sealed manifest or the
142/// structural [`DedupDomain`] floor. The RPC-only method discriminator is
143/// always `None` on this plane.
144#[derive(Debug, Clone, Copy)]
145pub struct CasObjectLabelResolver {
146    label: Option<SecurityLabel>,
147}
148
149impl CasObjectLabelResolver {
150    /// Resolve a known trusted label.
151    pub const fn new(label: Option<SecurityLabel>) -> Self {
152        Self { label }
153    }
154
155    /// Resolve the structural floor for a CAS dedup domain.
156    pub fn from_domain(domain: &DedupDomain) -> Self {
157        Self::new(Some(domain_label(domain)))
158    }
159}
160
161impl RpcObjectLabelResolver for CasObjectLabelResolver {
162    fn resolve(&self, service_domain: &str, method: Option<&[u16]>) -> Option<SecurityLabel> {
163        if service_domain == CAS_SERVICE_DOMAIN && method.is_none() {
164            self.label
165        } else {
166            None
167        }
168    }
169}
170
171// ────────────────────────────────────────────────────────────────────────────
172// Clearance-input seam
173// ────────────────────────────────────────────────────────────────────────────
174
175/// Resolve a verified subject identity to a MAC [`SecurityContext`] for CAS
176/// access.
177///
178/// The CAS PEP calls
179/// [`CasClearanceSource::clearance_for`] with the verified subject and tenant
180/// binding (extracted from `EnvelopeContext` or an equivalent verified HTTP
181/// identity) and receives a `SecurityContext` — **never** a caller-supplied
182/// clearance.
183///
184/// `None` ⇒ **unresolvable** ⇒ the PEP MUST deny. Implementors must NOT
185/// manufacture a permissive default.
186///
187/// The #698 clearance primitives are available, but until a CAS-specific
188/// adapter is installed [`DenyAllClearanceSource`] returns `None` for every
189/// subject.
190///
191/// Async because the production source revalidates credential-bearing cache
192/// entries against the canonical revocation authority on every read.
193#[async_trait::async_trait]
194pub trait CasClearanceSource: Send + Sync {
195    /// Resolve `subject_id` to its MAC clearance, or `None` if unresolvable.
196    async fn clearance_for(
197        &self,
198        subject_id: &str,
199        verified_tenant: Option<&str>,
200    ) -> Option<SecurityContext>;
201}
202
203/// Fail-closed clearance source: denies every subject.
204///
205/// Every CAS read through this explicitly installed source denies. This is the
206/// safe default while no authority-backed CAS adapter is configured.
207pub struct DenyAllClearanceSource;
208
209#[async_trait::async_trait]
210impl CasClearanceSource for DenyAllClearanceSource {
211    async fn clearance_for(
212        &self,
213        _subject_id: &str,
214        _verified_tenant: Option<&str>,
215    ) -> Option<SecurityContext> {
216        None
217    }
218}
219
220/// Production CAS clearance source backed only by contexts derived from
221/// verified `Claims × VerifiedKeyMaterial` at an RPC/attach boundary.
222#[derive(Debug, Default, Clone, Copy)]
223pub struct VerifiedClaimsCasClearanceSource;
224
225#[async_trait::async_trait]
226impl CasClearanceSource for VerifiedClaimsCasClearanceSource {
227    async fn clearance_for(
228        &self,
229        subject_id: &str,
230        verified_tenant: Option<&str>,
231    ) -> Option<SecurityContext> {
232        hyprstream_rpc::auth::mac::subject_context(
233            &Subject::new(subject_id.to_owned()),
234            verified_tenant,
235        )
236        .await
237    }
238}
239
240// ────────────────────────────────────────────────────────────────────────────
241// CAS PEP — per-op enforcement
242// ────────────────────────────────────────────────────────────────────────────
243
244/// The CAS MAC Policy Enforcement Point.
245///
246/// Holds the clearance-input seam ([`CasClearanceSource`]) and the audit sink.
247/// Every CAS read path calls [`CasPep::check_read`] before serving bytes:
248///
249/// 1. Resolve the subject clearance via the seam → `None` = deny (fail-closed).
250/// 2. Check `clearance.can_access(object_label)`.
251/// 3. Audit every decision (a decision that cannot be durably audited is
252///    downgraded to `Deny`, same fail-closed contract as
253///    [`NinePAccessDecider`](crate::mac::pep::NinePAccessDecider)).
254pub struct CasPep {
255    clearance_source: Arc<dyn CasClearanceSource>,
256    sink: Arc<dyn AuditSink>,
257}
258
259impl CasPep {
260    /// Construct a CAS PEP with the given clearance source and audit sink.
261    pub fn new(clearance_source: Arc<dyn CasClearanceSource>, sink: Arc<dyn AuditSink>) -> Self {
262        Self {
263            clearance_source,
264            sink,
265        }
266    }
267
268    /// Construct a fail-closed CAS PEP using [`DenyAllClearanceSource`] and the
269    /// null audit sink. Every read denies. Use this at production constructors
270    /// where no production CAS clearance adapter is configured.
271    pub fn fail_closed() -> Self {
272        Self::new(
273            Arc::new(DenyAllClearanceSource),
274            Arc::new(crate::mac::audit::NullAuditSink),
275        )
276    }
277
278    /// Check read access for a verified subject against a trusted object-label
279    /// resolver.
280    ///
281    /// Returns the canonical [`MacDecision`]. An installed CAS PEP is
282    /// fail-closed for:
283    /// - missing clearance (subject not resolvable via the seam)
284    /// - missing object label (resolver returns `None`, per #547)
285    /// - audit failure (downgraded to deny)
286    #[must_use]
287    pub async fn check_read(
288        &self,
289        subject_id: &str,
290        verified_tenant: Option<&str>,
291        resolver: &dyn RpcObjectLabelResolver,
292    ) -> MacDecision {
293        self.check(
294            subject_id,
295            verified_tenant,
296            resolver.resolve(CAS_SERVICE_DOMAIN, None),
297        )
298        .await
299    }
300
301    /// Internal: resolve clearance, check dominance, audit.
302    async fn check(
303        &self,
304        subject_id: &str,
305        verified_tenant: Option<&str>,
306        label: Option<SecurityLabel>,
307    ) -> MacDecision {
308        let Some(ctx) = self
309            .clearance_source
310            .clearance_for(subject_id, verified_tenant)
311            .await
312        else {
313            return self.audit(
314                subject_id,
315                verified_tenant,
316                None,
317                label,
318                MacDecision::Deny(MacDenyReason::NoClearance),
319            );
320        };
321
322        let Some(label) = label else {
323            return self.audit(
324                subject_id,
325                verified_tenant,
326                Some(&ctx),
327                None,
328                MacDecision::Deny(MacDenyReason::UnlabeledObject),
329            );
330        };
331
332        let decision = if ctx.can_access(&label) {
333            MacDecision::Permit
334        } else {
335            MacDecision::Deny(MacDenyReason::FloorDeny)
336        };
337        self.audit(
338            subject_id,
339            verified_tenant,
340            Some(&ctx),
341            Some(label),
342            decision,
343        )
344    }
345
346    fn audit(
347        &self,
348        subject_id: &str,
349        verified_tenant: Option<&str>,
350        ctx: Option<&SecurityContext>,
351        label: Option<SecurityLabel>,
352        decision: MacDecision,
353    ) -> MacDecision {
354        use std::time::{SystemTime, UNIX_EPOCH};
355
356        let (audit_decision, reason) = match decision {
357            MacDecision::Permit => (Decision::Permit, DecisionReason::Permit),
358            MacDecision::Deny(MacDenyReason::NoClearance) => {
359                (Decision::Deny, DecisionReason::NoClearance)
360            }
361            MacDecision::Deny(MacDenyReason::UnlabeledObject) => {
362                (Decision::Deny, DecisionReason::UnlabeledObject)
363            }
364            MacDecision::Deny(
365                MacDenyReason::FloorDeny
366                | MacDenyReason::NoPepInstalled
367                | MacDenyReason::StaleAuthority,
368            ) => (Decision::Deny, DecisionReason::FloorDeny),
369        };
370        let policy = crate::mac::compiled_policy();
371        let generation = policy.as_ref().map_or(0, |p| p.generation);
372        let policy_hash = policy.as_ref().and_then(|p| p.policy_hash().ok());
373        let record = AuditRecord {
374            seq: 0,
375            prev_hash: [0; 32],
376            ts_unix_nanos: SystemTime::now()
377                .duration_since(UNIX_EPOCH)
378                .map_or(0, |d| d.as_nanos()),
379            decision: audit_decision,
380            generation,
381            policy_hash,
382            subject_type: CAS_SUBJECT_TYPE,
383            subject_clearance: ctx
384                .map(|c| *c.clearance())
385                .unwrap_or_else(SecurityLabel::bottom),
386            on_behalf_of: None,
387            object_type: CAS_OBJECT_TYPE,
388            object_label: label.unwrap_or_else(SecurityLabel::bottom),
389            action: crate::mac::te::Action::from_scope_action(crate::mac::te::ScopeAction::Query),
390            reason,
391            subject_id: Some(subject_id.to_owned()),
392            object_id: Some(match verified_tenant {
393                Some(tenant) => format!("{tenant}/{CAS_SERVICE_DOMAIN}"),
394                None => CAS_SERVICE_DOMAIN.to_owned(),
395            }),
396        };
397
398        match self.sink.record(&record) {
399            Ok(()) => decision,
400            Err(error) => {
401                let deny_record = AuditRecord {
402                    decision: Decision::Deny,
403                    reason: DecisionReason::AuditFailClosed,
404                    ..record
405                };
406                let _ = self.sink.record(&deny_record);
407                tracing::error!(
408                    target: "hyprstream.mac.cas_pep",
409                    %error,
410                    reason = DecisionReason::AuditFailClosed.as_str(),
411                    "CAS PEP decision could not be durably audited; enforcing deny"
412                );
413                // The canonical contract has no audit-specific deny variant.
414                // Keep the detailed cause in the audit vocabulary and expose a
415                // conservative floor denial to shared consumers.
416                MacDecision::Deny(MacDenyReason::FloorDeny)
417            }
418        }
419    }
420}
421
422// ────────────────────────────────────────────────────────────────────────────
423// CasMount integration
424// ────────────────────────────────────────────────────────────────────────────
425
426/// A [`CasMountAuthorizer`] backed by the CAS MAC PEP.
427///
428/// This replaces [`BootstrapCasAuthorizer`] at production constructors. On each
429/// `open`/`read`/`stat` it derives the content-bound label from the request's
430/// [`DedupDomain`] and checks the subject clearance via the PEP.
431///
432/// The label is derived from the domain (structural, trusted), NOT from any
433/// caller-supplied value. This is the trusted content-bound label at the point
434/// of use.
435pub struct MacCasAuthorizer {
436    pep: Arc<CasPep>,
437}
438
439impl MacCasAuthorizer {
440    /// Construct a MAC CAS authorizer wrapping the given PEP.
441    pub fn new(pep: Arc<CasPep>) -> Self {
442        Self { pep }
443    }
444
445    /// Construct a fail-closed MAC CAS authorizer (every read denies).
446    /// Use this at production constructors where no authority-backed CAS
447    /// clearance adapter is configured.
448    pub fn fail_closed() -> Self {
449        Self::new(Arc::new(CasPep::fail_closed()))
450    }
451}
452
453#[async_trait::async_trait]
454impl crate::storage::cas::CasMountAuthorizer for MacCasAuthorizer {
455    async fn authorize(
456        &self,
457        caller: &Subject,
458        request: crate::storage::cas::CasMountAuthzRequest<'_>,
459    ) -> Result<(), hyprstream_vfs::MountError> {
460        let resolver = CasObjectLabelResolver::from_domain(request.domain);
461        let decision = self
462            .pep
463            .check_read(&caller.to_string(), request.verified_tenant, &resolver)
464            .await;
465        if decision.is_permit() {
466            Ok(())
467        } else {
468            Err(hyprstream_vfs::MountError::PermissionDenied(format!(
469                "CAS MAC {} {:?} {} denied for {}: {decision:?} (#1270)",
470                request.operation, request.kind, request.address, caller,
471            )))
472        }
473    }
474}
475
476/// Assemble the production CAS PEP from verified subject contexts and a
477/// tamper-evident signed WAL.  Failure to obtain either signing key aborts the
478/// production constructor; it never substitutes the test-only null sink.
479pub async fn production_cas_pep(
480    signing_key: SigningKey,
481    oauth: &crate::config::OAuthConfig,
482    audit_stream: &str,
483) -> anyhow::Result<Arc<CasPep>> {
484    anyhow::ensure!(
485        !audit_stream.is_empty()
486            && audit_stream
487                .bytes()
488                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_'),
489        "invalid CAS MAC audit stream name"
490    );
491    let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir()?;
492    let ml_dsa_store = crate::auth::key_rotation::global_ml_dsa_key_store(&secrets_dir, oauth);
493    let signer = crate::mac::audit::cose::OwnedCoseAuditSigner::new(
494        Arc::new(signing_key),
495        ml_dsa_store.active_key().await,
496        hyprstream_rpc::envelope::mandatory_envelope_policy(),
497    );
498    anyhow::ensure!(
499        signer.can_sign(),
500        "CAS MAC PEP audit signer unavailable under mandatory Hybrid policy"
501    );
502    let audit_store = crate::mac::audit::WalAuditStore::open(
503        secrets_dir.join("mac-audit").join(audit_stream),
504        signer,
505    )
506    .context("open CAS MAC audit store")?;
507    Ok(Arc::new(CasPep::new(
508        Arc::new(VerifiedClaimsCasClearanceSource),
509        Arc::new(audit_store),
510    )))
511}
512
513// ────────────────────────────────────────────────────────────────────────────
514// Tests
515// ────────────────────────────────────────────────────────────────────────────
516
517#[cfg(test)]
518#[allow(clippy::unwrap_used, clippy::expect_used)]
519mod tests {
520    use parking_lot::Mutex;
521
522    use hyprstream_rpc::auth::mac::{
523        Assurance, CompartmentSet, Level, SecurityContext, SecurityLabel, VerifiedKeyMaterial,
524    };
525
526    use super::*;
527    use crate::mac::audit::{AuditError, AuditRecord};
528    use crate::storage::cas::{CasMountAuthorizer, CasMountAuthzRequest, CasMountObjectKind};
529    use crate::storage::cas::{DedupDomain, TrustBoundary};
530
531    // ── domain_label ────────────────────────────────────────────────────────
532
533    #[test]
534    fn local_domain_label_is_internal() {
535        let label = domain_label(&DedupDomain::local_default());
536        assert_eq!(label.level, Level::Internal);
537        assert_eq!(label.assurance, Assurance::Classical);
538        assert!(label.compartments.is_empty());
539    }
540
541    #[test]
542    fn shared_remote_domain_label_is_confidential() {
543        let domain = DedupDomain {
544            trust_boundary: TrustBoundary::SharedRemote,
545            ..DedupDomain::local_default()
546        };
547        let label = domain_label(&domain);
548        assert_eq!(label.level, Level::Confidential);
549    }
550
551    // ── seal_label ──────────────────────────────────────────────────────────
552
553    #[test]
554    fn seal_label_without_hint_is_domain_label() {
555        let domain = DedupDomain::local_default();
556        assert_eq!(seal_label(&domain, None), domain_label(&domain));
557    }
558
559    #[test]
560    fn seal_label_join_is_restrict_only() {
561        // Domain label = Internal; hint = Secret → join = Secret (more restrictive).
562        let domain = DedupDomain::local_default();
563        let hint = SecurityLabel::new(Level::Secret, Assurance::Classical, CompartmentSet::EMPTY);
564        let effective = seal_label(&domain, Some(hint));
565        assert_eq!(effective.level, Level::Secret);
566    }
567
568    #[test]
569    fn seal_label_hint_cannot_lower_below_domain() {
570        // Domain label = Confidential (shared-remote); hint = Public → join stays
571        // Confidential (join never lowers).
572        let domain = DedupDomain {
573            trust_boundary: TrustBoundary::SharedRemote,
574            ..DedupDomain::local_default()
575        };
576        let hint = SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY);
577        let effective = seal_label(&domain, Some(hint));
578        assert_eq!(
579            effective.level,
580            Level::Confidential,
581            "seal label must never be less restrictive than the domain floor"
582        );
583    }
584
585    #[test]
586    fn cas_resolver_uses_canonical_service_and_non_browser_method() {
587        let resolver = CasObjectLabelResolver::from_domain(&DedupDomain::local_default());
588        assert!(resolver.resolve(CAS_SERVICE_DOMAIN, None).is_some());
589        assert!(resolver.resolve("registry", None).is_none());
590        assert!(resolver
591            .resolve(CAS_SERVICE_DOMAIN, Some(&[1][..]))
592            .is_none());
593    }
594
595    // ── DenyAllClearanceSource ──────────────────────────────────────────────
596
597    #[tokio::test]
598    async fn deny_all_clearance_source_returns_none() {
599        let src = DenyAllClearanceSource;
600        assert!(src
601            .clearance_for("anyone", Some("tenant-a"))
602            .await
603            .is_none());
604        assert!(src.clearance_for("admin", None).await.is_none());
605    }
606
607    // ── CasPep fail-closed ──────────────────────────────────────────────────
608
609    #[tokio::test]
610    async fn fail_closed_pep_denies_every_read() {
611        let pep = CasPep::fail_closed();
612        let label = domain_label(&DedupDomain::local_default());
613        let labeled = CasObjectLabelResolver::new(Some(label));
614        assert_eq!(
615            pep.check_read("any-subject", Some("tenant-a"), &labeled)
616                .await,
617            MacDecision::Deny(MacDenyReason::NoClearance)
618        );
619        // Unlabeled object also denies.
620        let unlabeled = CasObjectLabelResolver::new(None);
621        assert_eq!(
622            pep.check_read("any-subject", Some("tenant-a"), &unlabeled)
623                .await,
624            MacDecision::Deny(MacDenyReason::NoClearance)
625        );
626    }
627
628    // ── CasPep with a real clearance source ─────────────────────────────────
629
630    struct FixtureClearance {
631        subject: String,
632        ctx: SecurityContext,
633    }
634
635    #[async_trait::async_trait]
636    impl CasClearanceSource for FixtureClearance {
637        async fn clearance_for(
638            &self,
639            subject_id: &str,
640            _verified_tenant: Option<&str>,
641        ) -> Option<SecurityContext> {
642            if subject_id == self.subject {
643                Some(self.ctx.clone())
644            } else {
645                None
646            }
647        }
648    }
649
650    fn ctx(level: Level) -> SecurityContext {
651        SecurityContext::from_clearance(
652            SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY),
653            VerifiedKeyMaterial::Classical,
654        )
655    }
656
657    struct TenantClearance;
658
659    #[async_trait::async_trait]
660    impl CasClearanceSource for TenantClearance {
661        async fn clearance_for(
662            &self,
663            subject_id: &str,
664            verified_tenant: Option<&str>,
665        ) -> Option<SecurityContext> {
666            (subject_id == "alice" && verified_tenant == Some("tenant-a"))
667                .then(|| ctx(Level::Secret))
668        }
669    }
670
671    async fn check(pep: &CasPep, subject_id: &str, label: Option<SecurityLabel>) -> MacDecision {
672        let resolver = CasObjectLabelResolver::new(label);
673        pep.check_read(subject_id, Some("tenant-a"), &resolver)
674            .await
675    }
676
677    #[derive(Default)]
678    struct SpySink {
679        records: Mutex<Vec<AuditRecord>>,
680    }
681
682    impl AuditSink for SpySink {
683        fn record(&self, record: &AuditRecord) -> Result<(), AuditError> {
684            self.records.lock().push(record.clone());
685            Ok(())
686        }
687    }
688
689    #[tokio::test]
690    async fn pep_permits_when_clearance_dominates_label() {
691        let sink = Arc::new(SpySink::default());
692        let pep = CasPep::new(
693            Arc::new(FixtureClearance {
694                subject: "secret-user".to_owned(),
695                ctx: ctx(Level::Secret),
696            }),
697            sink.clone(),
698        );
699        let label = domain_label(&DedupDomain::local_default()); // Internal
700        assert_eq!(
701            check(&pep, "secret-user", Some(label)).await,
702            MacDecision::Permit
703        );
704
705        let records = sink.records.lock();
706        assert_eq!(records.len(), 1);
707        assert_eq!(records[0].decision, Decision::Permit);
708    }
709
710    #[tokio::test]
711    async fn pep_threads_verified_tenant_to_clearance_source() {
712        let pep = CasPep::new(Arc::new(TenantClearance), Arc::new(SpySink::default()));
713        let resolver = CasObjectLabelResolver::from_domain(&DedupDomain::local_default());
714        assert_eq!(
715            pep.check_read("alice", Some("tenant-a"), &resolver).await,
716            MacDecision::Permit
717        );
718        assert_eq!(
719            pep.check_read("alice", None, &resolver).await,
720            MacDecision::Deny(MacDenyReason::NoClearance)
721        );
722    }
723
724    #[tokio::test]
725    async fn pep_denies_when_clearance_insufficient() {
726        let sink = Arc::new(SpySink::default());
727        let pep = CasPep::new(
728            Arc::new(FixtureClearance {
729                subject: "public-user".to_owned(),
730                ctx: ctx(Level::Public),
731            }),
732            sink.clone(),
733        );
734        let label = domain_label(&DedupDomain::local_default()); // Internal
735        assert_eq!(
736            check(&pep, "public-user", Some(label)).await,
737            MacDecision::Deny(MacDenyReason::FloorDeny)
738        );
739
740        let records = sink.records.lock();
741        assert_eq!(records[0].decision, Decision::Deny);
742        assert_eq!(records[0].reason, DecisionReason::FloorDeny);
743        assert_eq!(records[0].subject_id.as_deref(), Some("public-user"));
744        assert_eq!(records[0].object_id.as_deref(), Some("tenant-a/cas"));
745    }
746
747    #[tokio::test]
748    async fn pep_denies_unresolvable_subject() {
749        let sink = Arc::new(SpySink::default());
750        let pep = CasPep::new(
751            Arc::new(FixtureClearance {
752                subject: "known".to_owned(),
753                ctx: ctx(Level::Secret),
754            }),
755            sink.clone(),
756        );
757        let label = domain_label(&DedupDomain::local_default());
758        assert_eq!(
759            check(&pep, "unknown", Some(label)).await,
760            MacDecision::Deny(MacDenyReason::NoClearance)
761        );
762
763        let records = sink.records.lock();
764        assert_eq!(records[0].reason, DecisionReason::NoClearance);
765    }
766
767    #[tokio::test]
768    async fn pep_denies_unlabeled_object_even_with_clearance() {
769        let sink = Arc::new(SpySink::default());
770        let pep = CasPep::new(
771            Arc::new(FixtureClearance {
772                subject: "admin".to_owned(),
773                ctx: ctx(Level::Secret),
774            }),
775            sink.clone(),
776        );
777        assert_eq!(
778            check(&pep, "admin", None).await,
779            MacDecision::Deny(MacDenyReason::UnlabeledObject)
780        );
781
782        let records = sink.records.lock();
783        assert_eq!(records[0].reason, DecisionReason::UnlabeledObject);
784    }
785
786    // ── MacCasAuthorizer ────────────────────────────────────────────────────
787
788    #[tokio::test]
789    async fn mac_cas_authorizer_denies_with_fail_closed_pep() {
790        let authz = MacCasAuthorizer::fail_closed();
791        let domain = DedupDomain::local_default();
792        let req = CasMountAuthzRequest {
793            kind: CasMountObjectKind::Xorb,
794            address: "deadbeef",
795            domain: &domain,
796            verified_tenant: Some("tenant-a"),
797            operation: "read",
798            requested_label: None,
799        };
800        let subject = Subject::new("user");
801        assert!(authz.authorize(&subject, req).await.is_err());
802    }
803
804    #[tokio::test]
805    async fn mac_cas_authorizer_permits_with_dominating_clearance() {
806        let sink = Arc::new(SpySink::default());
807        let pep = Arc::new(CasPep::new(
808            Arc::new(FixtureClearance {
809                subject: "secret-user".to_owned(),
810                ctx: ctx(Level::Secret),
811            }),
812            sink,
813        ));
814        let authz = MacCasAuthorizer::new(pep);
815        let domain = DedupDomain::local_default();
816        let req = CasMountAuthzRequest {
817            kind: CasMountObjectKind::Xorb,
818            address: "deadbeef",
819            domain: &domain,
820            verified_tenant: Some("tenant-a"),
821            operation: "read",
822            requested_label: None,
823        };
824        let subject = Subject::new("secret-user");
825        assert!(authz.authorize(&subject, req).await.is_ok());
826    }
827
828    #[tokio::test]
829    async fn mac_cas_authorizer_uses_verified_http_tenant_for_clearance() {
830        let pep = Arc::new(CasPep::new(
831            Arc::new(TenantClearance),
832            Arc::new(SpySink::default()),
833        ));
834        let authz = MacCasAuthorizer::new(pep);
835        let domain = DedupDomain::local_default();
836        let subject = Subject::new("alice");
837
838        let tenant_a = CasMountAuthzRequest {
839            kind: CasMountObjectKind::Xorb,
840            address: "deadbeef",
841            domain: &domain,
842            verified_tenant: Some("tenant-a"),
843            operation: "read",
844            requested_label: None,
845        };
846        assert!(authz.authorize(&subject, tenant_a).await.is_ok());
847
848        let tenant_b = CasMountAuthzRequest {
849            kind: CasMountObjectKind::Xorb,
850            address: "deadbeef",
851            domain: &domain,
852            verified_tenant: Some("tenant-b"),
853            operation: "read",
854            requested_label: None,
855        };
856        assert!(authz.authorize(&subject, tenant_b).await.is_err());
857    }
858
859    #[tokio::test]
860    async fn mac_cas_authorizer_uses_domain_for_label() {
861        // SharedRemote domain → Confidential. A Secret clearance dominates; a
862        // Public clearance does not.
863        let sink = Arc::new(SpySink::default());
864        let pep = Arc::new(CasPep::new(
865            Arc::new(FixtureClearance {
866                subject: "public-user".to_owned(),
867                ctx: ctx(Level::Public),
868            }),
869            sink,
870        ));
871        let authz = MacCasAuthorizer::new(pep);
872        let domain = DedupDomain {
873            trust_boundary: TrustBoundary::SharedRemote,
874            ..DedupDomain::local_default()
875        };
876        let req = CasMountAuthzRequest {
877            kind: CasMountObjectKind::Object,
878            address: "some-addr",
879            domain: &domain,
880            verified_tenant: Some("tenant-a"),
881            operation: "open",
882            requested_label: None,
883        };
884        let subject = Subject::new("public-user");
885        assert!(
886            authz.authorize(&subject, req).await.is_err(),
887            "Public clearance must not read Confidential (shared-remote) content"
888        );
889    }
890}