Skip to main content

hyprstream_core/storage/cas/
mount.rs

1//! Subject-threaded 9P/VFS projection of the L1 CAS substrate (#813).
2//!
3//! The mount exposes CAS reads through the ordinary `Mount` surface, so access
4//! goes through open/read/stat authorization instead of treating hashes as
5//! bearer capabilities. A namespace may bind this mount wherever it chooses.
6//!
7//! ## Write-then-seal ingest (#814)
8//!
9//! Content addressing means the name (CID) is unknown until the bytes are
10//! complete (Venti-style), so ingest is a *staging-then-seal* protocol rather
11//! than an ordinary positioned write to a named file:
12//!
13//! 1. `create stage/new` (or `create /new` at the mount root) mints a
14//!    per-Subject staging slot and returns a directory fid on `stage/<id>/`.
15//!    Slots are quota'd per-slot and per-Subject (see [`StagingConfig`]).
16//! 2. `Twrite` at offset into `stage/<id>/data` accumulates bytes
17//!    (msize-chunked; resumable by offset; sparse gaps are zero-filled). Per-op
18//!    `Mount` IO is unbounded — the 16 MB cap in
19//!    [`hyprstream_vfs::namespace::MAX_READ_SIZE`] lives only on the `cat`/`echo`
20//!    convenience loops, which bulk data must never use.
21//! 3. Seal by writing `commit` to `stage/<id>/ctl` (**D-A**): the seal invokes
22//!    [`CasSubstrate::put`] (CDC chunking to xorbs happens *below* the seal
23//!    inside L1) and returns the manifest CID readback by *reading* `ctl`.
24//!    Cluck-sealing cannot return the CID inline, which is why the seal is an
25//!    explicit ctl command and the CID is read back separately.
26//! 4. Abort is cluck-without-commit (or `abort` on ctl): staged bytes are
27//!    discarded. Seal failure also converges to voided (fail-closed), matching
28//!    the attested-resource saga convergence rule (#1064/#1066).
29//!
30//! The seal is the natural join point for [`crate::mac::ifc_join`]: any object
31//! labels declared via `label` ctl commands are joined (LUB) and written into
32//! the manifest. A slot with no declared label cannot seal; unlabeled staging is
33//! transient only and is never admitted to the CAS.
34
35use std::collections::HashMap;
36use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
37use std::sync::Arc;
38
39use async_trait::async_trait;
40use cas_serve::StoreError;
41use hyprstream_rpc::auth::mac::{Assurance, CompartmentSet, Lattice, Level, SecurityLabel};
42use hyprstream_rpc::Subject;
43use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Stat, ORDWR, OREAD, OTRUNC, OWRITE};
44use parking_lot::Mutex;
45use tokio::sync::Notify;
46use tracing::{debug, warn};
47
48use super::{CasError, CasSubstrate, DedupDomain};
49use crate::mac::ifc_join;
50
51const QTDIR: u8 = 0x80;
52const QTFILE: u8 = 0x00;
53
54/// Default per-slot staging cap (256 MiB). Staging buffers are in-memory today;
55/// a spill-to-disk backing for truly huge ingests follows with the durable
56/// resource saga (#1064).
57pub const DEFAULT_STAGING_SLOT_QUOTA: usize = 256 * 1024 * 1024;
58/// Default per-Subject aggregate cap across all open staging slots (1 GiB).
59pub const DEFAULT_STAGING_SUBJECT_QUOTA: usize = 1024 * 1024 * 1024;
60
61/// Object class addressed through [`CasMount`].
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum CasMountObjectKind {
64    /// Full-file reconstruction by CID or legacy merkle.
65    Object,
66    /// Raw xorb bytes by xorb hash.
67    Xorb,
68    /// A write-then-seal staging slot (#814). `address` is the staging id.
69    Stage,
70}
71
72/// Authorization request made before a CAS operation.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct CasMountAuthzRequest<'a> {
75    /// Which CAS object namespace is being accessed.
76    pub kind: CasMountObjectKind,
77    /// CID, legacy merkle, xorb hash, or staging id, exactly as walked.
78    pub address: &'a str,
79    /// Dedup domain the mount is serving.
80    pub domain: &'a DedupDomain,
81    /// Authority-verified hosted-account tenant for the caller, when the
82    /// transport has one. This is transport context, never an object/path
83    /// field supplied by the caller.
84    pub verified_tenant: Option<&'a str>,
85    /// Operation name for policy/audit (e.g. `open`, `read`, `stat`,
86    /// `stage:create`, `stage:label`, `stage:commit`).
87    pub operation: &'static str,
88    /// Parsed object label proposed by a `stage:label` operation. `None` for
89    /// every other operation.
90    ///
91    /// A clearance-aware authorizer must resolve the caller's verified
92    /// [`hyprstream_rpc::auth::mac::SecurityContext`] and reject labels it does
93    /// not authorize. The raw ctl input is never authoritative by itself.
94    pub requested_label: Option<&'a SecurityLabel>,
95}
96
97/// Per-op authorization hook for [`CasMount`].
98///
99/// The default constructor uses [`DenyAllCasAuthorizer`]. The live XET read
100/// route uses [`BootstrapCasAuthorizer`] (#1094 plane #1: explicit, audited
101/// bootstrap grants, default-deny). As #699/#767 provenance and MAC plumbing
102/// lands, production namespaces move to a real MAC authorizer; trusted local
103/// single-tenant tools can explicitly opt into [`AllowAllCasAuthorizer`].
104#[async_trait::async_trait]
105pub trait CasMountAuthorizer: Send + Sync {
106    async fn authorize(
107        &self,
108        caller: &Subject,
109        request: CasMountAuthzRequest<'_>,
110    ) -> Result<(), MountError>;
111}
112
113/// Fail-closed authorizer used by [`CasMount::new`].
114#[derive(Debug, Default)]
115pub struct DenyAllCasAuthorizer;
116
117#[async_trait::async_trait]
118impl CasMountAuthorizer for DenyAllCasAuthorizer {
119    async fn authorize(
120        &self,
121        caller: &Subject,
122        request: CasMountAuthzRequest<'_>,
123    ) -> Result<(), MountError> {
124        Err(MountError::PermissionDenied(format!(
125            "CAS {} {} denied for {}: no CasMountAuthorizer installed",
126            request.operation, request.address, caller
127        )))
128    }
129}
130
131/// Explicit allow authorizer for tests and trusted local single-tenant wiring.
132#[derive(Debug, Default)]
133pub struct AllowAllCasAuthorizer;
134
135#[async_trait::async_trait]
136impl CasMountAuthorizer for AllowAllCasAuthorizer {
137    async fn authorize(
138        &self,
139        _caller: &Subject,
140        _request: CasMountAuthzRequest<'_>,
141    ) -> Result<(), MountError> {
142        Ok(())
143    }
144}
145
146// ─────────────────────────────────────────────────────────────────────────────
147// Bootstrap-grant authorizer (#1094)
148// ─────────────────────────────────────────────────────────────────────────────
149
150/// Who a [`CasMountGrant`] applies to — the *subject breadth* axis the #1094
151/// ratchet narrows.
152///
153/// Today there is exactly one breadth: the authenticated floor. Per-compartment
154/// and per-subject variants arrive with #698 (authority-owned subject
155/// clearances) and #699 (object provenance labels); they are deliberately not
156/// modeled yet — see the ratchet path on [`BootstrapCasAuthorizer`].
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum CasGrantSubject {
159    /// Any authenticated (non-anonymous) [`Subject`]. Anonymous callers never
160    /// match: the floor is *authenticated*, not bearerless.
161    AnyAuthenticated,
162}
163
164impl CasGrantSubject {
165    fn accepts(self, caller: &Subject) -> bool {
166        match self {
167            CasGrantSubject::AnyAuthenticated => !caller.is_anonymous(),
168        }
169    }
170}
171
172/// One explicit authorization grant — the unit of policy the
173/// [`BootstrapCasAuthorizer`] evaluates (#1094).
174///
175/// A request matches a grant when the caller is accepted by `subject`, the
176/// request's [`CasMountObjectKind`] is in `kinds`, and its operation string is
177/// in `operations`. A request matching **no** grant is denied (fail-closed).
178///
179/// The shape mirrors the MAC decision it will become — subject breadth ×
180/// object class × operation — so ratcheting toward the #698/#699 dominance
181/// check (`subject.ctx ⊒ object.label` per op) narrows fields of this struct
182/// instead of replacing an incompatible interim model.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub struct CasMountGrant {
185    /// Stable audit name emitted with every decision the grant allows.
186    pub name: &'static str,
187    /// Subject breadth.
188    pub subject: CasGrantSubject,
189    /// Object kinds covered.
190    pub kinds: &'static [CasMountObjectKind],
191    /// Operations covered (matched against [`CasMountAuthzRequest::operation`]).
192    pub operations: &'static [&'static str],
193}
194
195/// The day-one bootstrap grant: **"any authenticated subject may read xorb
196/// X"** (#1094). Covers `open` + `read` on [`CasMountObjectKind::Xorb`] only —
197/// `stat`, `obj/*` reads, and every `stage/*` operation stay denied.
198pub const AUTHENTICATED_XORB_READ: CasMountGrant = CasMountGrant {
199    name: "bootstrap:authenticated-xorb-read",
200    subject: CasGrantSubject::AnyAuthenticated,
201    kinds: &[CasMountObjectKind::Xorb],
202    operations: &["open", "read"],
203};
204
205/// Enforcing authorizer for the live `GET /get_xorb/{hash}/` surface (#1094):
206/// an explicit bootstrap grant list, default-deny, one audit event per decision.
207///
208/// This is plane #1 of #1091's R4b *compile-and-ratchet* MAC rollout: the route
209/// flips to enforcing on day one behind [`AUTHENTICATED_XORB_READ`], making
210/// today's implicit authenticated floor an explicit, auditable policy object
211/// instead of a silent [`AllowAllCasAuthorizer`].
212///
213/// ## Ratchet path (grant breadth → 0)
214///
215/// The day-one grant is maximally broad on two axes: every authenticated
216/// subject, every xorb address. Ratcheting is a deliberate, reviewable edit of
217/// the grant list, sequenced with the MAC-activation prerequisites:
218///
219/// 1. **#699 lands provenance labels** — repo/compartment `security_label`s on
220///    xorb-bearing manifests (carrier-(b)) give each request a real object
221///    label. Grants can then narrow per-domain, then per-compartment.
222/// 2. **#698 flows subject clearances** — authority-owned `Claims.clearance`
223///    gives the caller a real `SecurityContext`; [`CasGrantSubject`] gains
224///    clearance-bearing variants and the decision becomes dominance
225///    (`subject.ctx ⊒ object.label`) per op.
226/// 3. **Breadth 0** — with labels + clearances live, the grant list empties
227///    (== [`DenyAllCasAuthorizer`]) and this type is retired in favor of the
228///    MAC authorizer on the same [`CasMountAuthorizer`] seam.
229///
230/// That labeling/clearance work is **not** in scope here; only the seam and
231/// the day-one grant are.
232///
233/// Audit: allows log at `debug`, denies at `warn` (denials are
234/// security-relevant). Tamper-evident decision audit (#573,
235/// `crate::mac::audit`) takes over when the MAC authorizer lands.
236#[derive(Debug, Clone)]
237pub struct BootstrapCasAuthorizer {
238    grants: Vec<CasMountGrant>,
239}
240
241impl BootstrapCasAuthorizer {
242    /// The day-one policy (#1094): exactly [`AUTHENTICATED_XORB_READ`].
243    pub fn new() -> Self {
244        Self {
245            grants: vec![AUTHENTICATED_XORB_READ],
246        }
247    }
248
249    /// An explicit grant list — the ratchet knob. Narrow the list as #699
250    /// labels and #698 clearances land; an empty list denies everything
251    /// (equivalent to [`DenyAllCasAuthorizer`]).
252    pub fn with_grants(grants: Vec<CasMountGrant>) -> Self {
253        Self { grants }
254    }
255}
256
257impl Default for BootstrapCasAuthorizer {
258    fn default() -> Self {
259        Self::new()
260    }
261}
262
263#[async_trait::async_trait]
264impl CasMountAuthorizer for BootstrapCasAuthorizer {
265    async fn authorize(
266        &self,
267        caller: &Subject,
268        request: CasMountAuthzRequest<'_>,
269    ) -> Result<(), MountError> {
270        // Bootstrap grants do not carry verified subject clearances, so they
271        // can never authorize caller-selected object labels. A clearance-aware
272        // authorizer must replace this bootstrap seam before staging is enabled.
273        if request.requested_label.is_some() {
274            warn!(
275                subject = %caller,
276                kind = ?request.kind,
277                address = request.address,
278                operation = request.operation,
279                "CAS bootstrap grant: deny label declaration (no verified clearance)"
280            );
281            return Err(MountError::PermissionDenied(format!(
282                "CAS {} {:?} {} denied for {}: bootstrap authorizer has no verified clearance",
283                request.operation, request.kind, request.address, caller
284            )));
285        }
286
287        for grant in &self.grants {
288            if grant.subject.accepts(caller)
289                && grant.kinds.contains(&request.kind)
290                && grant.operations.contains(&request.operation)
291            {
292                debug!(
293                    subject = %caller,
294                    grant = grant.name,
295                    kind = ?request.kind,
296                    address = request.address,
297                    operation = request.operation,
298                    "CAS bootstrap grant: allow"
299                );
300                return Ok(());
301            }
302        }
303        warn!(
304            subject = %caller,
305            kind = ?request.kind,
306            address = request.address,
307            operation = request.operation,
308            "CAS bootstrap grant: deny (no matching grant)"
309        );
310        Err(MountError::PermissionDenied(format!(
311            "CAS {} {:?} {} denied for {}: no matching bootstrap grant (#1094)",
312            request.operation, request.kind, request.address, caller
313        )))
314    }
315}
316
317/// Quota + lattice configuration for write-then-seal staging (#814).
318///
319/// Staging buffers are per-Subject and in-memory. Both quotas are hard floors:
320/// a `Twrite` that would exceed either is rejected (the caller must commit or
321/// abort to free the budget). [`StagingConfig::default`] is permissive enough
322/// for ordinary model/adaptor ingest; production wiring (#1064/#1066 saga)
323/// shrinks these from operator policy.
324#[derive(Clone)]
325pub struct StagingConfig {
326    /// Max bytes a single staging slot may buffer.
327    pub slot_quota_bytes: usize,
328    /// Max total bytes across all of a subject's open (unsealed) slots.
329    pub subject_quota_bytes: usize,
330    /// Optional lattice for resolving compartment names in `label` ctl commands.
331    /// When `None`, only level+assurance labels (no compartments) are accepted.
332    pub lattice: Option<Arc<Lattice>>,
333}
334
335impl std::fmt::Debug for StagingConfig {
336    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337        f.debug_struct("StagingConfig")
338            .field("slot_quota_bytes", &self.slot_quota_bytes)
339            .field("subject_quota_bytes", &self.subject_quota_bytes)
340            .field("lattice", &self.lattice.is_some())
341            .finish()
342    }
343}
344
345impl Default for StagingConfig {
346    fn default() -> Self {
347        Self {
348            slot_quota_bytes: DEFAULT_STAGING_SLOT_QUOTA,
349            subject_quota_bytes: DEFAULT_STAGING_SUBJECT_QUOTA,
350            lattice: None,
351        }
352    }
353}
354
355// ─────────────────────────────────────────────────────────────────────────────
356// Staging slot + registry
357// ─────────────────────────────────────────────────────────────────────────────
358
359/// State machine for a staging slot. Stored as an atomic so the seal path can
360/// CAS without holding a mutex across the async substrate `put`.
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362#[repr(u8)]
363enum SlotState {
364    /// Accepting writes; not yet sealed.
365    Open = 0,
366    /// Seal in flight: a commit won the CAS and is mid-`put`. Concurrent
367    /// commits/aborts/writes must reject.
368    Sealing = 1,
369    /// Sealed: bytes are in the substrate, `result` holds the CID.
370    Sealed = 2,
371    /// Voided (explicit abort, cluck-without-commit, or seal failure): bytes
372    /// discarded. Terminal.
373    Voided = 3,
374}
375
376impl SlotState {
377    #[inline]
378    const fn from_u8(v: u8) -> Self {
379        match v {
380            0 => Self::Open,
381            1 => Self::Sealing,
382            2 => Self::Sealed,
383            _ => Self::Voided,
384        }
385    }
386}
387
388/// Result of a seal, stashed for ctl readback (D-A: commit + CID readback).
389type SealResult = Result<String, String>;
390
391/// One in-flight write-then-seal ingest.
392struct StagingSlot {
393    owner: Subject,
394    state: AtomicU8,
395    buffer: Mutex<Vec<u8>>,
396    /// Running LUB of caller-declared labels plus how many were declared.
397    /// Folded incrementally (join is associative/commutative) so repeated
398    /// `label` commands stay O(1) memory — declared labels must not bypass the
399    /// byte quotas.
400    declared_labels: Mutex<Option<(SecurityLabel, usize)>>,
401    /// Signalled when a seal leaves `Sealing` (→ Sealed or Voided) so
402    /// concurrent commits can suspend instead of spinning.
403    seal_done: Notify,
404    /// Set once the seal completes (Ok) or fails (Err). `Ok(cid)` after a
405    /// successful commit; `Err(message)` after a seal failure that voided the
406    /// slot. Read via ctl.
407    result: Mutex<Option<SealResult>>,
408    /// Outstanding fids (root/data/ctl) referencing this slot. The last cluck
409    /// voids an Open slot and reaps the entry.
410    outstanding: AtomicU64,
411    slot_quota_bytes: usize,
412}
413
414impl StagingSlot {
415    fn new(owner: Subject, slot_quota_bytes: usize) -> Self {
416        Self {
417            owner,
418            state: AtomicU8::new(SlotState::Open as u8),
419            buffer: Mutex::new(Vec::new()),
420            declared_labels: Mutex::new(None),
421            seal_done: Notify::new(),
422            result: Mutex::new(None),
423            outstanding: AtomicU64::new(0),
424            slot_quota_bytes,
425        }
426    }
427
428    #[inline]
429    fn state(&self) -> SlotState {
430        SlotState::from_u8(self.state.load(Ordering::Acquire))
431    }
432
433    /// Buffered byte count (the staged payload length so far).
434    fn len(&self) -> usize {
435        self.buffer.lock().len()
436    }
437
438    /// Fold a caller-declared object label into the running LUB (joined at
439    /// seal time). Rejected once the slot leaves `Open`: the state check runs
440    /// under the label lock, and the seal reads the join under the same lock
441    /// only after CAS'ing to `Sealing`, so a label accepted here is always
442    /// visible to the seal.
443    fn declare_label(&self, label: SecurityLabel) -> Result<(), MountError> {
444        let mut declared = self.declared_labels.lock();
445        if self.state() != SlotState::Open {
446            return Err(MountError::InvalidArgument(
447                "cannot declare labels on a slot that is no longer open".into(),
448            ));
449        }
450        *declared = Some(match *declared {
451            None => (label, 1),
452            Some((current, n)) => (ifc_join(&[current, label]), n.saturating_add(1)),
453        });
454        Ok(())
455    }
456
457    /// Count of labels declared so far (for ctl status).
458    fn label_count(&self) -> usize {
459        self.declared_labels.lock().map_or(0, |(_, n)| n)
460    }
461
462    /// The IFC-joined object label to plumb into the substrate at seal. `None`
463    /// is valid only while staging; the seal boundary rejects it before bytes
464    /// are handed to CAS.
465    fn joined_label(&self) -> Option<SecurityLabel> {
466        self.declared_labels.lock().map(|(label, _)| label)
467    }
468}
469
470struct StagingRegistry {
471    slots: Mutex<HashMap<String, Arc<StagingSlot>>>,
472    /// Per-subject total open-staged bytes (for the aggregate quota).
473    subject_bytes: Mutex<HashMap<String, u64>>,
474    next_id: AtomicU64,
475}
476
477impl StagingRegistry {
478    fn new() -> Self {
479        Self {
480            slots: Mutex::new(HashMap::new()),
481            subject_bytes: Mutex::new(HashMap::new()),
482            next_id: AtomicU64::new(1),
483        }
484    }
485
486    fn mint(&self, owner: &Subject, slot_quota_bytes: usize) -> String {
487        let id = self.next_id.fetch_add(1, Ordering::Relaxed).to_string();
488        let slot = Arc::new(StagingSlot::new(owner.clone(), slot_quota_bytes));
489        // The create fid counts as one outstanding reference.
490        slot.outstanding.store(1, Ordering::Release);
491        self.slots.lock().insert(id.clone(), slot);
492        id
493    }
494
495    fn get(&self, id: &str) -> Option<Arc<StagingSlot>> {
496        self.slots.lock().get(id).cloned()
497    }
498
499    fn list_for(&self, owner: &Subject) -> Vec<String> {
500        let slots = self.slots.lock();
501        let mut ids: Vec<String> = slots
502            .iter()
503            .filter(|(_, s)| &s.owner == owner)
504            .map(|(id, _)| id.clone())
505            .collect();
506        ids.sort();
507        ids
508    }
509
510    /// Increment a slot's outstanding-fid count (a new walk/create referencing it).
511    fn inc_outstanding(&self, slot: &Arc<StagingSlot>) {
512        slot.outstanding.fetch_add(1, Ordering::AcqRel);
513    }
514
515    /// Decrement outstanding fids; on the last cluck, void an Open slot (bytes
516    /// discarded — D-A "abort = cluck-without-commit") and reap it. Sealed
517    /// slots are also reaped once unread (the content now lives in the
518    /// substrate under its CID).
519    fn cluck(&self, id: &str, slot: &Arc<StagingSlot>) {
520        if slot.outstanding.fetch_sub(1, Ordering::AcqRel) != 1 {
521            return;
522        }
523        // Last reference gone. CAS Open→Voided so an in-flight seal (Sealing)
524        // is never clobbered; the byte count is read under the buffer lock
525        // *after* winning the CAS so it pairs exactly with what was reserved.
526        if slot
527            .state
528            .compare_exchange(
529                SlotState::Open as u8,
530                SlotState::Voided as u8,
531                Ordering::AcqRel,
532                Ordering::Acquire,
533            )
534            .is_ok()
535        {
536            // Cluck-without-commit → discard.
537            let dropped = slot.buffer.lock().len() as u64;
538            self.adjust_subject(&slot.owner, -(dropped as i64));
539        }
540        self.slots.lock().remove(id);
541    }
542
543    fn adjust_subject(&self, owner: &Subject, delta_bytes: i64) {
544        let key = owner_key(owner);
545        let mut map = self.subject_bytes.lock();
546        // `get_mut` returns a short-lived borrow whose lifetime ends at the end
547        // of this statement, so the subsequent `remove` on a zero total is
548        // legal (no outstanding mutable borrow of `map`).
549        let remaining = match map.get_mut(&key) {
550            Some(v) => {
551                if delta_bytes >= 0 {
552                    *v = v.saturating_add(delta_bytes as u64);
553                } else {
554                    *v = v.saturating_sub((-delta_bytes) as u64);
555                }
556                *v
557            }
558            None => {
559                if delta_bytes > 0 {
560                    map.insert(key.clone(), delta_bytes as u64);
561                    delta_bytes as u64
562                } else {
563                    0
564                }
565            }
566        };
567        if remaining == 0 {
568            map.remove(&key);
569        }
570    }
571
572    /// Atomically check-and-reserve `growth` bytes of aggregate staging budget
573    /// under a single `subject_bytes` lock, so two concurrent writes cannot
574    /// both observe the same usage and overshoot the quota. Returns the
575    /// current usage on rejection.
576    fn try_reserve(&self, owner: &Subject, growth: u64, limit: u64) -> Result<(), u64> {
577        let key = owner_key(owner);
578        let mut map = self.subject_bytes.lock();
579        let current = map.get(&key).copied().unwrap_or(0);
580        let new_total = current.saturating_add(growth);
581        if new_total > limit {
582            return Err(current);
583        }
584        if new_total > 0 {
585            map.insert(key, new_total);
586        }
587        Ok(())
588    }
589
590    /// Current aggregate usage for a subject (test observability; production
591    /// paths reserve via [`Self::try_reserve`]).
592    #[cfg(test)]
593    fn subject_usage(&self, owner: &Subject) -> u64 {
594        self.subject_bytes
595            .lock()
596            .get(&owner_key(owner))
597            .copied()
598            .unwrap_or(0)
599    }
600}
601
602fn owner_key(owner: &Subject) -> String {
603    // Subjects validate to a safe charset (or are federated URLs validated at
604    // JWT decode); either way this is a hash-map key, not a path component.
605    owner.to_string()
606}
607
608// ─────────────────────────────────────────────────────────────────────────────
609// CasMount
610// ─────────────────────────────────────────────────────────────────────────────
611
612/// CAS as a namespace mount.
613///
614/// Relative layout:
615/// - `obj/{cid-or-legacy-merkle}` — full-file reconstruction.
616/// - `xorb/{hash}` — raw xorb compatibility read.
617/// - `stage/` — write-then-seal ingest (#814):
618///   - `create stage/new` → `stage/<id>/` (per-Subject, quota'd).
619///   - `stage/<id>/data` — bulk `Twrite`-at-offset target.
620///   - `stage/<id>/ctl` — `commit` / `abort` / `label …`; read returns status
621///     incl. the sealed CID.
622#[derive(Clone)]
623pub struct CasMount {
624    substrate: CasSubstrate,
625    domain: DedupDomain,
626    verified_tenant: Option<String>,
627    authorizer: Arc<dyn CasMountAuthorizer>,
628    staging: Arc<StagingRegistry>,
629    staging_cfg: StagingConfig,
630}
631
632impl std::fmt::Debug for CasMount {
633    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
634        f.debug_struct("CasMount")
635            .field("domain", &self.domain)
636            .field("staging_cfg", &self.staging_cfg)
637            .finish_non_exhaustive()
638    }
639}
640
641impl CasMount {
642    /// Construct a fail-closed CAS mount over the given substrate/domain with
643    /// default staging quotas.
644    pub fn new(substrate: CasSubstrate, domain: DedupDomain) -> Self {
645        Self::with_authorizer(substrate, domain, DenyAllCasAuthorizer)
646    }
647
648    /// Construct a fail-closed CAS mount over the default local dedup domain.
649    pub fn local_default(substrate: CasSubstrate) -> Self {
650        Self::new(substrate, DedupDomain::local_default())
651    }
652
653    /// Construct a CAS mount with an explicit authorizer and default staging.
654    pub fn with_authorizer<A>(substrate: CasSubstrate, domain: DedupDomain, authorizer: A) -> Self
655    where
656        A: CasMountAuthorizer + 'static,
657    {
658        Self::with_authorizer_and_staging(substrate, domain, authorizer, StagingConfig::default())
659    }
660
661    /// Construct a CAS mount with an already shared authorizer.
662    ///
663    /// Service state uses this form so the installed policy object is explicit
664    /// and injectable without wrapping an `Arc` inside another `Arc`.
665    pub fn with_shared_authorizer(
666        substrate: CasSubstrate,
667        domain: DedupDomain,
668        authorizer: Arc<dyn CasMountAuthorizer>,
669    ) -> Self {
670        Self {
671            substrate,
672            domain,
673            verified_tenant: None,
674            authorizer,
675            staging: Arc::new(StagingRegistry::new()),
676            staging_cfg: StagingConfig::default(),
677        }
678    }
679
680    /// Construct a CAS mount with an explicit authorizer and staging config.
681    pub fn with_authorizer_and_staging<A>(
682        substrate: CasSubstrate,
683        domain: DedupDomain,
684        authorizer: A,
685        staging_cfg: StagingConfig,
686    ) -> Self
687    where
688        A: CasMountAuthorizer + 'static,
689    {
690        Self {
691            substrate,
692            domain,
693            verified_tenant: None,
694            authorizer: Arc::new(authorizer),
695            staging: Arc::new(StagingRegistry::new()),
696            staging_cfg,
697        }
698    }
699
700    /// Bind this request-scoped mount to a transport-verified tenant.
701    ///
702    /// Only HTTP/RPC authentication adapters should call this. The value is
703    /// passed to the MAC clearance source and is not used for object routing.
704    pub(crate) fn with_verified_tenant(mut self, verified_tenant: String) -> Self {
705        self.verified_tenant = Some(verified_tenant);
706        self
707    }
708
709    async fn authorize(
710        &self,
711        caller: &Subject,
712        kind: CasMountObjectKind,
713        address: &str,
714        operation: &'static str,
715    ) -> Result<(), MountError> {
716        self.authorizer
717            .authorize(
718                caller,
719                CasMountAuthzRequest {
720                    kind,
721                    address,
722                    domain: &self.domain,
723                    verified_tenant: self.verified_tenant.as_deref(),
724                    operation,
725                    requested_label: None,
726                },
727            )
728            .await
729    }
730
731    async fn authorize_label(
732        &self,
733        caller: &Subject,
734        address: &str,
735        requested_label: &SecurityLabel,
736    ) -> Result<(), MountError> {
737        self.authorizer
738            .authorize(
739                caller,
740                CasMountAuthzRequest {
741                    kind: CasMountObjectKind::Stage,
742                    address,
743                    domain: &self.domain,
744                    verified_tenant: self.verified_tenant.as_deref(),
745                    operation: "stage:label",
746                    requested_label: Some(requested_label),
747                },
748            )
749            .await
750    }
751
752    async fn read_all(
753        &self,
754        kind: CasMountObjectKind,
755        address: &str,
756    ) -> Result<Vec<u8>, MountError> {
757        match kind {
758            CasMountObjectKind::Object => self.substrate.get(&self.domain, address).await,
759            CasMountObjectKind::Xorb => self.substrate.read_xorb(&self.domain, address).await,
760            CasMountObjectKind::Stage => {
761                return Err(MountError::InvalidArgument(
762                    "Stage kind is not a read target".into(),
763                ));
764            }
765        }
766        .map_err(map_cas_error)
767    }
768
769    /// Resolve a staging id to its slot, enforcing Subject ownership. Returns
770    /// `NotFound` (not PermissionDenied) for foreign slots so existence does
771    /// not leak across subjects.
772    fn slot_for(&self, id: &str, caller: &Subject) -> Result<Arc<StagingSlot>, MountError> {
773        let slot = self
774            .staging
775            .get(id)
776            .ok_or_else(|| MountError::NotFound(format!("staging slot {id}")))?;
777        if &slot.owner != caller {
778            return Err(MountError::NotFound(format!("staging slot {id}")));
779        }
780        Ok(slot)
781    }
782
783    /// Run the seal: CAS Open→Sealing, take the buffered bytes, invoke the
784    /// substrate, and record the CID (or void on failure). Idempotent — a
785    /// second commit returns the same CID; concurrent commits serialize via CAS.
786    async fn seal_slot(&self, slot: &Arc<StagingSlot>) -> Result<String, MountError> {
787        // An unlabeled slot is a staging-only state. Reject before taking bytes
788        // or transitioning to Sealing so the caller may label it and retry.
789        if slot.state() == SlotState::Open && slot.joined_label().is_none() {
790            return Err(MountError::PermissionDenied(
791                "cannot seal an unlabeled staging slot; declare a label first".into(),
792            ));
793        }
794
795        loop {
796            match slot.state.compare_exchange(
797                SlotState::Open as u8,
798                SlotState::Sealing as u8,
799                Ordering::AcqRel,
800                Ordering::Acquire,
801            ) {
802                Ok(_) => break, // won the commit race
803                Err(actual) => match SlotState::from_u8(actual) {
804                    SlotState::Sealed => {
805                        // Idempotent commit: hand back the existing CID/error.
806                        return match slot.result.lock().clone() {
807                            Some(Ok(cid)) => Ok(cid),
808                            Some(Err(e)) => Err(MountError::Io(e)),
809                            None => Err(MountError::Io("sealed slot has no CID".into())),
810                        };
811                    }
812                    SlotState::Sealing => {
813                        // Another commit is mid-`put`. Suspend until it leaves
814                        // Sealing (never spin — on a current-thread runtime a
815                        // spin here would starve the in-flight seal). `enable`
816                        // registers the waiter *before* the state re-check so
817                        // a `notify_waiters` between the failed CAS and the
818                        // await cannot be missed.
819                        let notified = slot.seal_done.notified();
820                        tokio::pin!(notified);
821                        notified.as_mut().enable();
822                        if slot.state() == SlotState::Sealing {
823                            notified.await;
824                        }
825                        continue;
826                    }
827                    SlotState::Voided => {
828                        // Surface a concurrent seal failure's message if any.
829                        return match slot.result.lock().clone() {
830                            Some(Err(e)) => Err(MountError::Io(e)),
831                            _ => Err(MountError::InvalidArgument(
832                                "cannot commit a voided staging slot".into(),
833                            )),
834                        };
835                    }
836                    SlotState::Open => continue,
837                },
838            }
839        }
840
841        // Won the CAS. Take the bytes + staging hint label out from under their
842        // locks so we don't hold them across the async substrate put. The hint
843        // is a D1 restrict-only input — the substrate derives the trusted
844        // content-bound label via seal_label(domain, hint) (#1270).
845        let bytes = std::mem::take(&mut *slot.buffer.lock());
846        let joined = match slot.joined_label() {
847            Some(label) => label,
848            None => {
849                // `declare_label` only adds labels and the state transition above
850                // excludes concurrent declarations, so this is unreachable after
851                // the preflight. Preserve fail-closed terminal behavior if that
852                // invariant is ever changed.
853                let msg = "cannot seal an unlabeled staging slot".to_owned();
854                *slot.result.lock() = Some(Err(msg.clone()));
855                slot.state.store(SlotState::Voided as u8, Ordering::Release);
856                slot.seal_done.notify_waiters();
857                self.staging
858                    .adjust_subject(&slot.owner, -(bytes.len() as i64));
859                return Err(MountError::PermissionDenied(msg));
860            }
861        };
862        let put_result = self.substrate.put(&self.domain, &bytes, Some(joined)).await;
863
864        match put_result {
865            Ok(manifest) => {
866                let cid = manifest.cid.clone();
867                *slot.result.lock() = Some(Ok(cid.clone()));
868                slot.state.store(SlotState::Sealed as u8, Ordering::Release);
869                slot.seal_done.notify_waiters();
870                // Bytes have left staging (now durable in the substrate).
871                self.staging
872                    .adjust_subject(&slot.owner, -(bytes.len() as i64));
873                Ok(cid)
874            }
875            Err(err) => {
876                let msg = err.to_string();
877                *slot.result.lock() = Some(Err(msg.clone()));
878                slot.state.store(SlotState::Voided as u8, Ordering::Release);
879                slot.seal_done.notify_waiters();
880                // Failure voids the slot; bytes are discarded.
881                self.staging
882                    .adjust_subject(&slot.owner, -(bytes.len() as i64));
883                Err(map_cas_error(err))
884            }
885        }
886    }
887
888    /// Process one ctl command line. Returns bytes consumed (= line length).
889    async fn ctl_command(
890        &self,
891        id: &str,
892        slot: &Arc<StagingSlot>,
893        line: &str,
894        caller: &Subject,
895    ) -> Result<(), MountError> {
896        let mut tokens = line.split_whitespace();
897        match tokens.next() {
898            None => Ok(()), // blank line
899            Some("commit") => {
900                self.authorize(caller, CasMountObjectKind::Stage, id, "stage:commit")
901                    .await?;
902                self.seal_slot(slot).await.map(|_| ())
903            }
904            Some("abort") => {
905                // CAS Open→Voided so an in-flight seal is never clobbered: a
906                // commit that has already taken the bytes must not have its
907                // Sealed result overwritten by a racing abort.
908                match slot.state.compare_exchange(
909                    SlotState::Open as u8,
910                    SlotState::Voided as u8,
911                    Ordering::AcqRel,
912                    Ordering::Acquire,
913                ) {
914                    Ok(_) => {
915                        let dropped = {
916                            let mut buf = slot.buffer.lock();
917                            let n = buf.len() as u64;
918                            buf.clear();
919                            n
920                        };
921                        self.staging.adjust_subject(&slot.owner, -(dropped as i64));
922                        Ok(())
923                    }
924                    Err(actual) => match SlotState::from_u8(actual) {
925                        SlotState::Sealed => Err(MountError::InvalidArgument(
926                            "cannot abort a sealed staging slot".into(),
927                        )),
928                        SlotState::Sealing => Err(MountError::InvalidArgument(
929                            "cannot abort while a commit is sealing".into(),
930                        )),
931                        // Idempotent: aborting a voided slot is a no-op.
932                        SlotState::Voided => Ok(()),
933                        SlotState::Open => unreachable!("CAS from Open cannot fail with Open"),
934                    },
935                }
936            }
937            Some("label") => {
938                self.declare_label_cmd(id, slot, tokens.collect(), caller)
939                    .await
940            }
941            Some(cmd) => Err(MountError::InvalidArgument(format!(
942                "unknown ctl command: {cmd}"
943            ))),
944        }
945    }
946
947    async fn declare_label_cmd(
948        &self,
949        id: &str,
950        slot: &Arc<StagingSlot>,
951        args: Vec<&str>,
952        caller: &Subject,
953    ) -> Result<(), MountError> {
954        // label <level> <assurance> [compartment...]
955        let mut it = args.into_iter();
956        let level_s = it
957            .next()
958            .ok_or_else(|| MountError::InvalidArgument("label: missing level".into()))?;
959        let assurance_s = it
960            .next()
961            .ok_or_else(|| MountError::InvalidArgument("label: missing assurance".into()))?;
962        let level = parse_level(level_s)
963            .ok_or_else(|| MountError::InvalidArgument(format!("unknown level: {level_s}")))?;
964        let assurance = parse_assurance(assurance_s).ok_or_else(|| {
965            MountError::InvalidArgument(format!("unknown assurance: {assurance_s}"))
966        })?;
967        let comps: Vec<&str> = it.collect();
968        let label = if comps.is_empty() {
969            SecurityLabel::new(level, assurance, CompartmentSet::EMPTY)
970        } else {
971            let lattice = self.staging_cfg.lattice.as_ref().ok_or_else(|| {
972                MountError::InvalidArgument(
973                    "label: compartments require a lattice on the mount".into(),
974                )
975            })?;
976            let comps = comps
977                .into_iter()
978                .map(hyprstream_rpc::auth::mac::Compartment::new)
979                .collect::<Vec<_>>();
980            lattice
981                .label(level, assurance, comps)
982                .map_err(|e| MountError::InvalidArgument(format!("label: {e}")))?
983        };
984        // Authorization sees the fully parsed label and runs before slot
985        // mutation. A rejection therefore cannot transition or persist label
986        // state, and a clearance-aware authorizer can enforce dominance.
987        self.authorize_label(caller, id, &label).await?;
988        slot.declare_label(label)
989    }
990
991    /// Render the ctl status text.
992    fn ctl_status(&self, slot: &Arc<StagingSlot>) -> String {
993        match slot.state() {
994            SlotState::Open => {
995                let labels = slot.label_count();
996                format!(
997                    "state=staging bytes={} labels={} quota={}\n",
998                    slot.len(),
999                    labels,
1000                    slot.slot_quota_bytes,
1001                )
1002            }
1003            SlotState::Sealing => "state=sealing\n".to_owned(),
1004            SlotState::Sealed => match slot.result.lock().clone() {
1005                Some(Ok(cid)) => format!("state=sealed cid={cid}\n"),
1006                Some(Err(e)) => format!("state=sealed error={e}\n"),
1007                None => "state=sealed\n".to_owned(),
1008            },
1009            SlotState::Voided => match slot.result.lock().clone() {
1010                Some(Err(e)) => format!("state=voided error={e}\n"),
1011                _ => "state=voided\n".to_owned(),
1012            },
1013        }
1014    }
1015}
1016
1017#[derive(Debug, Clone, PartialEq, Eq)]
1018enum CasFid {
1019    Root,
1020    ObjDir,
1021    XorbDir,
1022    StageDir,
1023    File {
1024        kind: CasMountObjectKind,
1025        address: String,
1026        opened: bool,
1027    },
1028    StageRoot {
1029        id: String,
1030        opened: bool,
1031    },
1032    /// `mode` is `Some(open-mode & 0x03)` once opened; reads require
1033    /// OREAD/ORDWR and writes OWRITE/ORDWR — a fid opened write-only must not
1034    /// read the staged bytes and vice versa.
1035    StageData {
1036        id: String,
1037        mode: Option<u8>,
1038    },
1039    StageCtl {
1040        id: String,
1041        mode: Option<u8>,
1042    },
1043}
1044
1045/// Enforce that an opened stage fid's mode permits reading.
1046fn check_readable(mode: Option<u8>) -> Result<(), MountError> {
1047    match mode {
1048        None => Err(MountError::InvalidArgument("fid is not open".into())),
1049        Some(OREAD) | Some(ORDWR) => Ok(()),
1050        Some(_) => Err(MountError::PermissionDenied(
1051            "fid is not open for reading".into(),
1052        )),
1053    }
1054}
1055
1056/// Enforce that an opened stage fid's mode permits writing.
1057fn check_writable(mode: Option<u8>) -> Result<(), MountError> {
1058    match mode {
1059        None => Err(MountError::InvalidArgument("fid is not open".into())),
1060        Some(OWRITE) | Some(ORDWR) => Ok(()),
1061        Some(_) => Err(MountError::PermissionDenied(
1062            "fid is not open for writing".into(),
1063        )),
1064    }
1065}
1066
1067impl CasFid {
1068    /// If this fid pins a staging slot, return its id.
1069    fn slot_id(&self) -> Option<&str> {
1070        match self {
1071            CasFid::StageRoot { id, .. }
1072            | CasFid::StageData { id, .. }
1073            | CasFid::StageCtl { id, .. } => Some(id),
1074            _ => None,
1075        }
1076    }
1077}
1078
1079#[async_trait]
1080impl Mount for CasMount {
1081    async fn walk(&self, components: &[&str], caller: &Subject) -> Result<Fid, MountError> {
1082        let fid = match components {
1083            [] => CasFid::Root,
1084            ["obj"] => CasFid::ObjDir,
1085            ["xorb"] => CasFid::XorbDir,
1086            ["stage"] => CasFid::StageDir,
1087            ["obj", address] if !address.is_empty() => CasFid::File {
1088                kind: CasMountObjectKind::Object,
1089                address: (*address).to_owned(),
1090                opened: false,
1091            },
1092            ["xorb", hash] if !hash.is_empty() => CasFid::File {
1093                kind: CasMountObjectKind::Xorb,
1094                address: (*hash).to_owned(),
1095                opened: false,
1096            },
1097            ["stage", id] if !id.is_empty() => {
1098                let slot = self.slot_for(id, caller)?;
1099                self.staging.inc_outstanding(&slot);
1100                CasFid::StageRoot {
1101                    id: (*id).to_owned(),
1102                    opened: false,
1103                }
1104            }
1105            ["stage", id, "data"] if !id.is_empty() => {
1106                let slot = self.slot_for(id, caller)?;
1107                self.staging.inc_outstanding(&slot);
1108                CasFid::StageData {
1109                    id: (*id).to_owned(),
1110                    mode: None,
1111                }
1112            }
1113            ["stage", id, "ctl"] if !id.is_empty() => {
1114                let slot = self.slot_for(id, caller)?;
1115                self.staging.inc_outstanding(&slot);
1116                CasFid::StageCtl {
1117                    id: (*id).to_owned(),
1118                    mode: None,
1119                }
1120            }
1121            _ => return Err(MountError::NotFound(components.join("/"))),
1122        };
1123        Ok(Fid::new(fid))
1124    }
1125
1126    async fn open(&self, fid: &mut Fid, mode: u8, caller: &Subject) -> Result<(), MountError> {
1127        let inner = fid
1128            .downcast_mut::<CasFid>()
1129            .ok_or_else(|| MountError::InvalidArgument("wrong fid type for CasMount".into()))?;
1130
1131        match inner {
1132            CasFid::Root | CasFid::ObjDir | CasFid::XorbDir | CasFid::StageDir => Ok(()),
1133            CasFid::File {
1134                kind,
1135                address,
1136                opened,
1137            } => {
1138                if mode & 0x03 != OREAD {
1139                    return Err(MountError::PermissionDenied(
1140                        "CAS obj/xorb files are read-only".into(),
1141                    ));
1142                }
1143                self.authorize(caller, *kind, address, "open").await?;
1144                *opened = true;
1145                Ok(())
1146            }
1147            CasFid::StageRoot { opened, .. } => {
1148                *opened = true;
1149                Ok(())
1150            }
1151            CasFid::StageData { id, mode: m } | CasFid::StageCtl { id, mode: m } => {
1152                let _slot = self.slot_for(id, caller)?;
1153                *m = Some(mode & 0x03);
1154                Ok(())
1155            }
1156        }
1157    }
1158
1159    async fn read(
1160        &self,
1161        fid: &Fid,
1162        offset: u64,
1163        count: u32,
1164        caller: &Subject,
1165    ) -> Result<Vec<u8>, MountError> {
1166        let inner = fid
1167            .downcast_ref::<CasFid>()
1168            .ok_or_else(|| MountError::InvalidArgument("wrong fid type for CasMount".into()))?;
1169        match inner {
1170            CasFid::File {
1171                kind,
1172                address,
1173                opened,
1174            } => {
1175                if !opened {
1176                    return Err(MountError::InvalidArgument("fid is not open".into()));
1177                }
1178                self.authorize(caller, *kind, address, "read").await?;
1179                let bytes = self.read_all(*kind, address).await?;
1180                Ok(slice_bytes(&bytes, offset, count))
1181            }
1182            CasFid::StageData { id, mode } => {
1183                check_readable(*mode)?;
1184                let slot = self.slot_for(id, caller)?;
1185                // Slice under the lock — never clone the whole staged buffer
1186                // (up to the slot quota) for a small positioned read.
1187                let bytes = slot.buffer.lock();
1188                Ok(slice_bytes(&bytes, offset, count))
1189            }
1190            CasFid::StageCtl { id, mode } => {
1191                check_readable(*mode)?;
1192                let slot = self.slot_for(id, caller)?;
1193                let status = self.ctl_status(&slot);
1194                Ok(slice_bytes(status.as_bytes(), offset, count))
1195            }
1196            CasFid::Root
1197            | CasFid::ObjDir
1198            | CasFid::XorbDir
1199            | CasFid::StageDir
1200            | CasFid::StageRoot { .. } => Err(MountError::IsDirectory(
1201                "cannot read a CAS directory as a file".into(),
1202            )),
1203        }
1204    }
1205
1206    async fn write(
1207        &self,
1208        fid: &Fid,
1209        offset: u64,
1210        data: &[u8],
1211        caller: &Subject,
1212    ) -> Result<u32, MountError> {
1213        let inner = fid
1214            .downcast_ref::<CasFid>()
1215            .ok_or_else(|| MountError::InvalidArgument("wrong fid type for CasMount".into()))?;
1216        match inner {
1217            CasFid::StageData { id, mode } => {
1218                check_writable(*mode)?;
1219                let slot = self.slot_for(id, caller)?;
1220                self.authorize(caller, CasMountObjectKind::Stage, id, "stage:write")
1221                    .await?;
1222
1223                let off = usize::try_from(offset)
1224                    .map_err(|_| MountError::InvalidArgument("write offset overflow".into()))?;
1225                let end = off
1226                    .checked_add(data.len())
1227                    .ok_or_else(|| MountError::InvalidArgument("write length overflow".into()))?;
1228
1229                // Per-slot quota.
1230                if end > slot.slot_quota_bytes {
1231                    return Err(MountError::PermissionDenied(format!(
1232                        "staging slot quota exceeded: {end} > {}",
1233                        slot.slot_quota_bytes
1234                    )));
1235                }
1236
1237                let mut buf = slot.buffer.lock();
1238                // Check the state *under the buffer lock*: the seal takes the
1239                // buffer under this lock only after CAS'ing to Sealing, and
1240                // abort/cluck clear it under this lock only after CAS'ing to
1241                // Voided — so Open observed here means these bytes are either
1242                // included in the seal or released with the void, never
1243                // written to a buffer that was already taken.
1244                if slot.state() != SlotState::Open {
1245                    return Err(MountError::InvalidArgument(format!(
1246                        "staging slot {id} is not open for writes (state={:?})",
1247                        slot.state()
1248                    )));
1249                }
1250
1251                // Per-Subject aggregate quota: atomically check-and-reserve
1252                // the growth delta so concurrent writes can't both pass the
1253                // check and overshoot.
1254                let prev_len = buf.len();
1255                let growth = end.saturating_sub(prev_len);
1256                if growth > 0 {
1257                    if let Err(usage) = self.staging.try_reserve(
1258                        caller,
1259                        growth as u64,
1260                        self.staging_cfg.subject_quota_bytes as u64,
1261                    ) {
1262                        return Err(MountError::PermissionDenied(format!(
1263                            "subject staging quota exceeded: {} + {growth} > {}",
1264                            usage, self.staging_cfg.subject_quota_bytes
1265                        )));
1266                    }
1267                }
1268
1269                if end > buf.len() {
1270                    buf.resize(off, 0); // sparse gap zero-fill
1271                    buf.extend_from_slice(data);
1272                } else {
1273                    buf[off..end].copy_from_slice(data);
1274                }
1275                drop(buf);
1276                Ok(data.len() as u32)
1277            }
1278            CasFid::StageCtl { id, mode } => {
1279                check_writable(*mode)?;
1280                let slot = self.slot_for(id, caller)?;
1281                let line = std::str::from_utf8(data)
1282                    .map_err(|_| MountError::InvalidArgument("ctl command is not UTF-8".into()))?;
1283                // Accept a single command per write (trailing newline trimmed).
1284                self.ctl_command(id, &slot, line.trim_end_matches(['\n', '\r']), caller)
1285                    .await?;
1286                Ok(data.len() as u32)
1287            }
1288            // Read-only object/xorb files and directories reject writes.
1289            _ => Err(MountError::NotSupported(
1290                "CAS mount writes go through stage/<id>/{data,ctl} (#814)".into(),
1291            )),
1292        }
1293    }
1294
1295    async fn create(
1296        &self,
1297        fid: &mut Fid,
1298        _name: &str,
1299        _perm: u32,
1300        mode: u8,
1301        caller: &Subject,
1302    ) -> Result<Stat, MountError> {
1303        // `create` is honored on the mount root and on `stage/`. The caller's
1304        // name (conventionally "new") is ignored: the server mints a fresh
1305        // staging id so two concurrent ingests never collide.
1306        let inner = fid
1307            .downcast_mut::<CasFid>()
1308            .ok_or_else(|| MountError::InvalidArgument("wrong fid type for CasMount".into()))?;
1309        let is_stage_parent = matches!(inner, CasFid::Root | CasFid::StageDir);
1310        if !is_stage_parent {
1311            return Err(MountError::NotSupported(
1312                "create only supported on the CAS root or stage/ (#814)".into(),
1313            ));
1314        }
1315
1316        self.authorize(caller, CasMountObjectKind::Stage, "new", "stage:create")
1317            .await?;
1318
1319        let id = self.staging.mint(caller, self.staging_cfg.slot_quota_bytes);
1320        *inner = CasFid::StageRoot {
1321            id: id.clone(),
1322            opened: true,
1323        };
1324        // `mode` is the open mode the caller wants on the new staging dir; the
1325        // dir itself is walked into for data/ctl, so we don't enforce it here
1326        // beyond accepting the create. Mask off truncate/close bits.
1327        let _ = mode & !(OTRUNC);
1328        Ok(staging_dir_stat(&id))
1329    }
1330
1331    async fn readdir(&self, fid: &Fid, caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
1332        let inner = fid
1333            .downcast_ref::<CasFid>()
1334            .ok_or_else(|| MountError::InvalidArgument("wrong fid type for CasMount".into()))?;
1335        match inner {
1336            CasFid::Root => Ok(vec![
1337                dir_entry("obj"),
1338                dir_entry("xorb"),
1339                dir_entry("stage"),
1340            ]),
1341            CasFid::ObjDir | CasFid::XorbDir => Ok(Vec::new()),
1342            CasFid::StageDir => {
1343                let ids = self.staging.list_for(caller);
1344                Ok(ids
1345                    .into_iter()
1346                    .map(|id| DirEntry {
1347                        name: id.clone(),
1348                        is_dir: true,
1349                        size: 0,
1350                        stat: Some(staging_dir_stat(&id)),
1351                    })
1352                    .collect())
1353            }
1354            CasFid::StageRoot { id, .. } => Ok(vec![
1355                DirEntry {
1356                    name: "data".to_owned(),
1357                    is_dir: false,
1358                    size: 0,
1359                    // The qid path must include the staging id so 9P clients do
1360                    // not alias `stage/<a>/data` with `stage/<b>/data` in a
1361                    // qid-keyed cache (qid is 9P's file identity).
1362                    stat: Some(staging_file_stat(id, "data", 0)),
1363                },
1364                DirEntry {
1365                    name: "ctl".to_owned(),
1366                    is_dir: false,
1367                    size: 0,
1368                    stat: Some(staging_file_stat(id, "ctl", 0)),
1369                },
1370            ]),
1371            other => Err(MountError::NotDirectory(
1372                other.slot_id().unwrap_or("file").to_owned(),
1373            )),
1374        }
1375    }
1376
1377    async fn stat(&self, fid: &Fid, caller: &Subject) -> Result<Stat, MountError> {
1378        let inner = fid
1379            .downcast_ref::<CasFid>()
1380            .ok_or_else(|| MountError::InvalidArgument("wrong fid type for CasMount".into()))?;
1381        match inner {
1382            CasFid::Root => Ok(dir_stat("", 0)),
1383            CasFid::ObjDir => Ok(dir_stat("obj", 1)),
1384            CasFid::XorbDir => Ok(dir_stat("xorb", 2)),
1385            CasFid::StageDir => Ok(dir_stat("stage", 3)),
1386            CasFid::File { kind, address, .. } => {
1387                self.authorize(caller, *kind, address, "stat").await?;
1388                let len = self.read_all(*kind, address).await?.len() as u64;
1389                Ok(file_stat(address, len))
1390            }
1391            CasFid::StageRoot { id, .. } => Ok(staging_dir_stat(id)),
1392            CasFid::StageData { id, .. } => {
1393                let slot = self.slot_for(id, caller)?;
1394                Ok(staging_file_stat(id, "data", slot.len() as u64))
1395            }
1396            CasFid::StageCtl { id, .. } => {
1397                let slot = self.slot_for(id, caller)?;
1398                let len = self.ctl_status(&slot).len() as u64;
1399                Ok(staging_file_stat(id, "ctl", len))
1400            }
1401        }
1402    }
1403
1404    async fn clunk(&self, fid: Fid, _caller: &Subject) {
1405        let Ok(inner) = fid.downcast_into::<CasFid>() else {
1406            return;
1407        };
1408        if let Some(id) = inner.slot_id() {
1409            if let Some(slot) = self.staging.get(id) {
1410                self.staging.cluck(id, &slot);
1411            }
1412        }
1413    }
1414}
1415
1416// ─────────────────────────────────────────────────────────────────────────────
1417// Helpers
1418// ─────────────────────────────────────────────────────────────────────────────
1419
1420fn parse_level(s: &str) -> Option<Level> {
1421    match s.to_ascii_lowercase().as_str() {
1422        "public" => Some(Level::Public),
1423        "internal" => Some(Level::Internal),
1424        "confidential" => Some(Level::Confidential),
1425        "secret" => Some(Level::Secret),
1426        _ => None,
1427    }
1428}
1429
1430fn parse_assurance(s: &str) -> Option<Assurance> {
1431    match s.to_ascii_lowercase().as_str() {
1432        "classical" => Some(Assurance::Classical),
1433        "pqhybrid" | "pq_hybrid" | "pq-hybrid" | "hybrid" => Some(Assurance::PqHybrid),
1434        _ => None,
1435    }
1436}
1437
1438fn dir_entry(name: &str) -> DirEntry {
1439    DirEntry {
1440        name: name.to_owned(),
1441        is_dir: true,
1442        size: 0,
1443        stat: Some(dir_stat(name, hash_path(name))),
1444    }
1445}
1446
1447fn dir_stat(name: &str, path: u64) -> Stat {
1448    Stat {
1449        qtype: QTDIR,
1450        version: 1,
1451        path,
1452        size: 0,
1453        name: name.to_owned(),
1454        mtime: 0,
1455    }
1456}
1457
1458fn file_stat(name: &str, size: u64) -> Stat {
1459    Stat {
1460        qtype: QTFILE,
1461        version: 1,
1462        path: hash_path(name),
1463        size,
1464        name: name.to_owned(),
1465        mtime: 0,
1466    }
1467}
1468
1469fn staging_dir_stat(id: &str) -> Stat {
1470    Stat {
1471        qtype: QTDIR,
1472        version: 1,
1473        path: hash_path(&format!("stage/{id}")),
1474        size: 0,
1475        name: id.to_owned(),
1476        mtime: 0,
1477    }
1478}
1479
1480fn staging_file_stat(id: &str, name: &str, size: u64) -> Stat {
1481    Stat {
1482        qtype: QTFILE,
1483        version: 1,
1484        // The qid path includes the staging id so two slots' `data` (or `ctl`)
1485        // files never share a qid — qid is 9P's file identity, and a qid-keyed
1486        // client cache would otherwise alias `stage/<a>/data` with
1487        // `stage/<b>/data`. (Advisory hint only — see the qid-soundness note on
1488        // `hyprstream_vfs::Stat`; authz never keys on this.)
1489        path: hash_path(&format!("stage/{id}/{name}")),
1490        size,
1491        name: name.to_owned(),
1492        mtime: 0,
1493    }
1494}
1495
1496fn slice_bytes(bytes: &[u8], offset: u64, count: u32) -> Vec<u8> {
1497    let start = usize::try_from(offset)
1498        .unwrap_or(usize::MAX)
1499        .min(bytes.len());
1500    let end = start.saturating_add(count as usize).min(bytes.len());
1501    bytes[start..end].to_vec()
1502}
1503
1504fn map_cas_error(err: CasError) -> MountError {
1505    match err {
1506        CasError::Store(StoreError::NotFound(s)) => MountError::NotFound(s),
1507        CasError::Store(StoreError::InvalidHash(s)) | CasError::Cid(s) | CasError::Hex(s) => {
1508            MountError::InvalidArgument(s)
1509        }
1510        CasError::Manifest(s) => MountError::InvalidArgument(s),
1511        CasError::Store(e) => MountError::Io(e.to_string()),
1512        CasError::UnsupportedIngestAlgorithm(algo) => {
1513            MountError::InvalidArgument(format!("unsupported CAS algorithm: {algo:?}"))
1514        }
1515    }
1516}
1517
1518fn hash_path(path: &str) -> u64 {
1519    let mut h: u64 = 0xcbf29ce484222325;
1520    for b in path.as_bytes() {
1521        h ^= u64::from(*b);
1522        h = h.wrapping_mul(0x100000001b3);
1523    }
1524    h
1525}
1526
1527#[cfg(test)]
1528#[allow(clippy::unwrap_used, clippy::expect_used)]
1529mod tests {
1530    use super::*;
1531    use hyprstream_vfs::{ORDWR, OWRITE};
1532    use parking_lot::Mutex;
1533
1534    fn label() -> SecurityLabel {
1535        SecurityLabel::new(Level::Internal, Assurance::Classical, CompartmentSet::EMPTY)
1536    }
1537
1538    async fn declare_test_label(mount: &CasMount, ctl: &Fid, caller: &Subject) {
1539        mount
1540            .write(ctl, 0, b"label internal classical\n", caller)
1541            .await
1542            .unwrap();
1543    }
1544
1545    #[derive(Default)]
1546    struct RecordingAuthorizer {
1547        deny: bool,
1548        deny_labels: bool,
1549        calls: Mutex<Vec<(String, CasMountObjectKind, String, &'static str)>>,
1550        label_calls: Mutex<Vec<(String, String, SecurityLabel)>>,
1551    }
1552
1553    impl RecordingAuthorizer {
1554        fn calls(&self) -> Vec<(String, CasMountObjectKind, String, &'static str)> {
1555            self.calls.lock().clone()
1556        }
1557
1558        fn label_calls(&self) -> Vec<(String, String, SecurityLabel)> {
1559            self.label_calls.lock().clone()
1560        }
1561    }
1562
1563    #[async_trait::async_trait]
1564    impl CasMountAuthorizer for std::sync::Arc<RecordingAuthorizer> {
1565        async fn authorize(
1566            &self,
1567            caller: &Subject,
1568            request: CasMountAuthzRequest<'_>,
1569        ) -> Result<(), MountError> {
1570            self.calls.lock().push((
1571                caller.to_string(),
1572                request.kind,
1573                request.address.to_owned(),
1574                request.operation,
1575            ));
1576            if let Some(label) = request.requested_label {
1577                self.label_calls.lock().push((
1578                    caller.to_string(),
1579                    request.address.to_owned(),
1580                    *label,
1581                ));
1582            }
1583            if self.deny || (self.deny_labels && request.requested_label.is_some()) {
1584                Err(MountError::PermissionDenied("denied by test".into()))
1585            } else {
1586                Ok(())
1587            }
1588        }
1589    }
1590
1591    // ── read-side (existing) ───────────────────────────────────────────────
1592
1593    #[tokio::test]
1594    async fn object_read_requires_authorizer_and_slices() {
1595        let dir = tempfile::tempdir().unwrap();
1596        let substrate = CasSubstrate::new(dir.path());
1597        let domain = DedupDomain::local_default();
1598        let manifest = substrate
1599            .put(&domain, b"hello-cas-mount", Some(label()))
1600            .await
1601            .unwrap();
1602        let authz = std::sync::Arc::new(RecordingAuthorizer::default());
1603        let mount = CasMount::with_authorizer(substrate, domain, authz.clone());
1604        let caller = Subject::new("alice");
1605
1606        let mut fid = mount.walk(&["obj", &manifest.cid], &caller).await.unwrap();
1607        mount.open(&mut fid, OREAD, &caller).await.unwrap();
1608        let out = mount.read(&fid, 6, 3, &caller).await.unwrap();
1609
1610        assert_eq!(out, b"cas");
1611        assert_eq!(
1612            authz.calls(),
1613            vec![
1614                (
1615                    "alice".to_owned(),
1616                    CasMountObjectKind::Object,
1617                    manifest.cid.clone(),
1618                    "open"
1619                ),
1620                (
1621                    "alice".to_owned(),
1622                    CasMountObjectKind::Object,
1623                    manifest.cid,
1624                    "read"
1625                ),
1626            ]
1627        );
1628    }
1629
1630    #[tokio::test]
1631    async fn default_authorizer_denies_even_when_hash_exists() {
1632        let dir = tempfile::tempdir().unwrap();
1633        let substrate = CasSubstrate::new(dir.path());
1634        let domain = DedupDomain::local_default();
1635        let manifest = substrate
1636            .put(&domain, b"secret bytes", Some(label()))
1637            .await
1638            .unwrap();
1639        let mount = CasMount::new(substrate, domain);
1640        let caller = Subject::new("bob");
1641
1642        let mut fid = mount
1643            .walk(&["obj", &manifest.merkle], &caller)
1644            .await
1645            .unwrap();
1646        let err = mount.open(&mut fid, OREAD, &caller).await.unwrap_err();
1647        assert!(matches!(err, MountError::PermissionDenied(_)));
1648    }
1649
1650    #[tokio::test]
1651    async fn xorb_read_uses_xorb_authorization_class() {
1652        let dir = tempfile::tempdir().unwrap();
1653        let substrate = CasSubstrate::new(dir.path());
1654        let domain = DedupDomain::local_default();
1655        let manifest = substrate
1656            .put(&domain, b"xorb-backed-payload", Some(label()))
1657            .await
1658            .unwrap();
1659        let xorb = manifest.xorb_hashes.first().expect("xorb hash").clone();
1660        let authz = std::sync::Arc::new(RecordingAuthorizer::default());
1661        let mount = CasMount::with_authorizer(substrate, domain, authz.clone());
1662        let caller = Subject::new("alice");
1663
1664        let mut fid = mount.walk(&["xorb", &xorb], &caller).await.unwrap();
1665        mount.open(&mut fid, OREAD, &caller).await.unwrap();
1666        let out = mount.read(&fid, 0, 1024, &caller).await.unwrap();
1667
1668        assert!(!out.is_empty());
1669        assert_eq!(authz.calls()[0].1, CasMountObjectKind::Xorb);
1670        assert_eq!(authz.calls()[1].1, CasMountObjectKind::Xorb);
1671    }
1672
1673    #[tokio::test]
1674    async fn root_lists_non_enumerating_cas_dirs() {
1675        let mount = CasMount::with_authorizer(
1676            CasSubstrate::new(tempfile::tempdir().unwrap().path()),
1677            DedupDomain::local_default(),
1678            AllowAllCasAuthorizer,
1679        );
1680        let caller = Subject::new("alice");
1681        let fid = mount.walk(&[], &caller).await.unwrap();
1682        let entries = mount.readdir(&fid, &caller).await.unwrap();
1683        let names: Vec<_> = entries.into_iter().map(|e| e.name).collect();
1684        assert_eq!(names, vec!["obj", "xorb", "stage"]);
1685    }
1686
1687    // ── bootstrap-grant authorizer (#1094) ─────────────────────────────────
1688
1689    /// Build a substrate holding one xorb and return it with the xorb hash.
1690    async fn substrate_with_xorb(bytes: &[u8]) -> (tempfile::TempDir, CasSubstrate, String) {
1691        let dir = tempfile::tempdir().unwrap();
1692        let substrate = CasSubstrate::new(dir.path());
1693        let manifest = substrate
1694            .put(&DedupDomain::local_default(), bytes, Some(label()))
1695            .await
1696            .unwrap();
1697        let xorb = manifest.xorb_hashes.first().expect("xorb hash").clone();
1698        (dir, substrate, xorb)
1699    }
1700
1701    #[tokio::test]
1702    async fn bootstrap_grant_allows_authenticated_xorb_read() {
1703        let (_dir, substrate, xorb) = substrate_with_xorb(b"bootstrap-xorb").await;
1704        let mount = CasMount::with_authorizer(
1705            substrate,
1706            DedupDomain::local_default(),
1707            BootstrapCasAuthorizer::new(),
1708        );
1709        let caller = Subject::new("alice");
1710
1711        let mut fid = mount.walk(&["xorb", &xorb], &caller).await.unwrap();
1712        mount.open(&mut fid, OREAD, &caller).await.unwrap();
1713        let out = mount.read(&fid, 0, 1024, &caller).await.unwrap();
1714
1715        assert!(!out.is_empty());
1716    }
1717
1718    #[tokio::test]
1719    async fn bootstrap_grant_denies_anonymous_xorb_read() {
1720        let (_dir, substrate, xorb) = substrate_with_xorb(b"bootstrap-xorb").await;
1721        let mount = CasMount::with_authorizer(
1722            substrate,
1723            DedupDomain::local_default(),
1724            BootstrapCasAuthorizer::new(),
1725        );
1726        let caller = Subject::anonymous();
1727
1728        let mut fid = mount.walk(&["xorb", &xorb], &caller).await.unwrap();
1729        let err = mount.open(&mut fid, OREAD, &caller).await.unwrap_err();
1730
1731        assert!(matches!(err, MountError::PermissionDenied(_)));
1732    }
1733
1734    #[tokio::test]
1735    async fn bootstrap_grant_denies_obj_reads_and_stage_ops() {
1736        let (_dir, substrate, xorb) = substrate_with_xorb(b"bootstrap-xorb").await;
1737        let manifest = substrate
1738            .put(&DedupDomain::local_default(), b"obj-bytes", Some(label()))
1739            .await
1740            .unwrap();
1741        let mount = CasMount::with_authorizer(
1742            substrate,
1743            DedupDomain::local_default(),
1744            BootstrapCasAuthorizer::new(),
1745        );
1746        let caller = Subject::new("alice");
1747
1748        // obj/* reads are outside the day-one grant.
1749        let mut fid = mount.walk(&["obj", &manifest.cid], &caller).await.unwrap();
1750        let err = mount.open(&mut fid, OREAD, &caller).await.unwrap_err();
1751        assert!(matches!(err, MountError::PermissionDenied(_)));
1752
1753        // stat on a xorb is outside the grant (open + read only).
1754        let fid = mount.walk(&["xorb", &xorb], &caller).await.unwrap();
1755        let err = mount.stat(&fid, &caller).await.unwrap_err();
1756        assert!(matches!(err, MountError::PermissionDenied(_)));
1757
1758        // stage/* ingest is outside the grant.
1759        let mut root = mount.walk(&["stage"], &caller).await.unwrap();
1760        let err = mount
1761            .create(&mut root, "new", 0o600, OWRITE, &caller)
1762            .await
1763            .unwrap_err();
1764        assert!(matches!(err, MountError::PermissionDenied(_)));
1765    }
1766
1767    #[tokio::test]
1768    async fn bootstrap_grant_list_ratchets_to_deny_all() {
1769        // The ratchet terminus: an empty grant list denies even the day-one
1770        // xorb read, equivalent to DenyAllCasAuthorizer.
1771        let authz = BootstrapCasAuthorizer::with_grants(Vec::new());
1772        let domain = DedupDomain::local_default();
1773        let request = CasMountAuthzRequest {
1774            kind: CasMountObjectKind::Xorb,
1775            address: "aa00",
1776            domain: &domain,
1777            verified_tenant: None,
1778            operation: "read",
1779            requested_label: None,
1780        };
1781        let err = authz
1782            .authorize(&Subject::new("alice"), request)
1783            .await
1784            .unwrap_err();
1785        assert!(matches!(err, MountError::PermissionDenied(_)));
1786    }
1787
1788    #[test]
1789    fn bootstrap_day_one_grant_matches_exactly_xorb_open_read() {
1790        let grant = AUTHENTICATED_XORB_READ;
1791        assert_eq!(grant.subject, CasGrantSubject::AnyAuthenticated);
1792        assert_eq!(grant.kinds, &[CasMountObjectKind::Xorb]);
1793        assert_eq!(grant.operations, &["open", "read"]);
1794    }
1795
1796    #[tokio::test]
1797    async fn bootstrap_cannot_grant_labels_without_verified_clearance() {
1798        let authz = BootstrapCasAuthorizer::with_grants(vec![CasMountGrant {
1799            name: "test:stage-label",
1800            subject: CasGrantSubject::AnyAuthenticated,
1801            kinds: &[CasMountObjectKind::Stage],
1802            operations: &["stage:label"],
1803        }]);
1804        let domain = DedupDomain::local_default();
1805        let requested_label = label();
1806        let request = CasMountAuthzRequest {
1807            kind: CasMountObjectKind::Stage,
1808            address: "1",
1809            domain: &domain,
1810            verified_tenant: None,
1811            operation: "stage:label",
1812            requested_label: Some(&requested_label),
1813        };
1814
1815        let err = authz
1816            .authorize(&Subject::new("alice"), request)
1817            .await
1818            .unwrap_err();
1819        assert!(matches!(err, MountError::PermissionDenied(_)));
1820    }
1821
1822    // ── write-then-seal (#814) ─────────────────────────────────────────────
1823
1824    /// Build a mount with small quotas so overflow paths are testable without
1825    /// allocating hundreds of MiB.
1826    fn staging_mount(substrate: CasSubstrate, slot_quota: usize, subject_quota: usize) -> CasMount {
1827        CasMount::with_authorizer_and_staging(
1828            substrate,
1829            DedupDomain::local_default(),
1830            AllowAllCasAuthorizer,
1831            StagingConfig {
1832                slot_quota_bytes: slot_quota,
1833                subject_quota_bytes: subject_quota,
1834                lattice: None,
1835            },
1836        )
1837    }
1838
1839    /// Create a staging slot and return `(id, root_fid)`. The root fid pins the
1840    /// slot (one outstanding reference); tests must `clunk` it — along with any
1841    /// walked data/ctl fids — for the slot to be reaped.
1842    async fn create_stage(mount: &CasMount, caller: &Subject) -> (String, Fid) {
1843        let mut root = mount.walk(&["stage"], caller).await.unwrap();
1844        let stat = mount
1845            .create(&mut root, "new", 0o600, OWRITE, caller)
1846            .await
1847            .unwrap();
1848        (stat.name, root)
1849    }
1850
1851    async fn open_data_ctl(mount: &CasMount, id: &str, caller: &Subject) -> (Fid, Fid) {
1852        let mut data = mount.walk(&["stage", id, "data"], caller).await.unwrap();
1853        let mut ctl = mount.walk(&["stage", id, "ctl"], caller).await.unwrap();
1854        mount.open(&mut data, ORDWR, caller).await.unwrap();
1855        mount.open(&mut ctl, ORDWR, caller).await.unwrap();
1856        (data, ctl)
1857    }
1858
1859    /// Read the ctl status text as an owned `String` (avoids temporary-value
1860    /// borrow errors from `from_utf8_lossy(&mount.read(...).await.unwrap())`).
1861    async fn ctl_str(mount: &CasMount, ctl: &Fid, caller: &Subject) -> String {
1862        String::from_utf8_lossy(&mount.read(ctl, 0, 1024, caller).await.unwrap()).into_owned()
1863    }
1864
1865    #[tokio::test]
1866    async fn create_then_seal_returns_cid_readable_via_ctl() {
1867        let dir = tempfile::tempdir().unwrap();
1868        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
1869        let caller = Subject::new("alice");
1870        let (id, _root) = create_stage(&mount, &caller).await;
1871        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
1872
1873        // Pre-seal status.
1874        let pre = mount.read(&ctl, 0, 1024, &caller).await.unwrap();
1875        assert!(String::from_utf8_lossy(&pre).contains("state=staging"));
1876
1877        // Two positioned writes (resumable by offset).
1878        mount.write(&data, 0, b"hello ", &caller).await.unwrap();
1879        mount.write(&data, 6, b"world", &caller).await.unwrap();
1880
1881        // Seal.
1882        declare_test_label(&mount, &ctl, &caller).await;
1883        let n = mount.write(&ctl, 0, b"commit\n", &caller).await.unwrap();
1884        assert_eq!(n, 7);
1885
1886        let post = mount.read(&ctl, 0, 1024, &caller).await.unwrap();
1887        let status = String::from_utf8_lossy(&post);
1888        assert!(status.contains("state=sealed "), "got: {status}");
1889        let sealed_cid = status.split("cid=").nth(1).unwrap().trim().to_owned();
1890        assert!(!sealed_cid.is_empty());
1891
1892        // The bytes are reconstructable by CID through the read side.
1893        let got = mount
1894            .substrate
1895            .get(&mount.domain, &sealed_cid)
1896            .await
1897            .unwrap();
1898        assert_eq!(got, b"hello world");
1899
1900        // Cluck everything; sealed content remains in the substrate.
1901        mount.clunk(data, &caller).await;
1902        // Read the CID one more time before clucking ctl.
1903        let _ = mount.read(&ctl, 0, 1024, &caller).await.unwrap();
1904        mount.clunk(ctl, &caller).await;
1905        assert_eq!(
1906            mount
1907                .substrate
1908                .get(&mount.domain, &sealed_cid)
1909                .await
1910                .unwrap(),
1911            b"hello world"
1912        );
1913    }
1914
1915    #[tokio::test]
1916    async fn sparse_write_zero_fills_gap() {
1917        let dir = tempfile::tempdir().unwrap();
1918        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
1919        let caller = Subject::new("alice");
1920        let (id, _root) = create_stage(&mount, &caller).await;
1921        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
1922
1923        // Write at offset 5, leaving bytes 0..5 as a sparse gap.
1924        mount.write(&data, 5, b"xyz", &caller).await.unwrap();
1925        let buf = mount.read(&data, 0, 64, &caller).await.unwrap();
1926        assert_eq!(&buf[5..8], b"xyz");
1927        assert_eq!(&buf[..5], &[0, 0, 0, 0, 0]);
1928
1929        declare_test_label(&mount, &ctl, &caller).await;
1930        mount.write(&ctl, 0, b"commit\n", &caller).await.unwrap();
1931        let status = ctl_str(&mount, &ctl, &caller).await;
1932        let cid = status.split("cid=").nth(1).unwrap().trim().to_owned();
1933        let reconstructed = mount.substrate.get(&mount.domain, &cid).await.unwrap();
1934        assert_eq!(reconstructed.len(), 8);
1935        assert_eq!(&reconstructed[..5], &[0, 0, 0, 0, 0]);
1936        assert_eq!(&reconstructed[5..], b"xyz");
1937        mount.clunk(data, &caller).await;
1938        mount.clunk(ctl, &caller).await;
1939    }
1940
1941    #[tokio::test]
1942    async fn cluck_without_commit_voids_and_discards() {
1943        let dir = tempfile::tempdir().unwrap();
1944        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
1945        let caller = Subject::new("alice");
1946        let (id, root) = create_stage(&mount, &caller).await;
1947        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
1948        mount
1949            .write(&data, 0, b"never sealed", &caller)
1950            .await
1951            .unwrap();
1952
1953        // Cluck every fid (root + data + ctl) without committing → the slot is
1954        // reaped (outstanding refcount hits zero while still Open).
1955        mount.clunk(data, &caller).await;
1956        mount.clunk(ctl, &caller).await;
1957        mount.clunk(root, &caller).await;
1958
1959        // Walking the id again fails (NotFound).
1960        let err = mount
1961            .walk(&["stage", &id, "data"], &caller)
1962            .await
1963            .unwrap_err();
1964        assert!(matches!(err, MountError::NotFound(_)));
1965
1966        // And the stage dir no longer lists it.
1967        let stage = mount.walk(&["stage"], &caller).await.unwrap();
1968        let entries = mount.readdir(&stage, &caller).await.unwrap();
1969        assert!(entries.is_empty());
1970    }
1971
1972    #[tokio::test]
1973    async fn explicit_abort_discards_and_releases_quota() {
1974        let dir = tempfile::tempdir().unwrap();
1975        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 1 << 20);
1976        let caller = Subject::new("alice");
1977        let (id, _root) = create_stage(&mount, &caller).await;
1978        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
1979        mount.write(&data, 0, &[0u8; 4096], &caller).await.unwrap();
1980        assert_eq!(mount.staging.subject_usage(&caller), 4096);
1981
1982        // Abort via ctl.
1983        mount.write(&ctl, 0, b"abort\n", &caller).await.unwrap();
1984        let status = ctl_str(&mount, &ctl, &caller).await;
1985        assert!(status.contains("state=voided"), "got: {status}");
1986
1987        // Subject quota released.
1988        assert_eq!(mount.staging.subject_usage(&caller), 0);
1989
1990        // Cannot commit a voided slot.
1991        let err = mount
1992            .write(&ctl, 0, b"commit\n", &caller)
1993            .await
1994            .unwrap_err();
1995        assert!(matches!(err, MountError::InvalidArgument(_)));
1996        mount.clunk(data, &caller).await;
1997        mount.clunk(ctl, &caller).await;
1998    }
1999
2000    #[tokio::test]
2001    async fn commit_is_idempotent() {
2002        let dir = tempfile::tempdir().unwrap();
2003        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
2004        let caller = Subject::new("alice");
2005        let (id, _root) = create_stage(&mount, &caller).await;
2006        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2007        mount.write(&data, 0, b"payload", &caller).await.unwrap();
2008
2009        declare_test_label(&mount, &ctl, &caller).await;
2010        mount.write(&ctl, 0, b"commit\n", &caller).await.unwrap();
2011        let cid1 = {
2012            let s = ctl_str(&mount, &ctl, &caller).await;
2013            s.split("cid=").nth(1).unwrap().trim().to_owned()
2014        };
2015
2016        // A second commit returns the same CID without re-ingesting.
2017        mount.write(&ctl, 0, b"commit\n", &caller).await.unwrap();
2018        let cid2 = {
2019            let s = ctl_str(&mount, &ctl, &caller).await;
2020            s.split("cid=").nth(1).unwrap().trim().to_owned()
2021        };
2022        assert_eq!(cid1, cid2);
2023        mount.clunk(data, &caller).await;
2024        mount.clunk(ctl, &caller).await;
2025    }
2026
2027    #[tokio::test]
2028    async fn slot_quota_rejects_oversize_write() {
2029        let dir = tempfile::tempdir().unwrap();
2030        let mount = staging_mount(CasSubstrate::new(dir.path()), 8, 64);
2031        let caller = Subject::new("alice");
2032        let (id, _root) = create_stage(&mount, &caller).await;
2033        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2034        let err = mount
2035            .write(&data, 0, &[0u8; 16], &caller)
2036            .await
2037            .unwrap_err();
2038        assert!(matches!(err, MountError::PermissionDenied(_)));
2039        mount.clunk(data, &caller).await;
2040        mount.clunk(ctl, &caller).await;
2041    }
2042
2043    #[tokio::test]
2044    async fn subject_quota_aggregates_across_slots() {
2045        let dir = tempfile::tempdir().unwrap();
2046        // slot=8, subject=12 → two slots can't both fill.
2047        let mount = staging_mount(CasSubstrate::new(dir.path()), 8, 12);
2048        let caller = Subject::new("alice");
2049        let (id1, _root1) = create_stage(&mount, &caller).await;
2050        let (id2, _root2) = create_stage(&mount, &caller).await;
2051        let (d1, c1) = open_data_ctl(&mount, &id1, &caller).await;
2052        let (d2, c2) = open_data_ctl(&mount, &id2, &caller).await;
2053
2054        mount.write(&d1, 0, &[0u8; 8], &caller).await.unwrap();
2055        assert_eq!(mount.staging.subject_usage(&caller), 8);
2056        // Second slot's 8 bytes would bring the total to 16 > 12.
2057        let err = mount.write(&d2, 0, &[0u8; 8], &caller).await.unwrap_err();
2058        assert!(matches!(err, MountError::PermissionDenied(_)));
2059        assert_eq!(mount.staging.subject_usage(&caller), 8);
2060        for f in [d1, c1, d2, c2] {
2061            mount.clunk(f, &caller).await;
2062        }
2063    }
2064
2065    #[tokio::test]
2066    async fn cross_subject_isolation_not_found_for_foreign_slot() {
2067        let dir = tempfile::tempdir().unwrap();
2068        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
2069        let alice = Subject::new("alice");
2070        let bob = Subject::new("bob");
2071        let (id, _root) = create_stage(&mount, &alice).await;
2072
2073        // Bob cannot see alice's slot: NotFound (no existence leak).
2074        let err = mount.walk(&["stage", &id, "data"], &bob).await.unwrap_err();
2075        assert!(matches!(err, MountError::NotFound(_)));
2076
2077        // And bob's stage listing is empty.
2078        let bob_stage = mount.walk(&["stage"], &bob).await.unwrap();
2079        assert!(mount.readdir(&bob_stage, &bob).await.unwrap().is_empty());
2080
2081        // Alice still sees it.
2082        let alice_stage = mount.walk(&["stage"], &alice).await.unwrap();
2083        let entries = mount.readdir(&alice_stage, &alice).await.unwrap();
2084        assert_eq!(entries.len(), 1);
2085
2086        let (d, c) = open_data_ctl(&mount, &id, &alice).await;
2087        mount.clunk(d, &alice).await;
2088        mount.clunk(c, &alice).await;
2089    }
2090
2091    #[tokio::test]
2092    async fn seal_joins_declared_labels_into_manifest() {
2093        use hyprstream_rpc::auth::mac::{Compartment, LatticeVersion};
2094        let dir = tempfile::tempdir().unwrap();
2095        let lattice = Arc::new(Lattice::new(
2096            LatticeVersion(1),
2097            [Compartment::new("pii"), Compartment::new("finance")],
2098        ));
2099        let mount = CasMount::with_authorizer_and_staging(
2100            CasSubstrate::new(dir.path()),
2101            DedupDomain::local_default(),
2102            AllowAllCasAuthorizer,
2103            StagingConfig {
2104                slot_quota_bytes: 1 << 20,
2105                subject_quota_bytes: 4 << 20,
2106                lattice: Some(lattice.clone()),
2107            },
2108        );
2109        let caller = Subject::new("alice");
2110        let (id, _root) = create_stage(&mount, &caller).await;
2111        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2112        mount
2113            .write(&data, 0, b"labeled-bytes", &caller)
2114            .await
2115            .unwrap();
2116
2117        // Declare two labels; the seal must apply the IFC provenance join.
2118        mount
2119            .write(&ctl, 0, b"label internal classical pii\n", &caller)
2120            .await
2121            .unwrap();
2122        mount
2123            .write(&ctl, 0, b"label confidential pqhybrid finance\n", &caller)
2124            .await
2125            .unwrap();
2126
2127        let status = ctl_str(&mount, &ctl, &caller).await;
2128        assert!(status.contains("labels=2"), "got: {status}");
2129
2130        mount.write(&ctl, 0, b"commit\n", &caller).await.unwrap();
2131        let cid = {
2132            let s = ctl_str(&mount, &ctl, &caller).await;
2133            s.split("cid=").nth(1).unwrap().trim().to_owned()
2134        };
2135
2136        let pii = lattice
2137            .label(
2138                Level::Internal,
2139                Assurance::Classical,
2140                [Compartment::new("pii")],
2141            )
2142            .unwrap();
2143        let pqhybrid_finance_input = lattice
2144            .label(
2145                Level::Confidential,
2146                Assurance::PqHybrid,
2147                [Compartment::new("finance")],
2148            )
2149            .unwrap();
2150        let joined = ifc_join(&[pii, pqhybrid_finance_input]);
2151        let finance_at_joined_assurance = lattice
2152            .label(
2153                Level::Confidential,
2154                joined.assurance,
2155                [Compartment::new("finance")],
2156            )
2157            .unwrap();
2158        let manifest = mount.substrate.manifest(&mount.domain, &cid).unwrap();
2159        assert_eq!(manifest.security_label, joined);
2160        assert_eq!(manifest.security_label.assurance, Assurance::Classical);
2161        assert!(manifest.security_label.can_access(&pii));
2162        assert!(manifest
2163            .security_label
2164            .can_access(&finance_at_joined_assurance));
2165        assert!(!manifest.security_label.can_access(&pqhybrid_finance_input));
2166        assert!(manifest.security_label.compartments.contains(0));
2167        assert!(manifest.security_label.compartments.contains(1));
2168        mount.clunk(data, &caller).await;
2169        mount.clunk(ctl, &caller).await;
2170    }
2171
2172    #[tokio::test]
2173    async fn seal_without_a_label_fails_closed_before_cas_ingest() {
2174        let dir = tempfile::tempdir().unwrap();
2175        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
2176        let caller = Subject::new("alice");
2177        let (id, _root) = create_stage(&mount, &caller).await;
2178        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2179        mount
2180            .write(&data, 0, b"must-not-seal", &caller)
2181            .await
2182            .unwrap();
2183
2184        let err = mount
2185            .write(&ctl, 0, b"commit\n", &caller)
2186            .await
2187            .unwrap_err();
2188        assert!(matches!(err, MountError::PermissionDenied(_)));
2189        assert!(ctl_str(&mount, &ctl, &caller)
2190            .await
2191            .contains("state=staging"));
2192
2193        declare_test_label(&mount, &ctl, &caller).await;
2194        mount.write(&ctl, 0, b"commit\n", &caller).await.unwrap();
2195        mount.clunk(data, &caller).await;
2196        mount.clunk(ctl, &caller).await;
2197    }
2198
2199    #[tokio::test]
2200    async fn create_rejected_under_obj_or_xorb() {
2201        let mount = staging_mount(
2202            CasSubstrate::new(tempfile::tempdir().unwrap().path()),
2203            1 << 20,
2204            4 << 20,
2205        );
2206        let caller = Subject::new("alice");
2207        let mut obj_dir = mount.walk(&["obj"], &caller).await.unwrap();
2208        let err = mount
2209            .create(&mut obj_dir, "new", 0o600, OWRITE, &caller)
2210            .await
2211            .unwrap_err();
2212        assert!(matches!(err, MountError::NotSupported(_)));
2213    }
2214
2215    #[tokio::test]
2216    async fn denyall_authorizer_blocks_create_and_commit() {
2217        let dir = tempfile::tempdir().unwrap();
2218        let mount = CasMount::new(CasSubstrate::new(dir.path()), DedupDomain::local_default());
2219        let caller = Subject::new("alice");
2220        let mut stage = mount.walk(&["stage"], &caller).await.unwrap();
2221        let err = mount
2222            .create(&mut stage, "new", 0o600, OWRITE, &caller)
2223            .await
2224            .unwrap_err();
2225        assert!(matches!(err, MountError::PermissionDenied(_)));
2226    }
2227
2228    #[tokio::test]
2229    async fn unknown_ctl_command_is_rejected() {
2230        let dir = tempfile::tempdir().unwrap();
2231        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
2232        let caller = Subject::new("alice");
2233        let (id, _root) = create_stage(&mount, &caller).await;
2234        let (_data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2235        let err = mount
2236            .write(&ctl, 0, b"frobnicate\n", &caller)
2237            .await
2238            .unwrap_err();
2239        assert!(matches!(err, MountError::InvalidArgument(_)));
2240        mount.clunk(ctl, &caller).await;
2241    }
2242
2243    #[tokio::test]
2244    async fn stage_fid_open_modes_are_enforced() {
2245        let dir = tempfile::tempdir().unwrap();
2246        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
2247        let caller = Subject::new("alice");
2248        let (id, _root) = create_stage(&mount, &caller).await;
2249
2250        // A write-only data fid must not read staged bytes.
2251        let mut wo = mount.walk(&["stage", &id, "data"], &caller).await.unwrap();
2252        mount.open(&mut wo, OWRITE, &caller).await.unwrap();
2253        mount.write(&wo, 0, b"secret", &caller).await.unwrap();
2254        let err = mount.read(&wo, 0, 64, &caller).await.unwrap_err();
2255        assert!(matches!(err, MountError::PermissionDenied(_)));
2256
2257        // A read-only data fid must not write.
2258        let mut ro = mount.walk(&["stage", &id, "data"], &caller).await.unwrap();
2259        mount.open(&mut ro, OREAD, &caller).await.unwrap();
2260        let err = mount.write(&ro, 0, b"x", &caller).await.unwrap_err();
2261        assert!(matches!(err, MountError::PermissionDenied(_)));
2262        assert_eq!(mount.read(&ro, 0, 64, &caller).await.unwrap(), b"secret");
2263
2264        // An unopened fid is rejected outright.
2265        let unopened = mount.walk(&["stage", &id, "ctl"], &caller).await.unwrap();
2266        let err = mount.read(&unopened, 0, 64, &caller).await.unwrap_err();
2267        assert!(matches!(err, MountError::InvalidArgument(_)));
2268
2269        for f in [wo, ro, unopened] {
2270            mount.clunk(f, &caller).await;
2271        }
2272    }
2273
2274    #[tokio::test]
2275    async fn abort_after_seal_is_rejected_and_abort_is_idempotent() {
2276        let dir = tempfile::tempdir().unwrap();
2277        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
2278        let caller = Subject::new("alice");
2279
2280        // Abort after a successful commit must not clobber the sealed state.
2281        let (id, _root) = create_stage(&mount, &caller).await;
2282        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2283        mount
2284            .write(&data, 0, b"sealed-bytes", &caller)
2285            .await
2286            .unwrap();
2287        declare_test_label(&mount, &ctl, &caller).await;
2288        mount.write(&ctl, 0, b"commit\n", &caller).await.unwrap();
2289        let err = mount.write(&ctl, 0, b"abort\n", &caller).await.unwrap_err();
2290        assert!(matches!(err, MountError::InvalidArgument(_)));
2291        let status = ctl_str(&mount, &ctl, &caller).await;
2292        assert!(status.contains("state=sealed"), "got: {status}");
2293        mount.clunk(data, &caller).await;
2294        mount.clunk(ctl, &caller).await;
2295
2296        // A second abort of a voided slot is an idempotent no-op.
2297        let (id2, _root2) = create_stage(&mount, &caller).await;
2298        let (d2, c2) = open_data_ctl(&mount, &id2, &caller).await;
2299        mount.write(&c2, 0, b"abort\n", &caller).await.unwrap();
2300        mount.write(&c2, 0, b"abort\n", &caller).await.unwrap();
2301        let status = ctl_str(&mount, &c2, &caller).await;
2302        assert!(status.contains("state=voided"), "got: {status}");
2303        mount.clunk(d2, &caller).await;
2304        mount.clunk(c2, &caller).await;
2305    }
2306
2307    #[tokio::test]
2308    async fn label_after_seal_is_rejected() {
2309        let dir = tempfile::tempdir().unwrap();
2310        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
2311        let caller = Subject::new("alice");
2312        let (id, _root) = create_stage(&mount, &caller).await;
2313        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2314        mount.write(&data, 0, b"bytes", &caller).await.unwrap();
2315        declare_test_label(&mount, &ctl, &caller).await;
2316        mount.write(&ctl, 0, b"commit\n", &caller).await.unwrap();
2317        let err = mount
2318            .write(&ctl, 0, b"label secret pqhybrid\n", &caller)
2319            .await
2320            .unwrap_err();
2321        assert!(matches!(err, MountError::InvalidArgument(_)));
2322        mount.clunk(data, &caller).await;
2323        mount.clunk(ctl, &caller).await;
2324    }
2325
2326    #[tokio::test]
2327    async fn concurrent_commits_converge_on_one_cid() {
2328        let dir = tempfile::tempdir().unwrap();
2329        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
2330        let caller = Subject::new("alice");
2331        let (id, _root) = create_stage(&mount, &caller).await;
2332        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2333        mount
2334            .write(&data, 0, b"raced-bytes", &caller)
2335            .await
2336            .unwrap();
2337        declare_test_label(&mount, &ctl, &caller).await;
2338
2339        // Two commits racing on the same slot: exactly one seals, the other
2340        // waits on the seal (never spinning) and converges on the same CID.
2341        let (a, b) = tokio::join!(
2342            mount.write(&ctl, 0, b"commit\n", &caller),
2343            mount.write(&ctl, 0, b"commit\n", &caller),
2344        );
2345        a.unwrap();
2346        b.unwrap();
2347        let status = ctl_str(&mount, &ctl, &caller).await;
2348        assert!(status.contains("state=sealed cid="), "got: {status}");
2349        mount.clunk(data, &caller).await;
2350        mount.clunk(ctl, &caller).await;
2351    }
2352
2353    #[tokio::test]
2354    async fn commit_authorizes_with_staging_id_address() {
2355        let dir = tempfile::tempdir().unwrap();
2356        let authz = std::sync::Arc::new(RecordingAuthorizer::default());
2357        let mount = CasMount::with_authorizer_and_staging(
2358            CasSubstrate::new(dir.path()),
2359            DedupDomain::local_default(),
2360            authz.clone(),
2361            StagingConfig::default(),
2362        );
2363        let caller = Subject::new("alice");
2364        let (id, _root) = create_stage(&mount, &caller).await;
2365        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2366        mount
2367            .write(&data, 0, b"authz-bytes", &caller)
2368            .await
2369            .unwrap();
2370        declare_test_label(&mount, &ctl, &caller).await;
2371        mount.write(&ctl, 0, b"commit\n", &caller).await.unwrap();
2372
2373        // The commit authorization must address the staging id, not "ctl".
2374        let commit_calls: Vec<_> = authz
2375            .calls()
2376            .into_iter()
2377            .filter(|(_, _, _, op)| *op == "stage:commit")
2378            .collect();
2379        assert_eq!(commit_calls.len(), 1);
2380        assert_eq!(commit_calls[0].2, id);
2381        mount.clunk(data, &caller).await;
2382        mount.clunk(ctl, &caller).await;
2383    }
2384
2385    #[tokio::test]
2386    async fn label_authorization_sees_requested_label_and_rejection_does_not_mutate_slot() {
2387        let dir = tempfile::tempdir().unwrap();
2388        let authz = std::sync::Arc::new(RecordingAuthorizer {
2389            deny_labels: true,
2390            ..RecordingAuthorizer::default()
2391        });
2392        let mount = CasMount::with_authorizer_and_staging(
2393            CasSubstrate::new(dir.path()),
2394            DedupDomain::local_default(),
2395            authz.clone(),
2396            StagingConfig::default(),
2397        );
2398        let caller = Subject::new("alice");
2399        let (id, _root) = create_stage(&mount, &caller).await;
2400        let (data, ctl) = open_data_ctl(&mount, &id, &caller).await;
2401
2402        let err = mount
2403            .write(&ctl, 0, b"label internal classical\n", &caller)
2404            .await
2405            .unwrap_err();
2406        assert!(matches!(err, MountError::PermissionDenied(_)));
2407        assert_eq!(authz.label_calls(), vec![("alice".to_owned(), id, label())]);
2408        let status = ctl_str(&mount, &ctl, &caller).await;
2409        assert!(
2410            status.contains("labels=0"),
2411            "rejected label must not mutate slot: {status}"
2412        );
2413        mount.clunk(data, &caller).await;
2414        mount.clunk(ctl, &caller).await;
2415    }
2416
2417    #[tokio::test]
2418    async fn staging_qids_are_distinct_per_slot_and_file() {
2419        // Regression guard for the qid-aliasing finding: a 9P client keys a
2420        // file cache on qid path, so two slots' `data` files (and `data` vs
2421        // `ctl`) MUST NOT share a qid. The path is hashed from
2422        // `stage/{id}/{name}`.
2423        let dir = tempfile::tempdir().unwrap();
2424        let mount = staging_mount(CasSubstrate::new(dir.path()), 1 << 20, 4 << 20);
2425        let caller = Subject::new("alice");
2426        let (id1, root1) = create_stage(&mount, &caller).await;
2427        let (id2, root2) = create_stage(&mount, &caller).await;
2428
2429        // Stat each slot's data + ctl directly (no open needed for stat).
2430        let d1 = mount.walk(&["stage", &id1, "data"], &caller).await.unwrap();
2431        let c1 = mount.walk(&["stage", &id1, "ctl"], &caller).await.unwrap();
2432        let d2 = mount.walk(&["stage", &id2, "data"], &caller).await.unwrap();
2433
2434        let d1_stat = mount.stat(&d1, &caller).await.unwrap();
2435        let c1_stat = mount.stat(&c1, &caller).await.unwrap();
2436        let d2_stat = mount.stat(&d2, &caller).await.unwrap();
2437
2438        // Distinct slots' data files must not alias.
2439        assert_ne!(
2440            d1_stat.path, d2_stat.path,
2441            "stage/<a>/data and stage/<b>/data must have distinct qids"
2442        );
2443        // data vs ctl within the same slot must not alias either.
2444        assert_ne!(
2445            d1_stat.path, c1_stat.path,
2446            "stage/<id>/data and stage/<id>/ctl must have distinct qids"
2447        );
2448        // A qid of 0 would mean "unknown"; make sure these are real identities.
2449        assert_ne!(d1_stat.path, 0);
2450        assert_ne!(d2_stat.path, 0);
2451
2452        // readdir on a staging root also surfaces the per-slot qids.
2453        let entries = mount.readdir(&root1, &caller).await.unwrap();
2454        let data_entry = entries.iter().find(|e| e.name == "data").unwrap();
2455        assert_eq!(data_entry.stat.as_ref().unwrap().path, d1_stat.path);
2456
2457        for f in [d1, c1, d2, root1, root2] {
2458            mount.clunk(f, &caller).await;
2459        }
2460    }
2461}