hyprstream_9p/mac_seam.rs
1//! 9P reference-monitor contract (S2 / #568, epic #547).
2//!
3//! `hyprstream-9p` owns the 9P operation choke point but deliberately does not
4//! depend on the application crate that owns MAC policy loading and the AVC.
5//! This module is the dependency-inversion boundary: the application verifies a
6//! sender-bound access token once at `Tattach`, then the translator applies the
7//! label, token, and IFC gates *before* asking an injected local policy monitor
8//! (the application's AVC/PDP adapter).
9//!
10//! The mediation ordering is intentional and non-optional:
11//!
12//! ```text
13//! Tattach: verify sender-bound token -> SessionContext (cached per fid)
14//! each op: resolve content-truth label -> token scope -> IFC -> local AVC/PDP
15//! ```
16//!
17//! No token, expired token, unlabeled object, or non-dominating subject reaches
18//! the policy monitor, so a permissive policy implementation cannot bypass the
19//! mandatory token/IFC floor. Per-op cost is a fid-table lookup plus a local
20//! AVC call — never UCAN chain validation or Casbin matching.
21//!
22//! ## Production activation posture
23//!
24//! [`Translator`](crate::Translator) can run without a [`ReferenceMonitor`] for
25//! tests and embeddings, but every production constructor installs one. The
26//! mount-ticket paths derive a unified [`VerifiedAttach`] from verified Claims
27//! and key material, while fixed-subject transports remain floor-only until
28//! they gain a credential carrier. The operator activation control widens or
29//! narrows the subject context; it never removes mediation.
30//!
31//! ## Mediation is over the *name*, not the *object* (read before relying on it)
32//!
33//! The monitor is authoritative over the **path** a fid is tagged with, not
34//! over the **object** the backend resolves that fid to. [`ReferenceMonitor::
35//! authorize`] resolves the label from `ObjectRef::Path(components)` (the
36//! cached walked path), while the backend independently resolves the fid to an
37//! actual object/handle. Nothing in this contract *binds* the labeled name to
38//! the served object: the invariant "the label checked is the label of the
39//! object served" holds **only if the label resolver and the backend resolve
40//! names identically**. That is a convention, not an enforced invariant — so
41//! the honest statement of #568's "complete mediation" claim is:
42//!
43//! > Every dispatched op is routed through the monitor, **and** the monitor's
44//! > label resolver agrees with the backend's name resolution for the served
45//! > namespace. The first half is by construction; the second is a precondition.
46//!
47//! Concretely, this name↔object gap is **not** covered today:
48//!
49//! - **Partial walks** — the backend reports its exact reached request prefix,
50//! and the translator rejects a result whose QID count disagrees with that
51//! prefix. `MountBackend` emits one QID per bound component; `ModelBackend`
52//! rejects multi-name walks until it can provide that same contract. This
53//! prevents the former one-leaf-QID/deep-fid mismatch, but still relies on
54//! the label resolver and backend agreeing on what a reported path names.
55//! - **Path traversal / `..`** — `hyprstream-9p` performs **no** `..`
56//! canonicalization; `wnames` are concatenated verbatim into the cached path.
57//! Not exploitable against `MemoryBackend`/`MountBackend` (they resolve
58//! component-wise from a root), but a future resolver that does not
59//! canonicalize identically to the backend reopens this gap. Any resolver
60//! wired at activation **must** canonicalize or reject `..`, or the label
61//! lookup and the backend resolution can diverge.
62//! - **Bind / symlink / mount indirection** — the VFS supports bind mounts and
63//! per-process bind namespaces. If a path component resolves through an
64//! indirection the string-keyed resolver does not model, the label checked is
65//! for the *name* and the bytes served are for the *target*. `ObjectRef::Cid`
66//! exists precisely to close this (content-addressed refs bind the label to
67//! the object, not the name); the 9P seam feeds `ObjectRef::Path`.
68//!
69//! Closing the name↔object TOCTOU by making the monitor authoritative over the
70//! **fid/object** (e.g. resolving labels from the backend's reached object, or
71//! via `ObjectRef::Cid`) is **activation-blocking** and tracked with #699.
72//! Until then, treat "complete mediation by construction" as the
73//! *two-independent-resolutions-agree* claim above, not as object authority.
74
75use std::sync::Arc;
76use std::time::Instant;
77
78use async_trait::async_trait;
79use hyprstream_rpc::auth::mac::{
80 Assurance, CompartmentSet, Level, SecurityContext, SecurityLabel, VerifiedKeyMaterial,
81};
82use hyprstream_rpc::Subject;
83use hyprstream_vfs::MountError;
84
85pub use hyprstream_rpc::auth::mac::{ObjectLabelResolver, ObjectRef};
86
87/// The 9P operation an [`AccessDecider`] is asked to authorize.
88///
89/// Mirrors the translator's dispatch surface (`walk`/`open`/`read`/`write`/
90/// `getattr`/`readdir`) so a real decider can apply per-action policy (e.g.
91/// deny `Write` more aggressively than `Read`). Only ops the translator
92/// actually dispatches appear here — there is no `Tlcreate`/`Tremove` handler,
93/// so no `Create`/`Remove` variant (a dead variant would be an unreachable
94/// policy surface). `Tclunk` is fid disposal, not an object operation, and is
95/// deliberately not mediated.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
97pub enum Action {
98 Attach,
99 Walk,
100 Open,
101 Read,
102 Write,
103 Getattr,
104 Readdir,
105}
106
107/// A verified, sender-bound access-token scope cached for one 9P attach.
108///
109/// This type intentionally contains only the deny-only token facts needed on
110/// the hot path. Signature/expiry/DPoP verification happens in the
111/// [`AttachAuthenticator`] before constructing it; UCAN chain validation never
112/// runs per operation. The object label is *not* token-supplied: it is passed
113/// to [`Self::authorizes`] by the reference monitor after trusted resolution.
114#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct VerifiedTokenScope {
116 label_ceiling: SecurityLabel,
117 operations: Arc<[Action]>,
118 valid_until: Instant,
119}
120
121impl VerifiedTokenScope {
122 /// Build the local representation of an access token that has already had
123 /// its signature, sender binding, and expiry verified at attach time.
124 ///
125 /// Callers must not derive these values from a UCAN/caveat or a
126 /// caller-supplied label. The monitor independently resolves the object
127 /// label from the mounted object's manifest/genesis source.
128 pub fn from_verified_token(
129 label_ceiling: SecurityLabel,
130 operations: impl Into<Arc<[Action]>>,
131 valid_until: Instant,
132 ) -> Self {
133 Self {
134 label_ceiling,
135 operations: operations.into(),
136 valid_until,
137 }
138 }
139
140 /// The token's label ceiling, for diagnostics and application audit code.
141 pub fn label_ceiling(&self) -> SecurityLabel {
142 self.label_ceiling
143 }
144
145 /// Token gate: unexpired, exact operation membership, and object label no
146 /// more restrictive than the verified token's ceiling.
147 #[inline]
148 pub fn authorizes(&self, object_label: &SecurityLabel, action: Action) -> bool {
149 Instant::now() < self.valid_until
150 && self.operations.contains(&action)
151 && self.label_ceiling.can_access(object_label)
152 }
153}
154
155/// Attach-scoped state cached onto every fid derived from the attach fid.
156///
157/// The public constructor is intentionally named for its trust precondition:
158/// only an [`AttachAuthenticator`] that has verified the presented token and
159/// DPoP sender binding may construct a permitting session. There is no
160/// constructor from raw `uname`, `Subject`, claims, paths, or labels.
161#[derive(Clone, Debug, PartialEq, Eq)]
162pub struct SessionContext {
163 attach_identity: Option<VerifiedAttachIdentity>,
164 security_context: SecurityContext,
165 token: Option<VerifiedTokenScope>,
166}
167
168/// Stable principal or credential identity returned by an
169/// [`AttachAuthenticator`] after verification.
170///
171/// This is deliberately separate from [`SecurityContext`]: clearance and key
172/// assurance are authorization attributes, not a principal identity. The
173/// verifier must derive this from the verified subject or stable credential
174/// fingerprint, never from an unverified `Tattach.uname` string.
175#[derive(Clone, Debug, PartialEq, Eq)]
176pub struct VerifiedAttachIdentity {
177 subject: Arc<str>,
178 tenant: Arc<str>,
179}
180
181/// One credential verification result shared by both enforcement sides of a
182/// 9P attach. The MAC session and the VFS subject cannot be supplied
183/// independently.
184#[derive(Clone, Debug, PartialEq, Eq)]
185pub struct VerifiedAttach {
186 identity: VerifiedAttachIdentity,
187 subject: Subject,
188 session: SessionContext,
189}
190
191impl VerifiedAttach {
192 /// Bind a credential-verified identity to the exact VFS subject and MAC
193 /// session derived from that same verification.
194 pub fn try_new(
195 identity: VerifiedAttachIdentity,
196 subject: Subject,
197 session: SessionContext,
198 ) -> Result<Self, MountError> {
199 let subject_name = subject.name().ok_or_else(|| {
200 MountError::PermissionDenied("verified attach has anonymous VFS subject".to_owned())
201 })?;
202 if subject_name != identity.subject() {
203 return Err(MountError::PermissionDenied(
204 "MAC identity and VFS subject diverge".to_owned(),
205 ));
206 }
207 if identity.tenant().is_empty() {
208 return Err(MountError::PermissionDenied(
209 "verified attach has no authority-bound tenant".to_owned(),
210 ));
211 }
212 if session.verified_attach_identity() != Some(&identity) {
213 return Err(MountError::PermissionDenied(
214 "MAC session identity and verified attach identity diverge".to_owned(),
215 ));
216 }
217 Ok(Self {
218 identity,
219 subject,
220 session,
221 })
222 }
223
224 pub fn identity(&self) -> &VerifiedAttachIdentity {
225 &self.identity
226 }
227
228 pub fn subject(&self) -> &Subject {
229 &self.subject
230 }
231
232 pub fn session(&self) -> &SessionContext {
233 &self.session
234 }
235}
236
237impl VerifiedAttachIdentity {
238 /// Construct an identity and tenant obtained from verified credential
239 /// material.
240 ///
241 /// Both values must come from the same successful ticket/attach
242 /// verification. Raw `Tattach.uname` input is not verified credential
243 /// material and must never be passed here.
244 pub fn from_verified_credential(
245 subject: impl Into<Arc<str>>,
246 tenant: impl Into<Arc<str>>,
247 ) -> Self {
248 Self {
249 subject: subject.into(),
250 tenant: tenant.into(),
251 }
252 }
253
254 /// Verified subject identity.
255 pub fn subject(&self) -> &str {
256 &self.subject
257 }
258
259 /// Verified tenant/domain bound by the same credential.
260 pub fn tenant(&self) -> &str {
261 &self.tenant
262 }
263}
264
265impl SessionContext {
266 /// Combine a verified subject context with the scope of the same verified,
267 /// sender-bound token.
268 pub fn from_verified_token(
269 attach_identity: VerifiedAttachIdentity,
270 security_context: SecurityContext,
271 token: VerifiedTokenScope,
272 ) -> Self {
273 Self {
274 attach_identity: Some(attach_identity),
275 security_context,
276 token: Some(token),
277 }
278 }
279
280 /// A session with a verified clearance but **no sender-bound token**.
281 ///
282 /// Every op denies at the token gate ([`Self::token_authorizes`] returns
283 /// `false` when `token` is `None`). This is the **fail-closed structural**
284 /// constructor for the #698 / S6 token path that is not yet wired: the
285 /// monitor is installed, clearance derivation is real (or fail-closed via
286 /// the clearance source), but no capability token has been minted yet, so
287 /// the session cannot authorize any operation. There is no permissive
288 /// default.
289 ///
290 /// Once the S6 grant path issues a sender-bound token at `Tattach`, the
291 /// production authenticator will construct via
292 /// [`from_verified_token`](Self::from_verified_token) instead.
293 pub fn from_verified_clearance(
294 attach_identity: VerifiedAttachIdentity,
295 security_context: SecurityContext,
296 ) -> Self {
297 Self {
298 attach_identity: Some(attach_identity),
299 security_context,
300 token: None,
301 }
302 }
303
304 /// A deliberately unusable session for an invalid or absent credential.
305 /// The anonymous security floor is kept for diagnostics; the missing token
306 /// makes every operation deny before the AVC/PDP is reached.
307 pub fn deny() -> Self {
308 Self {
309 attach_identity: None,
310 security_context: anonymous_floor(),
311 token: None,
312 }
313 }
314
315 /// Verified, tenant-bound attach identity, absent for a fail-closed session.
316 pub fn verified_attach_identity(&self) -> Option<&VerifiedAttachIdentity> {
317 self.attach_identity.as_ref()
318 }
319
320 /// The context derived at attach from verified identity and key material.
321 pub fn security_context(&self) -> &SecurityContext {
322 &self.security_context
323 }
324
325 /// Apply the mandatory verified-token gate. A missing token is deny.
326 #[inline]
327 pub fn token_authorizes(&self, object_label: &SecurityLabel, action: Action) -> bool {
328 self.token
329 .as_ref()
330 .is_some_and(|token| token.authorizes(object_label, action))
331 }
332
333 /// Identity comparison for re-attach detection, deliberately distinct from
334 /// the derived [`PartialEq`].
335 ///
336 /// Two attaches are the *same* session when their verified identity,
337 /// verified subject context, and verified-token scope (label ceiling +
338 /// permitted operations) match.
339 /// The token's `valid_until` deadline is excluded on purpose: a real
340 /// [`AttachAuthenticator`] re-stamps `Instant::now() + ttl` on every
341 /// verification of the *same* ticket, so including it would make an
342 /// identical, still-valid ticket compare unequal and wrongly reject a
343 /// legitimate re-attach/reconnect (F2). The derived `PartialEq` is plain
344 /// value equality (useful for diagnostics/tests); *attach identity* — what
345 /// `bind_attach_session` checks — is this method.
346 pub fn same_attach_identity(&self, other: &SessionContext) -> bool {
347 if self.attach_identity != other.attach_identity {
348 return false;
349 }
350 if self.security_context != other.security_context {
351 return false;
352 }
353 match (&self.token, &other.token) {
354 // The token's `valid_until` is deliberately ignored: a real
355 // authenticator re-stamps it on every verification of the same
356 // ticket, so it is not part of attach identity.
357 (None, None) => true,
358 (Some(a), Some(b)) => {
359 a.label_ceiling == b.label_ceiling && a.operations == b.operations
360 }
361 _ => false,
362 }
363 }
364}
365
366/// Verifies the `Tattach` credential and returns the session cached per fid.
367///
368/// Implementations verify the S6-minted access token once (hybrid signature,
369/// expiry, DPoP binding, and policy generation), derive `SecurityContext` from
370/// verified identity/key material, and translate the token's authorized subset
371/// to [`VerifiedTokenScope`]. Invalid input returns [`SessionContext::deny`].
372#[async_trait]
373pub trait AttachAuthenticator: Send + Sync {
374 async fn authenticate(&self, uname: &str, aname: &str) -> Result<VerifiedAttach, MountError>;
375}
376
377/// Fail-closed authenticator: every attach resolves to a deny-only session.
378/// Used by [`ReferenceMonitor`] constructions that have not been given an
379/// application authenticator, and by tests.
380#[derive(Debug, Default, Clone, Copy)]
381pub struct AnonymousAuthenticator;
382
383#[async_trait]
384impl AttachAuthenticator for AnonymousAuthenticator {
385 async fn authenticate(&self, _uname: &str, _aname: &str) -> Result<VerifiedAttach, MountError> {
386 Err(MountError::PermissionDenied(
387 "no verified attach credential".to_owned(),
388 ))
389 }
390}
391
392/// The anonymous security floor. It is not authorization: a session at this
393/// floor still has no [`VerifiedTokenScope`] and is denied.
394pub fn anonymous_floor() -> SecurityContext {
395 SecurityContext::from_clearance(
396 SecurityLabel::new(Level::Public, Assurance::Unverified, CompartmentSet::EMPTY),
397 VerifiedKeyMaterial::Unverified,
398 )
399}
400
401/// Fail-closed label resolver for a mount with no content/static label source.
402/// A real export injects the genesis/manifest resolver owned by the
403/// application. Returning `None` is a mandatory deny (design §1 invariant 2).
404#[derive(Debug, Default, Clone, Copy)]
405pub struct DenyUnlabeledResolver;
406
407impl ObjectLabelResolver for DenyUnlabeledResolver {
408 fn resolve(&self, _object: ObjectRef<'_>) -> Option<SecurityLabel> {
409 None
410 }
411}
412
413/// Authorizes one operation against a subject's cached [`SecurityContext`] and
414/// exact walked object reference.
415///
416/// Resolution belongs to the concrete implementation in `hyprstream`, which
417/// owns the production content-truth label resolver and tamper-evident audit
418/// sink. Passing the object reference—not an optional caller-supplied
419/// label—keeps label resolution and auditing inside the authoritative PEP.
420pub trait AccessDecider: Send + Sync {
421 fn check(&self, ctx: &SecurityContext, object: ObjectRef<'_>, action: Action) -> bool;
422
423 /// Record a denial made by the reference monitor before the local policy
424 /// decision is reached.
425 ///
426 /// Production implementations must write through the same tamper-evident
427 /// audit sink used by [`Self::check`]. This method is required rather than
428 /// defaulted so adding an early-return gate cannot silently create an
429 /// unaudited denial path.
430 fn audit_denial(
431 &self,
432 ctx: &SecurityContext,
433 object: ObjectRef<'_>,
434 object_label: Option<SecurityLabel>,
435 action: Action,
436 reason: ReferenceMonitorDenyReason,
437 );
438}
439
440/// Denial gates owned by [`ReferenceMonitor`] rather than the local decider.
441#[derive(Debug, Clone, Copy, PartialEq, Eq)]
442pub enum ReferenceMonitorDenyReason {
443 /// Trusted object-label resolution returned no label.
444 UnlabeledObject,
445 /// The verified sender-bound token was missing, expired, or insufficient.
446 TokenGate,
447 /// The independent read/write IFC floor denied.
448 FloorDeny,
449}
450
451/// Fail-closed fallback for layers that cannot construct the production
452/// resolver-backed, audited decider.
453#[derive(Debug, Default, Clone, Copy)]
454pub struct DenyAllDecider;
455
456impl AccessDecider for DenyAllDecider {
457 fn check(&self, ctx: &SecurityContext, object: ObjectRef<'_>, action: Action) -> bool {
458 tracing::warn!(
459 target: "hyprstream.mac.audit",
460 ?object,
461 ?action,
462 clearance = ?ctx.clearance(),
463 "9P access denied: production MAC decider unavailable"
464 );
465 false
466 }
467
468 fn audit_denial(
469 &self,
470 ctx: &SecurityContext,
471 object: ObjectRef<'_>,
472 object_label: Option<SecurityLabel>,
473 action: Action,
474 reason: ReferenceMonitorDenyReason,
475 ) {
476 tracing::warn!(
477 target: "hyprstream.mac.audit",
478 ?object,
479 ?object_label,
480 ?action,
481 ?reason,
482 clearance = ?ctx.clearance(),
483 "9P access denied before local decider: production MAC decider unavailable"
484 );
485 }
486}
487
488/// The reference monitor a [`Translator`](crate::Translator) mediates every
489/// dispatched op through once installed. Bundles the three injection points so
490/// enforcement is all-or-nothing: there is no translator state in which the
491/// token gate runs but the label resolver is absent, or vice versa.
492///
493/// Constructed by the application (`hyprstream` crate) at activation time from
494/// its concrete token verifier, genesis/manifest label resolver, and AVC/PDP
495/// adapter. The application installs it at every production 9P constructor;
496/// monitor-less translators remain available for tests and embeddings.
497pub struct ReferenceMonitor {
498 authenticator: Arc<dyn AttachAuthenticator>,
499 labels: Arc<dyn ObjectLabelResolver + Send + Sync>,
500 decider: Arc<dyn AccessDecider>,
501}
502
503impl ReferenceMonitor {
504 /// Assemble the monitor from its three mandatory seams. There is no
505 /// permissive or partial construction: each argument is required, and the
506 /// crate's fail-closed defaults ([`AnonymousAuthenticator`],
507 /// [`DenyUnlabeledResolver`], [`DenyAllDecider`]) are the explicit choices
508 /// for a seam the application does not supply.
509 pub fn new(
510 authenticator: Arc<dyn AttachAuthenticator>,
511 labels: Arc<dyn ObjectLabelResolver + Send + Sync>,
512 decider: Arc<dyn AccessDecider>,
513 ) -> Self {
514 Self {
515 authenticator,
516 labels,
517 decider,
518 }
519 }
520
521 /// Verify the `Tattach` credential exactly once for this connection.
522 pub async fn authenticate(
523 &self,
524 uname: &str,
525 aname: &str,
526 ) -> Result<VerifiedAttach, MountError> {
527 self.authenticator.authenticate(uname, aname).await
528 }
529
530 /// Complete mediation for one op on `path` under `session`, in the
531 /// mandatory order: trusted label resolution → token gate → independent
532 /// IFC dominance → local policy monitor. Every step fails closed: an
533 /// unresolvable label, missing/expired/insufficient token, non-dominating
534 /// subject, or decider denial all return `false`.
535 pub fn authorize(&self, session: &SessionContext, path: &[String], action: Action) -> bool {
536 let components: Vec<&str> = path.iter().map(String::as_str).collect();
537 let object = ObjectRef::Path(&components);
538 let Some(object_label) = self.labels.resolve(ObjectRef::Path(&components)) else {
539 self.decider.audit_denial(
540 session.security_context(),
541 object,
542 None,
543 action,
544 ReferenceMonitorDenyReason::UnlabeledObject,
545 );
546 return false;
547 };
548
549 // Token is a deny-only capability gate. Its label ceiling is checked
550 // against the trusted object label, never a token/UCAN-provided label.
551 if !session.token_authorizes(&object_label, action) {
552 self.decider.audit_denial(
553 session.security_context(),
554 object,
555 Some(object_label),
556 action,
557 ReferenceMonitorDenyReason::TokenGate,
558 );
559 return false;
560 }
561
562 // IFC dominance is independent of the token and the policy matrix.
563 // Write operations use the *-property (no-write-down); reads use the
564 // simple-security rule (no-read-up). The assurance axis is a crypto
565 // floor in both directions and does not flip.
566 let ifc_ok = if action == Action::Write {
567 session.security_context().can_write_to(&object_label)
568 } else {
569 session.security_context().can_access(&object_label)
570 };
571 if !ifc_ok {
572 self.decider.audit_denial(
573 session.security_context(),
574 object,
575 Some(object_label),
576 action,
577 ReferenceMonitorDenyReason::FloorDeny,
578 );
579 return false;
580 }
581
582 self.decider.check(
583 session.security_context(),
584 ObjectRef::Path(&components),
585 action,
586 )
587 }
588}
589
590#[cfg(test)]
591#[allow(clippy::unwrap_used)]
592mod tests {
593 use super::*;
594 use std::time::Duration;
595
596 fn label(level: Level) -> SecurityLabel {
597 SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY)
598 }
599
600 fn ctx(level: Level) -> SecurityContext {
601 // Classical key material so the derived assurance dominates the
602 // Classical-assurance object labels used across these tests.
603 SecurityContext::new(level, CompartmentSet::EMPTY, VerifiedKeyMaterial::Classical)
604 }
605
606 fn permit_token(ops: &[Action]) -> VerifiedTokenScope {
607 VerifiedTokenScope::from_verified_token(
608 label(Level::Secret),
609 Arc::from(ops),
610 Instant::now() + Duration::from_secs(3600),
611 )
612 }
613
614 struct StaticLabels(Option<SecurityLabel>);
615 impl ObjectLabelResolver for StaticLabels {
616 fn resolve(&self, _object: ObjectRef<'_>) -> Option<SecurityLabel> {
617 self.0
618 }
619 }
620
621 struct AllowAll;
622 impl AccessDecider for AllowAll {
623 fn check(&self, _ctx: &SecurityContext, _object: ObjectRef<'_>, _action: Action) -> bool {
624 true
625 }
626
627 fn audit_denial(
628 &self,
629 _ctx: &SecurityContext,
630 _object: ObjectRef<'_>,
631 _object_label: Option<SecurityLabel>,
632 _action: Action,
633 _reason: ReferenceMonitorDenyReason,
634 ) {
635 }
636 }
637
638 fn monitor(labels: Option<SecurityLabel>, decider: Arc<dyn AccessDecider>) -> ReferenceMonitor {
639 ReferenceMonitor::new(
640 Arc::new(AnonymousAuthenticator),
641 Arc::new(StaticLabels(labels)),
642 decider,
643 )
644 }
645
646 fn path(parts: &[&str]) -> Vec<String> {
647 parts.iter().map(|s| (*s).to_owned()).collect()
648 }
649
650 #[test]
651 fn token_scope_requires_unexpired_op_and_label_ceiling() {
652 let scope = VerifiedTokenScope::from_verified_token(
653 label(Level::Confidential),
654 Arc::from([Action::Read]),
655 Instant::now() + Duration::from_secs(10),
656 );
657 assert!(scope.authorizes(&label(Level::Public), Action::Read));
658 assert!(!scope.authorizes(&label(Level::Public), Action::Write));
659 assert!(!scope.authorizes(&label(Level::Secret), Action::Read));
660 }
661
662 #[test]
663 fn expired_or_missing_token_fails_closed() {
664 let expired = VerifiedTokenScope::from_verified_token(
665 label(Level::Secret),
666 Arc::from([Action::Read]),
667 Instant::now() - Duration::from_secs(1),
668 );
669 assert!(!expired.authorizes(&label(Level::Public), Action::Read));
670 assert!(!SessionContext::deny().token_authorizes(&label(Level::Public), Action::Read));
671 }
672
673 #[test]
674 fn authorize_allows_when_all_gates_pass() {
675 let monitor = monitor(Some(label(Level::Public)), Arc::new(AllowAll));
676 let session = SessionContext::from_verified_token(
677 VerifiedAttachIdentity::from_verified_credential("test-subject", "test-tenant"),
678 ctx(Level::Secret),
679 permit_token(&[Action::Read]),
680 );
681 assert!(monitor.authorize(&session, &path(&["a.txt"]), Action::Read));
682 }
683
684 #[test]
685 fn authorize_denies_unlabeled_before_decider() {
686 // Even a permit-everything decider cannot rescue an unlabeled object.
687 let monitor = monitor(None, Arc::new(AllowAll));
688 let session = SessionContext::from_verified_token(
689 VerifiedAttachIdentity::from_verified_credential("test-subject", "test-tenant"),
690 ctx(Level::Secret),
691 permit_token(&[Action::Read]),
692 );
693 assert!(!monitor.authorize(&session, &path(&["a.txt"]), Action::Read));
694 }
695
696 #[test]
697 fn authorize_denies_missing_or_scope_violating_token() {
698 let monitor = monitor(Some(label(Level::Public)), Arc::new(AllowAll));
699 assert!(!monitor.authorize(&SessionContext::deny(), &path(&["a.txt"]), Action::Read));
700 let read_only = SessionContext::from_verified_token(
701 VerifiedAttachIdentity::from_verified_credential("test-subject", "test-tenant"),
702 ctx(Level::Secret),
703 permit_token(&[Action::Read]),
704 );
705 assert!(!monitor.authorize(&read_only, &path(&["a.txt"]), Action::Write));
706 }
707
708 #[test]
709 fn authorize_enforces_ifc_floor_independent_of_decider() {
710 // Permissive policy must not bypass the mandatory IFC floor: a Public
711 // subject reading a Secret object denies even with an allow-all
712 // decider and a token whose ceiling covers it.
713 let monitor = monitor(Some(label(Level::Secret)), Arc::new(AllowAll));
714 let session = SessionContext::from_verified_token(
715 VerifiedAttachIdentity::from_verified_credential("test-subject", "test-tenant"),
716 ctx(Level::Public),
717 permit_token(&[Action::Read]),
718 );
719 assert!(!monitor.authorize(&session, &path(&["secret.txt"]), Action::Read));
720 }
721
722 #[test]
723 fn deny_unlabeled_resolver_resolves_nothing() {
724 let resolver = DenyUnlabeledResolver;
725 assert!(resolver.resolve(ObjectRef::Path(&["anything"])).is_none());
726 }
727
728 #[test]
729 fn authorize_write_uses_no_write_down_ifc() {
730 // A Secret subject with a write-capable token may write to a Secret
731 // object but NOT to a Public one (no-write-down / *-property).
732 let secret_obj = label(Level::Secret);
733 let public_obj = label(Level::Public);
734 let mon = monitor(Some(secret_obj), Arc::new(AllowAll));
735 let session = SessionContext::from_verified_token(
736 VerifiedAttachIdentity::from_verified_credential("writer", "test-tenant"),
737 ctx(Level::Secret),
738 VerifiedTokenScope::from_verified_token(
739 label(Level::Secret),
740 Arc::from([Action::Read, Action::Write]),
741 Instant::now() + Duration::from_secs(3600),
742 ),
743 );
744 // Write to Secret object: allowed (same level, all gates pass).
745 assert!(mon.authorize(&session, &path(&["secret"]), Action::Write));
746
747 // Now test write-down: relabel to Public. A Secret writer must not write
748 // to a Public object.
749 let mon_down = monitor(Some(public_obj), Arc::new(AllowAll));
750 assert!(!mon_down.authorize(&session, &path(&["public"]), Action::Write));
751 }
752
753 #[test]
754 fn from_verified_clearance_session_denies_at_token_gate() {
755 // A clearance-only session (no S6 token) denies every op, even with a
756 // permissive decider and a Public object. Fail-closed structural shape.
757 let mon = monitor(Some(label(Level::Public)), Arc::new(AllowAll));
758 let session = SessionContext::from_verified_clearance(
759 VerifiedAttachIdentity::from_verified_credential("stub", "test-tenant"),
760 ctx(Level::Secret),
761 );
762 assert!(!mon.authorize(&session, &path(&["public"]), Action::Read));
763 assert!(!mon.authorize(&session, &path(&["public"]), Action::Write));
764 }
765
766 #[test]
767 fn verified_attach_identity_is_tenant_bound_and_denied_sessions_have_none() {
768 let tenant_a = SessionContext::from_verified_clearance(
769 VerifiedAttachIdentity::from_verified_credential("alice", "tenant-a"),
770 ctx(Level::Secret),
771 );
772 let tenant_b = SessionContext::from_verified_clearance(
773 VerifiedAttachIdentity::from_verified_credential("alice", "tenant-b"),
774 ctx(Level::Secret),
775 );
776
777 assert!(!tenant_a.same_attach_identity(&tenant_b));
778 assert_eq!(
779 tenant_a
780 .verified_attach_identity()
781 .expect("verified session")
782 .tenant(),
783 "tenant-a",
784 );
785 assert!(SessionContext::deny().verified_attach_identity().is_none());
786 }
787}