Skip to main content

hyprstream_vfs/
namespace.rs

1//! Namespace — the client's mount table.
2//!
3//! Routes 9P operations by longest-prefix match to mount targets.
4//! Forkable for per-task sandboxing. Static after initial population.
5
6use std::sync::Arc;
7
8use crate::mac_pep::NamespaceAction;
9#[cfg(not(target_arch = "wasm32"))]
10use crate::mac_pep::NamespacePep;
11use crate::mount::{DirEntry, Fid, Mount, MountError, Stat, OWRITE};
12use hyprstream_rpc::Subject;
13
14// ─────────────────────────────────────────────────────────────────────────────
15// Types
16// ─────────────────────────────────────────────────────────────────────────────
17
18/// Namespace error.
19#[derive(Debug)]
20pub enum NamespaceError {
21    Mount(MountError),
22    ReservedPath(String),
23    /// A mandatory MAC reference-monitor decision denied the op (#1272).
24    ///
25    /// Carries the [`NamespaceAction`] that was denied and a human-readable
26    /// detail string. This is the fail-closed surface: the PEP returns this
27    /// variant whenever the caller's clearance is unprovable, the object is
28    /// unlabeled, or `can_access` fails. There is no permissive fallback.
29    Denied(NamespaceAction, String),
30}
31
32impl std::fmt::Display for NamespaceError {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        match self {
35            Self::Mount(e) => write!(f, "{e}"),
36            Self::ReservedPath(p) => write!(f, "reserved path: {p}"),
37            Self::Denied(action, detail) => {
38                write!(f, "MAC denied {action:?}: {detail}")
39            }
40        }
41    }
42}
43
44impl std::error::Error for NamespaceError {}
45
46impl From<MountError> for NamespaceError {
47    fn from(e: MountError) -> Self {
48        Self::Mount(e)
49    }
50}
51
52/// How a new mount interacts with existing mounts at the same prefix.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum BindFlag {
55    /// Replace any existing mount at this prefix.
56    Replace,
57    /// Prepend: new mount's entries appear first in union readdir.
58    Before,
59    /// Append: new mount's entries appear after existing.
60    After,
61    /// Append *and* designate this target as the union's writable **upper**
62    /// layer for copy-up (#370). A write to a path that exists only in a
63    /// read-only lower is copied up into this target specifically, rather than
64    /// the first target that happens to accept a `create` (the bind-order
65    /// heuristic used when no upper is designated).
66    Upper,
67}
68
69/// What a mount point routes to — always an in-process Mount impl.
70pub type MountTarget = Arc<dyn Mount>;
71
72/// A routed mount capability restricted to read operations. The underlying
73/// writable `Mount` is never returned to read-only protocol adapters.
74#[derive(Clone)]
75pub struct ReadMountTarget(MountTarget);
76
77impl ReadMountTarget {
78    pub async fn walk(&self, components: &[&str], caller: &Subject) -> Result<Fid, MountError> {
79        self.0.walk(components, caller).await
80    }
81
82    pub async fn open(&self, fid: &mut Fid, mode: u8, caller: &Subject) -> Result<(), MountError> {
83        if mode != 0 {
84            return Err(MountError::PermissionDenied(
85                "read-only namespace target".into(),
86            ));
87        }
88        self.0.open(fid, mode, caller).await
89    }
90
91    pub async fn read(
92        &self,
93        fid: &Fid,
94        offset: u64,
95        count: u32,
96        caller: &Subject,
97    ) -> Result<Vec<u8>, MountError> {
98        self.0.read(fid, offset, count, caller).await
99    }
100
101    pub async fn readdir(&self, fid: &Fid, caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
102        self.0.readdir(fid, caller).await
103    }
104
105    pub async fn stat(&self, fid: &Fid, caller: &Subject) -> Result<Stat, MountError> {
106        self.0.stat(fid, caller).await
107    }
108
109    pub async fn clunk(&self, fid: Fid, caller: &Subject) {
110        self.0.clunk(fid, caller).await;
111    }
112}
113
114struct MountEntry {
115    prefix: String,
116    targets: Vec<MountTarget>,
117    /// The designated copy-up upper for this union, if one was bound with
118    /// [`BindFlag::Upper`]. Held as an `Arc` clone (not an index) so it stays
119    /// stable across later `Before` inserts that would shift positions. Always
120    /// also present in `targets` (so reads and readdir-merge see it).
121    upper: Option<MountTarget>,
122}
123
124// ─────────────────────────────────────────────────────────────────────────────
125// Namespace
126// ─────────────────────────────────────────────────────────────────────────────
127
128/// Maximum read size for cat/ctl loops (16 MB).
129const MAX_READ_SIZE: usize = 16 * 1024 * 1024;
130
131/// Client-side namespace. Maps path prefixes to mount targets.
132///
133/// Populated from service discovery at startup (`/srv/{name}`).
134/// Forkable for per-task sandboxing via `fork()` + `unmount()`.
135///
136/// # MAC enforcement (#1272)
137///
138/// The namespace carries an optional [`NamespacePep`] — the mandatory
139/// reference monitor over the direct API. A namespace built with [`Self::new`]
140/// is **unenforced** (the dormant status quo, matching the rest of MAC
141/// enforcement today); installing a PEP with [`Self::with_pep`] arms the
142/// fail-closed monitor so every read/write/create and every
143/// `mount`/`bind_mount`/`unmount` then requires a proven subject. Flipping the
144/// default to enforced at construction sites is the separately-gated activation
145/// B-lane (#1267), not this field's existence.
146pub struct Namespace {
147    mounts: Vec<MountEntry>,
148    /// Mandatory MAC reference monitor over the direct API. `None` ⇒ the
149    /// un-enforced status quo; `Some` ⇒ every mediated op must pass it.
150    #[cfg(not(target_arch = "wasm32"))]
151    pep: Option<Arc<NamespacePep>>,
152}
153
154impl Namespace {
155    /// Create an empty, **unenforced** namespace.
156    ///
157    /// No MAC PEP is installed: direct-API ops behave as before (the
158    /// documented dormant posture — CLAUDE.md "MAC current status"). To arm
159    /// fail-closed enforcement, call [`Self::with_pep`] after construction.
160    pub fn new() -> Self {
161        Self {
162            mounts: Vec::new(),
163            #[cfg(not(target_arch = "wasm32"))]
164            pep: None,
165        }
166    }
167
168    /// Install (or replace) the mandatory MAC reference monitor.
169    ///
170    /// Once armed, every mediated direct-API op (`cat`/`read_one`/`echo`/
171    /// `create`/`ctl`) requires a subject whose clearance the PEP can prove,
172    /// and the subject-less `mount`/`bind_mount`/`unmount` **deny** — runtime
173    /// callers must use the `_as` variants with a proven [`Subject`]. The PEP
174    /// itself is fail-closed by construction (see [`NamespacePep`]).
175    ///
176    /// Returns the previous PEP, if any (enables atomic re-arm in tests).
177    #[cfg(not(target_arch = "wasm32"))]
178    pub fn set_pep(&mut self, pep: Arc<NamespacePep>) -> Option<Arc<NamespacePep>> {
179        self.pep.replace(pep)
180    }
181
182    /// Whether a MAC PEP is currently armed on this namespace.
183    #[cfg(not(target_arch = "wasm32"))]
184    pub fn pep_armed(&self) -> bool {
185        self.pep.is_some()
186    }
187
188    /// Browser namespaces are clients; server-side MAC enforcement is absent.
189    #[cfg(target_arch = "wasm32")]
190    pub const fn pep_armed(&self) -> bool {
191        false
192    }
193
194    /// Enforce `action` by `subject` against the object at `path` when a PEP is
195    /// armed. No-op (permit) when no PEP is installed — the dormant status quo.
196    /// Fail-closed when armed: any unresolvable clearance/label or failed
197    /// `can_access` yields [`NamespaceError::Denied`].
198    #[cfg(not(target_arch = "wasm32"))]
199    async fn enforce(
200        &self,
201        subject: &Subject,
202        path: &str,
203        action: NamespaceAction,
204    ) -> Result<(), NamespaceError> {
205        let Some(pep) = &self.pep else {
206            return Ok(());
207        };
208        // Pass the canonical normalized path through the shared resolver
209        // contract. The authoritative resolver (in the `hyprstream` crate)
210        // performs prefix matching against genesis/bind-label carriers; the
211        // namespace supplies only the path, never a caller-authored label.
212        let normalized = normalize_path(path);
213        pep.authorize(subject, &normalized, action).await
214    }
215
216    #[cfg(target_arch = "wasm32")]
217    async fn enforce(
218        &self,
219        _subject: &Subject,
220        _path: &str,
221        _action: NamespaceAction,
222    ) -> Result<(), NamespaceError> {
223        // Browser VFS is a client. The native service boundary owns the
224        // mandatory MAC reference monitor and never delegates it to wasm.
225        Ok(())
226    }
227
228    /// Mount a target at a path prefix (replaces any existing mount).
229    ///
230    /// This is the **namespace-construction** path: it carries no [`Subject`]
231    /// and is therefore usable only while no MAC PEP is armed (the build/fork
232    /// phase before [`Self::set_pep`]). Once a PEP is armed, this denies —
233    /// runtime callers must prove a subject via [`Self::mount_as`].
234    pub fn mount(&mut self, prefix: &str, target: MountTarget) -> Result<(), NamespaceError> {
235        self.bind_mount(prefix, target, BindFlag::Replace)
236    }
237
238    /// Subject-mediated `mount` — the runtime path under an armed PEP (#1272).
239    pub async fn mount_as(
240        &mut self,
241        prefix: &str,
242        target: MountTarget,
243        subject: &Subject,
244    ) -> Result<(), NamespaceError> {
245        self.enforce(subject, prefix, NamespaceAction::Mount)
246            .await?;
247        self.bind_mount_inner(prefix, target, BindFlag::Replace)
248    }
249
250    /// Mount a target at a path prefix with union semantics.
251    ///
252    /// - `Replace`: removes any existing mount at this prefix.
253    /// - `Before`: prepends the target — its entries appear first in readdir,
254    ///   and walk tries it before existing mounts at the same prefix.
255    /// - `After`: appends the target — existing mounts are tried first.
256    /// - `Upper`: appends the target *and* records it as the union's writable
257    ///   copy-up upper (#370). See [`BindFlag::Upper`].
258    ///
259    /// Like [`Self::mount`], this is the **construction** path (no subject):
260    /// when a PEP is armed it denies — use [`Self::bind_mount_as`].
261    pub fn bind_mount(
262        &mut self,
263        prefix: &str,
264        target: MountTarget,
265        flag: BindFlag,
266    ) -> Result<(), NamespaceError> {
267        #[cfg(not(target_arch = "wasm32"))]
268        if let Some(pep) = &self.pep {
269            // An armed namespace cannot mutate without a proven subject — the
270            // subject-less construction path is intentionally closed once the
271            // reference monitor is in place (#1272). Route the forced denial
272            // through the PEP so it is recorded in the audit WAL.
273            let normalized = normalize_path(prefix);
274            return Err(pep.deny_uncredentialed(&normalized, NamespaceAction::BindMount));
275        }
276        self.bind_mount_inner(prefix, target, flag)
277    }
278
279    /// Subject-mediated `bind_mount` — the runtime path under an armed PEP.
280    pub async fn bind_mount_as(
281        &mut self,
282        prefix: &str,
283        target: MountTarget,
284        flag: BindFlag,
285        subject: &Subject,
286    ) -> Result<(), NamespaceError> {
287        self.enforce(subject, prefix, NamespaceAction::BindMount)
288            .await?;
289        self.bind_mount_inner(prefix, target, flag)
290    }
291
292    // Core bind logic shared by the construction and mediated paths. Assumes
293    // the caller has already passed any armed PEP (or is the construction path
294    // on an un-armed namespace).
295    fn bind_mount_inner(
296        &mut self,
297        prefix: &str,
298        target: MountTarget,
299        flag: BindFlag,
300    ) -> Result<(), NamespaceError> {
301        let prefix = normalize_prefix(prefix);
302
303        match flag {
304            BindFlag::Replace => {
305                self.mounts.retain(|m| m.prefix != prefix);
306                self.mounts.push(MountEntry {
307                    prefix,
308                    targets: vec![target],
309                    upper: None,
310                });
311            }
312            BindFlag::Before => {
313                if let Some(entry) = self.mounts.iter_mut().find(|m| m.prefix == prefix) {
314                    entry.targets.insert(0, target);
315                } else {
316                    self.mounts.push(MountEntry {
317                        prefix,
318                        targets: vec![target],
319                        upper: None,
320                    });
321                }
322            }
323            BindFlag::After => {
324                if let Some(entry) = self.mounts.iter_mut().find(|m| m.prefix == prefix) {
325                    entry.targets.push(target);
326                } else {
327                    self.mounts.push(MountEntry {
328                        prefix,
329                        targets: vec![target],
330                        upper: None,
331                    });
332                }
333            }
334            BindFlag::Upper => {
335                // The upper is PREPENDED (Before position): overlay semantics
336                // are upper-wins on the read path, and `cat`/`read_one`/
337                // readdir-dedup are all first-success/first-seen in bind order
338                // — so the upper must be tried before any lower. Appending it
339                // would leave union reads returning stale lower content after
340                // a copy-up.
341                if let Some(entry) = self.mounts.iter_mut().find(|m| m.prefix == prefix) {
342                    entry.targets.insert(0, Arc::clone(&target));
343                    entry.upper = Some(target);
344                } else {
345                    self.mounts.push(MountEntry {
346                        prefix,
347                        targets: vec![Arc::clone(&target)],
348                        upper: Some(target),
349                    });
350                }
351            }
352        }
353        // Sort by prefix length descending for longest-prefix match.
354        self.mounts
355            .sort_by_key(|b| std::cmp::Reverse(b.prefix.len()));
356        Ok(())
357    }
358
359    /// Remove a mount point. In forked namespaces, this is irreversible.
360    ///
361    /// Construction path (no subject): denies when a PEP is armed — use
362    /// [`Self::unmount_as`].
363    pub fn unmount(&mut self, prefix: &str) -> Result<(), NamespaceError> {
364        #[cfg(not(target_arch = "wasm32"))]
365        if let Some(pep) = &self.pep {
366            let normalized = normalize_path(prefix);
367            return Err(pep.deny_uncredentialed(&normalized, NamespaceAction::Unmount));
368        }
369        let prefix = normalize_prefix(prefix);
370        self.mounts.retain(|m| m.prefix != prefix);
371        Ok(())
372    }
373
374    /// Subject-mediated `unmount` — the runtime path under an armed PEP.
375    pub async fn unmount_as(
376        &mut self,
377        prefix: &str,
378        subject: &Subject,
379    ) -> Result<(), NamespaceError> {
380        self.enforce(subject, prefix, NamespaceAction::Unmount)
381            .await?;
382        let prefix = normalize_prefix(prefix);
383        self.mounts.retain(|m| m.prefix != prefix);
384        Ok(())
385    }
386
387    /// Create a child namespace (Plan 9 `rfork(RFNAMEG)`).
388    ///
389    /// The child gets a snapshot of the parent's mounts **and** the parent's
390    /// armed PEP (enforcement is inherited — a sandboxed child must not be
391    /// able to escape the reference monitor by forking). Modifications to the
392    /// child do not affect the parent.
393    pub fn fork(&self) -> Namespace {
394        Namespace {
395            #[cfg(not(target_arch = "wasm32"))]
396            pep: self.pep.clone(),
397            mounts: self
398                .mounts
399                .iter()
400                .map(|m| MountEntry {
401                    prefix: m.prefix.clone(),
402                    targets: m.targets.iter().map(Arc::clone).collect(),
403                    upper: m.upper.as_ref().map(Arc::clone),
404                })
405                .collect(),
406        }
407    }
408
409    /// List all mount prefixes (for debugging / `ls /`).
410    pub fn mount_prefixes(&self) -> Vec<&str> {
411        self.mounts.iter().map(|m| m.prefix.as_str()).collect()
412    }
413
414    /// Whether the union at `prefix` has a designated copy-up upper
415    /// ([`BindFlag::Upper`]).
416    ///
417    /// This is the query side of the union's copy-up policy (#370). It is the
418    /// in-process accessor for what a per-union `ctl` control file will expose
419    /// once namespace mutation is mediated through the reference monitor (#613);
420    /// designating the upper at bind time via `BindFlag::Upper` is the write
421    /// side today.
422    pub fn has_designated_upper(&self, prefix: &str) -> bool {
423        let prefix = normalize_prefix(prefix);
424        self.mounts
425            .iter()
426            .find(|m| m.prefix == prefix)
427            .is_some_and(|m| m.upper.is_some())
428    }
429
430    // ── Convenience methods ─────────────────────────────────────────────────
431
432    /// Read the entire contents of a file. Walk + open + read-all + clunk.
433    ///
434    /// Loops reads until an empty Vec is returned, up to 16MB cap.
435    /// With union mounts, tries each target in bind order until one succeeds.
436    pub async fn cat(&self, path: &str, caller: &Subject) -> Result<Vec<u8>, NamespaceError> {
437        self.enforce(caller, path, NamespaceAction::Read).await?;
438        let (targets, remainder) = self.resolve(path)?;
439        let components: Vec<&str> = split_path(&remainder);
440        let mut last_err = None;
441        for mount in targets {
442            let result: Result<Vec<u8>, MountError> = async {
443                let mut fid = mount.walk(&components, caller).await?;
444                if let Err(e) = mount.open(&mut fid, 0, caller).await {
445                    mount.clunk(fid, caller).await;
446                    return Err(e);
447                }
448                let mut data = Vec::new();
449                loop {
450                    match mount.read(&fid, data.len() as u64, 64 * 1024, caller).await {
451                        Ok(chunk) if chunk.is_empty() => break,
452                        Ok(chunk) => {
453                            data.extend_from_slice(&chunk);
454                            if data.len() >= MAX_READ_SIZE {
455                                break;
456                            }
457                        }
458                        Err(e) => {
459                            mount.clunk(fid, caller).await;
460                            return Err(e);
461                        }
462                    }
463                }
464                mount.clunk(fid, caller).await;
465                Ok(data)
466            }
467            .await;
468            match result {
469                Ok(data) => return Ok(data),
470                Err(e) => {
471                    last_err = Some(e);
472                }
473            }
474        }
475        Err(NamespaceError::Mount(
476            last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
477        ))
478    }
479
480    /// Read a single block from a file (for streams). Walk + open + read(once) + clunk.
481    ///
482    /// Unlike `cat()` which loops to EOF, this returns after one read call.
483    /// For streams, this returns the next available block. Empty bytes = EOF.
484    pub async fn read_one(&self, path: &str, caller: &Subject) -> Result<Vec<u8>, NamespaceError> {
485        self.enforce(caller, path, NamespaceAction::Read).await?;
486        let (targets, remainder) = self.resolve(path)?;
487        let components: Vec<&str> = split_path(&remainder);
488        let mut last_err = None;
489        for mount in targets {
490            let result: Result<Vec<u8>, MountError> = async {
491                let mut fid = mount.walk(&components, caller).await?;
492                if let Err(e) = mount.open(&mut fid, 0, caller).await {
493                    mount.clunk(fid, caller).await;
494                    return Err(e);
495                }
496                let chunk = mount.read(&fid, 0, 64 * 1024, caller).await;
497                mount.clunk(fid, caller).await;
498                chunk
499            }
500            .await;
501            match result {
502                Ok(data) => return Ok(data),
503                Err(e) => {
504                    last_err = Some(e);
505                }
506            }
507        }
508        Err(NamespaceError::Mount(
509            last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
510        ))
511    }
512
513    /// Write data to a file. Walk + open(write) + write + clunk.
514    ///
515    /// With union mounts, this implements **copy-up** (#394, #370):
516    ///   1. Try each target in bind order. The first writable target that
517    ///      already holds the file (open(OWRITE) succeeds) wins.
518    ///   2. If no writable target has the file but a read-only *lower* layer
519    ///      does, the lower-layer bytes are copied to the writable *upper*
520    ///      layer (create + write) before applying the new data. The upper is
521    ///      the target designated with [`BindFlag::Upper`] if one exists,
522    ///      otherwise the first target that accepts a `create` (bind order).
523    ///      The upper layer is node-local and append-only (journal), so this
524    ///      never mutates the immutable `/oid` floor in place.
525    ///
526    /// This is the overlayfs copy-up primitive lifted into the namespace: a
527    /// write to a path that resolves through the union dirty-over-committed
528    /// tree lands in the upper layer, leaving the committed floor untouched.
529    pub async fn echo(
530        &self,
531        path: &str,
532        data: &[u8],
533        caller: &Subject,
534    ) -> Result<(), NamespaceError> {
535        self.enforce(caller, path, NamespaceAction::Write).await?;
536        let (entry, remainder) = self.resolve_entry(path)?;
537        let targets = &entry.targets[..];
538        let components: Vec<&str> = split_path(&remainder);
539        let mut last_err = None;
540
541        // Pass 1: try a direct open(OWRITE) on each target in bind order.
542        for mount in targets {
543            let result: Result<(), MountError> = async {
544                let mut fid = mount.walk(&components, caller).await?;
545                if let Err(e) = mount.open(&mut fid, OWRITE, caller).await {
546                    mount.clunk(fid, caller).await;
547                    return Err(e);
548                }
549                mount.write(&fid, 0, data, caller).await?;
550                mount.clunk(fid, caller).await;
551                Ok(())
552            }
553            .await;
554            match result {
555                Ok(()) => return Ok(()),
556                Err(MountError::NotSupported(_)) => {
557                    // This target doesn't support writing (read-only / synthetic
558                    // mount that returned Unsupported from open). Fall through
559                    // to the next target.
560                    last_err = Some(MountError::NotSupported(path.to_owned()));
561                }
562                Err(e) => {
563                    last_err = Some(e);
564                }
565            }
566        }
567
568        // Pass 2: copy-up. If no writable target held the file, check whether a
569        // lower layer has it; if so, stage it into the designated (or first
570        // writable) upper target before writing the new data.
571        if let Some(copied) = self
572            .copy_up(targets, entry.upper.as_ref(), &components, data, caller)
573            .await?
574        {
575            return Ok(copied);
576        }
577
578        Err(NamespaceError::Mount(
579            last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
580        ))
581    }
582
583    /// Create a file or directory at `path` in the first writable target.
584    ///
585    /// This is the namespace-level entry point for the `Mount::create` op: it
586    /// walks to the parent directory in each target (bind order) and calls
587    /// `create` on the first target that accepts it. Lower-layer files are not
588    /// copied up here — `create` is for *new* files; copy-up of existing
589    /// lower-layer content on overwrite is handled by [`echo`](Self::echo).
590    ///
591    /// Returns the new file's `Stat` (qid fields are advisory hints only — see
592    /// the invariant on `hyprstream_vfs::Stat`).
593    pub async fn create(
594        &self,
595        path: &str,
596        perm: u32,
597        caller: &Subject,
598    ) -> Result<Stat, NamespaceError> {
599        self.enforce(caller, path, NamespaceAction::Create).await?;
600        let (targets, remainder) = self.resolve(path)?;
601        let components: Vec<&str> = split_path(&remainder);
602        if components.is_empty() {
603            return Err(NamespaceError::Mount(MountError::InvalidArgument(
604                "create requires a non-empty path".into(),
605            )));
606        }
607        let (name, parent) = components.split_last().expect("non-empty");
608
609        let mut last_err: Option<MountError> = None;
610        for mount in targets {
611            let result: Result<Stat, MountError> = async {
612                let mut dir_fid = mount.walk(parent, caller).await?;
613                // Open the parent directory for read so the backend can assert
614                // it's a directory; some impls require an open before create.
615                if let Err(e) = mount.open(&mut dir_fid, 0, caller).await {
616                    mount.clunk(dir_fid, caller).await;
617                    return Err(e);
618                }
619                let stat = mount
620                    .create(&mut dir_fid, name, perm, OWRITE, caller)
621                    .await?;
622                mount.clunk(dir_fid, caller).await;
623                Ok(stat)
624            }
625            .await;
626            match result {
627                Ok(stat) => return Ok(stat),
628                Err(MountError::NotSupported(_)) => {
629                    last_err = Some(MountError::NotSupported(path.to_owned()));
630                }
631                Err(e) => {
632                    last_err = Some(e);
633                }
634            }
635        }
636        Err(NamespaceError::Mount(
637            last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
638        ))
639    }
640
641    /// Copy-up: if `components` exists in a read-only lower layer but not in
642    /// any writable upper target, read the lower bytes and stage them into the
643    /// upper target via create+write, then apply `new_data` on top at offset 0.
644    ///
645    /// `upper` is the target designated with [`BindFlag::Upper`] for this union,
646    /// if any. When set, copy-up writes to it specifically. When `None`, copy-up
647    /// falls back to the first target in bind order that accepts a `create`
648    /// (#394's original heuristic) — preserving behaviour for unions bound
649    /// without an explicit upper.
650    ///
651    /// Returns `Some(())` if copy-up succeeded (caller treats that as a
652    /// successful echo), or `None` if no lower-layer source was found (caller
653    /// falls back to the original error). The upper write is *append-only* in
654    /// the journal sense — it creates a fresh upper file rather than mutating
655    /// the immutable `/oid` floor in place.
656    ///
657    /// # Semantics
658    ///
659    /// The lower bytes are staged first so a subsequent partial write (offset >
660    /// 0, count < file size) sees the full original content. For a full-file
661    /// `echo` the staged bytes are then overwritten at offset 0 by `new_data`,
662    /// so the visible result is just `new_data` — copy-up only matters for the
663    /// partial-write / append path, but staging unconditionally keeps the upper
664    /// layer a faithful snapshot of "floor + edits".
665    ///
666    /// `caller` threads through both the lower read and the upper create+write,
667    /// so copy-up is mediated by the same `Subject` checks as any other op — it
668    /// is not a privileged bypass (matters for MAC enforcement, #547).
669    async fn copy_up(
670        &self,
671        targets: &[MountTarget],
672        upper: Option<&MountTarget>,
673        components: &[&str],
674        new_data: &[u8],
675        caller: &Subject,
676    ) -> Result<Option<()>, NamespaceError> {
677        let (name, parent) = match components.split_last() {
678            Some(split) => split,
679            None => return Ok(None),
680        };
681
682        // Find the lower-layer source: the first target whose cat(components) succeeds.
683        let mut lower_bytes: Option<Vec<u8>> = None;
684        for mount in targets {
685            let result: Result<Vec<u8>, MountError> = async {
686                let mut fid = mount.walk(components, caller).await?;
687                if let Err(e) = mount.open(&mut fid, 0, caller).await {
688                    mount.clunk(fid, caller).await;
689                    return Err(e);
690                }
691                let mut data = Vec::new();
692                loop {
693                    match mount.read(&fid, data.len() as u64, 64 * 1024, caller).await {
694                        Ok(chunk) if chunk.is_empty() => break,
695                        Ok(chunk) => {
696                            data.extend_from_slice(&chunk);
697                            if data.len() >= MAX_READ_SIZE {
698                                break;
699                            }
700                        }
701                        Err(e) => {
702                            mount.clunk(fid, caller).await;
703                            return Err(e);
704                        }
705                    }
706                }
707                mount.clunk(fid, caller).await;
708                Ok(data)
709            }
710            .await;
711            if let Ok(data) = result {
712                lower_bytes = Some(data);
713                break;
714            }
715        }
716        let Some(_lower) = lower_bytes else {
717            return Ok(None);
718        };
719
720        // Stage into the upper target. We only reach copy-up when the direct
721        // open(OWRITE) pass failed on every target, so the upper target must
722        // *create* the file.
723        //
724        // `echo` is a full-file write at offset 0, so the new content fully
725        // replaces whatever the lower layer held — the staged lower bytes would
726        // be overwritten in their entirety. We therefore create the upper file
727        // and write only `new_data`. (Partial-write / append paths that need to
728        // preserve the lower prefix go through a different primitive, not
729        // `echo`; see the module docs on the append-only upper + journal.)
730        //
731        // Target selection: if the union has a designated upper
732        // ([`BindFlag::Upper`]), copy up into it specifically. Otherwise fall
733        // back to the first target in bind order that accepts the create.
734        let create_into = |mount: &MountTarget| {
735            let mount = Arc::clone(mount);
736            let new_data = new_data.to_vec();
737            let name = name.to_string();
738            let parent: Vec<String> = parent.iter().map(|s| s.to_string()).collect();
739            async move {
740                let parent_refs: Vec<&str> = parent.iter().map(String::as_str).collect();
741                let mut dir_fid = mount.walk(&parent_refs, caller).await?;
742                // Open the parent dir read-only so impls that need an open fid
743                // before create are satisfied.
744                if let Err(e) = mount.open(&mut dir_fid, 0, caller).await {
745                    mount.clunk(dir_fid, caller).await;
746                    return Err(e);
747                }
748                let _stat = mount
749                    .create(&mut dir_fid, &name, 0o644, OWRITE, caller)
750                    .await?;
751                // The create consumed the dir fid and replaced it with the
752                // opened new file. Write the caller's full-file content.
753                mount.write(&dir_fid, 0, &new_data, caller).await?;
754                mount.clunk(dir_fid, caller).await;
755                Ok::<(), MountError>(())
756            }
757        };
758
759        if let Some(up) = upper {
760            // Explicit upper: copy-up targets it and nothing else. A failure
761            // here is the real result — we do not silently fall through to some
762            // other writable target, because that would defeat the point of
763            // designating the upper.
764            return match create_into(up).await {
765                Ok(()) => Ok(Some(())),
766                Err(MountError::NotSupported(_)) => Ok(None),
767                Err(e) => Err(NamespaceError::Mount(e)),
768            };
769        }
770
771        for mount in targets {
772            match create_into(mount).await {
773                Ok(()) => return Ok(Some(())),
774                Err(MountError::NotSupported(_)) => continue,
775                Err(e) => return Err(NamespaceError::Mount(e)),
776            }
777        }
778        // No writable target accepted the create — copy-up not possible.
779        Ok(None)
780    }
781
782    /// Write to a ctl file and read the response. Walk + open(RDWR) + write + read + clunk.
783    ///
784    /// This is the Plan9 ctl pattern: write a command, read the response, all on
785    /// the same fid so the response buffer is available after the write.
786    /// Loops reads until an empty Vec is returned, up to 16MB cap.
787    /// With union mounts, tries each target in bind order until one succeeds.
788    pub async fn ctl(
789        &self,
790        path: &str,
791        data: &[u8],
792        caller: &Subject,
793    ) -> Result<Vec<u8>, NamespaceError> {
794        self.enforce(caller, path, NamespaceAction::Write).await?;
795        let (targets, remainder) = self.resolve(path)?;
796        let components: Vec<&str> = split_path(&remainder);
797        let mut last_err = None;
798        for mount in targets {
799            let result: Result<Vec<u8>, MountError> = async {
800                let mut fid = mount.walk(&components, caller).await?;
801                if let Err(e) = mount.open(&mut fid, 2, caller).await {
802                    mount.clunk(fid, caller).await;
803                    return Err(e);
804                }
805                if let Err(e) = mount.write(&fid, 0, data, caller).await {
806                    mount.clunk(fid, caller).await;
807                    return Err(e);
808                }
809                let mut resp = Vec::new();
810                loop {
811                    match mount.read(&fid, resp.len() as u64, 64 * 1024, caller).await {
812                        Ok(chunk) if chunk.is_empty() => break,
813                        Ok(chunk) => {
814                            resp.extend_from_slice(&chunk);
815                            if resp.len() >= MAX_READ_SIZE {
816                                break;
817                            }
818                        }
819                        Err(e) => {
820                            mount.clunk(fid, caller).await;
821                            return Err(e);
822                        }
823                    }
824                }
825                mount.clunk(fid, caller).await;
826                Ok(resp)
827            }
828            .await;
829            match result {
830                Ok(resp) => return Ok(resp),
831                Err(e) => {
832                    last_err = Some(e);
833                }
834            }
835        }
836        Err(NamespaceError::Mount(
837            last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
838        ))
839    }
840
841    /// List directory entries. Walk + open(read) + readdir + clunk.
842    ///
843    /// With union mounts, merges readdir results from all targets at the prefix,
844    /// deduplicating by name (first occurrence wins, preserving bind order).
845    pub async fn ls(&self, path: &str, caller: &Subject) -> Result<Vec<DirEntry>, NamespaceError> {
846        self.enforce(caller, path, NamespaceAction::Read).await?;
847        // Special case: ls "/" shows all mount prefixes as directories.
848        if path == "/" || path.is_empty() {
849            return Ok(self.root_dir_entries());
850        }
851
852        match self.resolve(path) {
853            Ok((targets, remainder)) => {
854                let components: Vec<&str> = split_path(&remainder);
855                let mut seen = std::collections::HashSet::new();
856                let mut merged = Vec::new();
857                let mut any_ok = false;
858                for mount in targets {
859                    if let Ok(mut fid) = mount.walk(&components, caller).await {
860                        if mount.open(&mut fid, 0, caller).await.is_ok() {
861                            if let Ok(entries) = mount.readdir(&fid, caller).await {
862                                any_ok = true;
863                                for entry in entries {
864                                    if seen.insert(entry.name.clone()) {
865                                        merged.push(entry);
866                                    }
867                                }
868                            }
869                        }
870                        mount.clunk(fid, caller).await;
871                    }
872                }
873                if any_ok {
874                    Ok(merged)
875                } else {
876                    Err(NamespaceError::Mount(MountError::NotFound(path.to_owned())))
877                }
878            }
879            Err(_) => {
880                // Path doesn't match any mount prefix directly. Check if it's an
881                // intermediate directory — i.e., some mount's prefix starts with
882                // "{path}/". Synthesize directory entries from sub-mount components.
883                let normalized = normalize_path(path);
884                let prefix_with_slash = format!("{}/", normalized);
885                let mut seen = std::collections::HashSet::new();
886                let mut entries = Vec::new();
887                for m in &self.mounts {
888                    if let Some(rest) = m.prefix.strip_prefix(&prefix_with_slash[..]) {
889                        let next = rest.split('/').next().unwrap_or("");
890                        if !next.is_empty() && seen.insert(next.to_owned()) {
891                            entries.push(DirEntry {
892                                name: next.to_owned(),
893                                is_dir: true,
894                                size: 0,
895                                stat: None,
896                            });
897                        }
898                    }
899                }
900                if entries.is_empty() {
901                    Err(NamespaceError::Mount(MountError::NotFound(path.to_owned())))
902                } else {
903                    Ok(entries)
904                }
905            }
906        }
907    }
908
909    /// Resolve a path to its mount targets (bind order) and the path components
910    /// **relative to the matched mount root**.
911    ///
912    /// This is the public, fid-level routing entry point used by FS-A's
913    /// `Namespace → FileSystem` down-adapter, which (unlike `cat`/`ls`/`echo`)
914    /// drives `walk`/`open`/`read`/`write`/`clunk` on the mount itself and needs
915    /// the raw targets plus the component slice. Returns the targets in bind
916    /// order (`Before` first, `After` last) so the caller can apply the same
917    /// union/fallthrough policy the convenience helpers do.
918    ///
919    /// Because a raw [`MountTarget`] exposes the complete mount capability,
920    /// including writes, an armed namespace authorizes the dedicated
921    /// [`NamespaceAction::ResolveHandle`] action before returning any target.
922    /// Missing clearance, a missing object label, or policy denial therefore
923    /// fails closed at the capability boundary. A dormant namespace remains a
924    /// pass-through.
925    ///
926    /// `path` is normalised (`.`/`..` resolved, leading `/` enforced) before the
927    /// longest-prefix match, identical to the convenience helpers.
928    ///
929    /// Async because an armed PEP revalidates credential-bearing cached
930    /// subject authority against the canonical revocation authority on every
931    /// call. The sync FUSE/vhost-user plane cannot await and uses
932    /// [`Self::resolve_targets_dormant`] instead.
933    pub async fn resolve_targets(
934        &self,
935        path: &str,
936        caller: &Subject,
937    ) -> Result<(Vec<MountTarget>, Vec<String>), NamespaceError> {
938        self.enforce(caller, path, NamespaceAction::ResolveHandle)
939            .await?;
940        self.route_targets(path)
941    }
942
943    /// Resolve only read capabilities after the mandatory read PEP check.
944    /// The returned wrapper cannot expose write, create, or a raw mount target.
945    pub async fn resolve_read_targets(
946        &self,
947        path: &str,
948        caller: &Subject,
949    ) -> Result<(Vec<ReadMountTarget>, Vec<String>), NamespaceError> {
950        self.enforce(caller, path, NamespaceAction::Read).await?;
951        let (targets, relative) = self.route_targets(path)?;
952        Ok((targets.into_iter().map(ReadMountTarget).collect(), relative))
953    }
954
955    /// Recheck read authority for an already-walked fid on every operation.
956    pub async fn authorize_read_path(
957        &self,
958        path: &str,
959        caller: &Subject,
960    ) -> Result<(), NamespaceError> {
961        self.enforce(caller, path, NamespaceAction::Read).await
962    }
963
964    /// Sync routing entry point for planes that serve only dormant (PEP-less)
965    /// namespaces from sync callbacks — the FUSE/vhost-user-fs session loop
966    /// (`hyprstream-vfs-server` over fuse-backend-rs) has no async frame per
967    /// operation, and the authorization revalidation requires an authority
968    /// RPC. An ARMED namespace therefore fails closed on every route through
969    /// this entry point: a plane that cannot revalidate cached authority
970    /// serves nothing rather than serving stale authority.
971    pub fn resolve_targets_dormant(
972        &self,
973        path: &str,
974        caller: &Subject,
975    ) -> Result<(Vec<MountTarget>, Vec<String>), NamespaceError> {
976        if self.pep_armed() {
977            return Err(NamespaceError::Denied(
978                NamespaceAction::ResolveHandle,
979                format!(
980                    "'{}': sync plane cannot revalidate subject authority",
981                    caller.name().unwrap_or("<anonymous>")
982                ),
983            ));
984        }
985        self.route_targets(path)
986    }
987
988    /// Longest-prefix routing shared by the enforcing and dormant entry
989    /// points.
990    fn route_targets(&self, path: &str) -> Result<(Vec<MountTarget>, Vec<String>), NamespaceError> {
991        let (targets, remainder) = self.resolve(path)?;
992        let components = split_path(&remainder)
993            .into_iter()
994            .map(str::to_owned)
995            .collect();
996        Ok((targets.to_vec(), components))
997    }
998
999    /// Whether `path` is an *intermediate* directory — a path that is not itself
1000    /// a mount prefix but is a strict ancestor of one (e.g. `/srv` when only
1001    /// `/srv/model` is mounted). Used by the down-adapter to synthesise
1002    /// directory inodes for the parts of the tree the namespace spans implicitly.
1003    ///
1004    /// Returns the synthetic child directory names if so (deduped, no order
1005    /// guarantee), or `None` if `path` is neither a mount nor an ancestor.
1006    pub fn intermediate_children(&self, path: &str) -> Option<Vec<String>> {
1007        let normalized = normalize_path(path);
1008        // A real mount prefix is not "intermediate".
1009        if self.mounts.iter().any(|m| m.prefix == normalized) {
1010            return None;
1011        }
1012        let prefix_with_slash = if normalized == "/" {
1013            "/".to_owned()
1014        } else {
1015            format!("{normalized}/")
1016        };
1017        let mut seen = std::collections::HashSet::new();
1018        let mut names = Vec::new();
1019        for m in &self.mounts {
1020            if let Some(rest) = m.prefix.strip_prefix(&prefix_with_slash[..]) {
1021                let next = rest.split('/').next().unwrap_or("");
1022                if !next.is_empty() && seen.insert(next.to_owned()) {
1023                    names.push(next.to_owned());
1024                }
1025            }
1026        }
1027        if names.is_empty() {
1028            None
1029        } else {
1030            Some(names)
1031        }
1032    }
1033
1034    // ── Internal ────────────────────────────────────────────────────────────
1035
1036    /// Resolve a path to (list of MountTargets, remainder after prefix).
1037    ///
1038    /// Returns targets in bind order (Before targets first, After targets last).
1039    fn resolve(&self, path: &str) -> Result<(&[MountTarget], String), NamespaceError> {
1040        self.resolve_entry(path)
1041            .map(|(entry, remainder)| (&entry.targets[..], remainder))
1042    }
1043
1044    /// Resolve a path to its owning `MountEntry` (which carries the designated
1045    /// copy-up upper, if any) plus the remainder after the matched prefix.
1046    fn resolve_entry(&self, path: &str) -> Result<(&MountEntry, String), NamespaceError> {
1047        let path = normalize_path(path);
1048
1049        for entry in &self.mounts {
1050            // A root mount ("/") is the catch-all: every path resolves to it
1051            // with the full path as remainder. Guarded specially because
1052            // `format!("{}/", "/")` would be "//", which `starts_with` never
1053            // matches — so a `/`-rooted rootfs (FS-D) would otherwise be unreachable.
1054            if entry.prefix == "/" {
1055                return Ok((entry, path));
1056            }
1057            if path == entry.prefix || path.starts_with(&format!("{}/", entry.prefix)) {
1058                let remainder = path[entry.prefix.len()..].to_owned();
1059                return Ok((entry, remainder));
1060            }
1061        }
1062
1063        Err(NamespaceError::Mount(MountError::NotFound(path)))
1064    }
1065
1066    /// Generate root directory entries from mount prefixes.
1067    fn root_dir_entries(&self) -> Vec<DirEntry> {
1068        let mut seen = std::collections::HashSet::new();
1069        let mut entries = Vec::new();
1070        for m in &self.mounts {
1071            // Extract the first path component after '/'.
1072            let first = m
1073                .prefix
1074                .trim_start_matches('/')
1075                .split('/')
1076                .next()
1077                .unwrap_or("");
1078            if !first.is_empty() && seen.insert(first.to_owned()) {
1079                entries.push(DirEntry {
1080                    name: first.to_owned(),
1081                    is_dir: true,
1082                    size: 0,
1083                    stat: None,
1084                });
1085            }
1086        }
1087        entries
1088    }
1089}
1090
1091impl Default for Namespace {
1092    fn default() -> Self {
1093        Self::new()
1094    }
1095}
1096
1097// ─────────────────────────────────────────────────────────────────────────────
1098// Helpers
1099// ─────────────────────────────────────────────────────────────────────────────
1100
1101fn normalize_prefix(prefix: &str) -> String {
1102    let p = if prefix.starts_with('/') {
1103        prefix.to_owned()
1104    } else {
1105        format!("/{prefix}")
1106    };
1107    // Remove trailing slash.
1108    if p.len() > 1 && p.ends_with('/') {
1109        p[..p.len() - 1].to_owned()
1110    } else {
1111        p
1112    }
1113}
1114
1115/// Normalize a path: ensure leading `/`, resolve `.` and `..` components, remove trailing `/`.
1116fn normalize_path(path: &str) -> String {
1117    let path = if path.starts_with('/') {
1118        path.to_owned()
1119    } else {
1120        format!("/{path}")
1121    };
1122    let mut parts: Vec<&str> = Vec::new();
1123    for seg in path.split('/') {
1124        match seg {
1125            "" | "." => {}
1126            ".." => {
1127                parts.pop();
1128            }
1129            s => parts.push(s),
1130        }
1131    }
1132    if parts.is_empty() {
1133        "/".to_owned()
1134    } else {
1135        format!("/{}", parts.join("/"))
1136    }
1137}
1138
1139fn split_path(path: &str) -> Vec<&str> {
1140    path.split('/')
1141        .filter(|s| !s.is_empty() && *s != "." && *s != "..")
1142        .collect()
1143}
1144
1145// ─────────────────────────────────────────────────────────────────────────────
1146// Tests
1147// ─────────────────────────────────────────────────────────────────────────────
1148
1149#[cfg(all(test, not(target_arch = "wasm32")))]
1150#[allow(clippy::unwrap_used, clippy::disallowed_types)]
1151mod tests {
1152    use super::*;
1153    use crate::mount::{Fid, MountError, Stat};
1154    use async_trait::async_trait;
1155    use std::collections::HashMap;
1156
1157    /// Simple in-memory Mount for testing.
1158    struct MemMount {
1159        files: HashMap<String, Vec<u8>>,
1160    }
1161
1162    impl MemMount {
1163        fn new(files: Vec<(&str, &[u8])>) -> Self {
1164            Self {
1165                files: files
1166                    .into_iter()
1167                    .map(|(k, v)| (k.to_owned(), v.to_vec()))
1168                    .collect(),
1169            }
1170        }
1171    }
1172
1173    struct MemFid {
1174        path: String,
1175        is_open: bool,
1176    }
1177
1178    #[async_trait]
1179    impl Mount for MemMount {
1180        async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
1181            let path = components.join("/");
1182            Ok(Fid::new(MemFid {
1183                path,
1184                is_open: false,
1185            }))
1186        }
1187
1188        async fn open(
1189            &self,
1190            fid: &mut Fid,
1191            _mode: u8,
1192            _caller: &Subject,
1193        ) -> Result<(), MountError> {
1194            let inner = fid
1195                .downcast_mut::<MemFid>()
1196                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1197            inner.is_open = true;
1198            Ok(())
1199        }
1200
1201        async fn read(
1202            &self,
1203            fid: &Fid,
1204            offset: u64,
1205            _count: u32,
1206            _caller: &Subject,
1207        ) -> Result<Vec<u8>, MountError> {
1208            let inner = fid
1209                .downcast_ref::<MemFid>()
1210                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1211            match self.files.get(&inner.path) {
1212                Some(data) => {
1213                    let start = offset as usize;
1214                    if start >= data.len() {
1215                        Ok(vec![])
1216                    } else {
1217                        Ok(data[start..].to_vec())
1218                    }
1219                }
1220                None => Err(MountError::NotFound(inner.path.clone())),
1221            }
1222        }
1223
1224        async fn write(
1225            &self,
1226            _fid: &Fid,
1227            _offset: u64,
1228            data: &[u8],
1229            _caller: &Subject,
1230        ) -> Result<u32, MountError> {
1231            Ok(data.len() as u32)
1232        }
1233
1234        async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
1235            let inner = fid
1236                .downcast_ref::<MemFid>()
1237                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1238            let prefix = if inner.path.is_empty() {
1239                String::new()
1240            } else {
1241                format!("{}/", inner.path)
1242            };
1243            let mut entries = Vec::new();
1244            for key in self.files.keys() {
1245                if let Some(rest) = key.strip_prefix(&prefix) {
1246                    if !rest.contains('/') {
1247                        entries.push(DirEntry {
1248                            name: rest.to_owned(),
1249                            is_dir: false,
1250                            size: 0,
1251                            stat: None,
1252                        });
1253                    }
1254                }
1255            }
1256            Ok(entries)
1257        }
1258
1259        async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
1260            let inner = fid
1261                .downcast_ref::<MemFid>()
1262                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1263            Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
1264        }
1265
1266        async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
1267    }
1268
1269    fn test_subject() -> Subject {
1270        Subject::new("test")
1271    }
1272
1273    #[tokio::test]
1274    async fn mount_and_cat() {
1275        let mut ns = Namespace::new();
1276        let mount: MountTarget = Arc::new(MemMount::new(vec![("temperature", b"0.7\n")]));
1277        ns.mount("/config", mount).unwrap();
1278
1279        let data = ns
1280            .cat("/config/temperature", &test_subject())
1281            .await
1282            .unwrap();
1283        assert_eq!(data, b"0.7\n");
1284    }
1285
1286    #[tokio::test]
1287    async fn mount_and_ls_root() {
1288        let mut ns = Namespace::new();
1289        ns.mount("/srv/model", Arc::new(MemMount::new(vec![])) as MountTarget)
1290            .unwrap();
1291        ns.mount("/srv/mcp", Arc::new(MemMount::new(vec![])) as MountTarget)
1292            .unwrap();
1293        ns.mount("/config", Arc::new(MemMount::new(vec![])) as MountTarget)
1294            .unwrap();
1295
1296        let entries = ns.ls("/", &test_subject()).await.unwrap();
1297        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
1298        assert!(names.contains(&"srv"));
1299        assert!(names.contains(&"config"));
1300    }
1301
1302    #[tokio::test]
1303    async fn longest_prefix_match() {
1304        let mut ns = Namespace::new();
1305        let srv: MountTarget = Arc::new(MemMount::new(vec![("status", b"ok")]));
1306        let nested: MountTarget = Arc::new(MemMount::new(vec![("status", b"loaded")]));
1307        ns.mount("/srv", srv).unwrap();
1308        ns.mount("/srv/model", nested).unwrap();
1309
1310        let data = ns.cat("/srv/model/status", &test_subject()).await.unwrap();
1311        assert_eq!(data, b"loaded");
1312    }
1313
1314    #[test]
1315    fn reserved_path_allows_mount() {
1316        let mut ns = Namespace::new();
1317        let mount: MountTarget = Arc::new(MemMount::new(vec![]));
1318        assert!(ns.mount("/config", mount).is_ok());
1319    }
1320
1321    #[tokio::test]
1322    async fn fork_and_unmount() {
1323        let mut ns = Namespace::new();
1324        ns.mount(
1325            "/srv/model",
1326            Arc::new(MemMount::new(vec![("status", b"loaded")])) as MountTarget,
1327        )
1328        .unwrap();
1329        ns.mount(
1330            "/srv/worker",
1331            Arc::new(MemMount::new(vec![])) as MountTarget,
1332        )
1333        .unwrap();
1334
1335        let mut child = ns.fork();
1336        let _ = child.unmount("/srv/worker");
1337
1338        assert_eq!(ns.mount_prefixes().len(), 2);
1339        assert_eq!(child.mount_prefixes().len(), 1);
1340        assert_eq!(child.mount_prefixes()[0], "/srv/model");
1341
1342        let data = child
1343            .cat("/srv/model/status", &test_subject())
1344            .await
1345            .unwrap();
1346        assert_eq!(data, b"loaded");
1347    }
1348
1349    /// A `/`-rooted mount (FS-D rootfs) is the catch-all: deep paths resolve to
1350    /// it, and longer prefixes still win over it (longest-prefix order).
1351    #[tokio::test]
1352    async fn root_mount_is_catch_all() {
1353        let mut ns = Namespace::new();
1354        let rootfs: MountTarget = Arc::new(MemMount::new(vec![("etc/hostname", b"host\n")]));
1355        ns.mount("/", rootfs).unwrap();
1356        let stream: MountTarget = Arc::new(MemMount::new(vec![("job/data", b"chunk")]));
1357        ns.mount("/stream", stream).unwrap();
1358
1359        // Deep rootfs path resolves through "/".
1360        assert_eq!(
1361            ns.cat("/etc/hostname", &test_subject()).await.unwrap(),
1362            b"host\n"
1363        );
1364        // A longer prefix still wins over the root catch-all.
1365        assert_eq!(
1366            ns.cat("/stream/job/data", &test_subject()).await.unwrap(),
1367            b"chunk"
1368        );
1369        // The rootfs itself is reachable at "/".
1370        assert!(ns.resolve_targets("/", &test_subject()).await.is_ok());
1371    }
1372
1373    #[tokio::test]
1374    async fn not_found() {
1375        let ns = Namespace::new();
1376        assert!(matches!(
1377            ns.cat("/nonexistent/file", &test_subject()).await,
1378            Err(NamespaceError::Mount(MountError::NotFound(_)))
1379        ));
1380    }
1381
1382    #[tokio::test]
1383    async fn echo_writes() {
1384        let mut ns = Namespace::new();
1385        let mount: MountTarget = Arc::new(MemMount::new(vec![("ctl", b"")]));
1386        ns.mount("/cmd", mount).unwrap();
1387
1388        assert!(ns
1389            .echo("/cmd/ctl", b"load qwen3:main", &test_subject())
1390            .await
1391            .is_ok());
1392    }
1393
1394    // ── New tests ──────────────────────────────────────────────────────────
1395
1396    /// Read loop must handle files larger than 64KB.
1397    #[tokio::test]
1398    async fn read_loop_large_file() {
1399        // Create a file > 64KB.
1400        let big_data = vec![0x42u8; 100 * 1024]; // 100 KB
1401        let mut ns = Namespace::new();
1402
1403        struct ChunkedMount {
1404            data: Vec<u8>,
1405        }
1406        struct ChunkedFid {
1407            _offset_limit: bool,
1408        }
1409
1410        #[async_trait]
1411        impl Mount for ChunkedMount {
1412            async fn walk(&self, _c: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
1413                Ok(Fid::new(ChunkedFid {
1414                    _offset_limit: false,
1415                }))
1416            }
1417            async fn open(
1418                &self,
1419                _fid: &mut Fid,
1420                _mode: u8,
1421                _caller: &Subject,
1422            ) -> Result<(), MountError> {
1423                Ok(())
1424            }
1425            async fn read(
1426                &self,
1427                _fid: &Fid,
1428                offset: u64,
1429                count: u32,
1430                _caller: &Subject,
1431            ) -> Result<Vec<u8>, MountError> {
1432                let start = offset as usize;
1433                if start >= self.data.len() {
1434                    return Ok(vec![]);
1435                }
1436                let end = std::cmp::min(start + count as usize, self.data.len());
1437                Ok(self.data[start..end].to_vec())
1438            }
1439            async fn write(
1440                &self,
1441                _fid: &Fid,
1442                _o: u64,
1443                d: &[u8],
1444                _c: &Subject,
1445            ) -> Result<u32, MountError> {
1446                Ok(d.len() as u32)
1447            }
1448            async fn readdir(&self, _fid: &Fid, _c: &Subject) -> Result<Vec<DirEntry>, MountError> {
1449                Ok(vec![])
1450            }
1451            async fn stat(
1452                &self,
1453                _fid: &Fid,
1454                _c: &Subject,
1455            ) -> Result<crate::mount::Stat, MountError> {
1456                Ok(crate::mount::Stat::unknown_qid(0, 0, String::new(), 0))
1457            }
1458            async fn clunk(&self, _fid: Fid, _c: &Subject) {}
1459        }
1460
1461        ns.mount(
1462            "/big",
1463            Arc::new(ChunkedMount {
1464                data: big_data.clone(),
1465            }) as MountTarget,
1466        )
1467        .unwrap();
1468        let result = ns.cat("/big/file", &test_subject()).await.unwrap();
1469        assert_eq!(result.len(), 100 * 1024);
1470        assert_eq!(result, big_data);
1471    }
1472
1473    /// OTRUNC mode pass-through.
1474    #[test]
1475    fn otrunc_mode_passthrough() {
1476        use crate::mount::{OTRUNC, OWRITE};
1477        // Verify the constants combine correctly.
1478        let mode = OWRITE | OTRUNC;
1479        assert_eq!(mode & 0x03, OWRITE);
1480        assert_ne!(mode & OTRUNC, 0);
1481    }
1482
1483    /// Path normalization with `..`.
1484    #[test]
1485    fn path_normalization_with_dotdot() {
1486        assert_eq!(normalize_path("/config/../srv/model"), "/srv/model");
1487        assert_eq!(normalize_path("/config/./status"), "/config/status");
1488        assert_eq!(normalize_path("//config///status"), "/config/status");
1489        assert_eq!(normalize_path("/a/b/c/../../d"), "/a/d");
1490        assert_eq!(normalize_path("/.."), "/");
1491    }
1492
1493    /// Normalize path resolves before prefix matching in resolve().
1494    #[tokio::test]
1495    async fn resolve_with_dotdot_path() {
1496        let mut ns = Namespace::new();
1497        ns.mount(
1498            "/srv/model",
1499            Arc::new(MemMount::new(vec![("status", b"ok")])) as MountTarget,
1500        )
1501        .unwrap();
1502
1503        // /config/../srv/model/status should normalize to /srv/model/status
1504        let data = ns
1505            .cat("/config/../srv/model/status", &test_subject())
1506            .await
1507            .unwrap();
1508        assert_eq!(data, b"ok");
1509    }
1510
1511    // ── Bind / union directory tests ──────────────────────────────────────
1512
1513    #[tokio::test]
1514    async fn bind_before_walk_tries_new_mount_first() {
1515        let mut ns = Namespace::new();
1516        // Original mount has "status" = "original"
1517        let orig: MountTarget = Arc::new(MemMount::new(vec![("status", b"original")]));
1518        ns.mount("/bin", orig).unwrap();
1519
1520        // Bind Before: new mount has "status" = "override"
1521        let overlay: MountTarget = Arc::new(MemMount::new(vec![("status", b"override")]));
1522        ns.bind_mount("/bin", overlay, BindFlag::Before).unwrap();
1523
1524        let data = ns.cat("/bin/status", &test_subject()).await.unwrap();
1525        assert_eq!(data, b"override");
1526    }
1527
1528    #[tokio::test]
1529    async fn bind_after_walk_tries_existing_first() {
1530        let mut ns = Namespace::new();
1531        let orig: MountTarget = Arc::new(MemMount::new(vec![("status", b"original")]));
1532        ns.mount("/bin", orig).unwrap();
1533
1534        // Bind After: new mount also has "status", but original should win.
1535        let extra: MountTarget = Arc::new(MemMount::new(vec![("status", b"extra")]));
1536        ns.bind_mount("/bin", extra, BindFlag::After).unwrap();
1537
1538        let data = ns.cat("/bin/status", &test_subject()).await.unwrap();
1539        assert_eq!(data, b"original");
1540    }
1541
1542    #[tokio::test]
1543    async fn bind_after_fallback_to_new_mount() {
1544        let mut ns = Namespace::new();
1545        // Original has only "cat"
1546        let orig: MountTarget = Arc::new(MemMount::new(vec![("cat", b"cat-impl")]));
1547        ns.mount("/bin", orig).unwrap();
1548
1549        // Bind After: new mount has "mytool" (not in original)
1550        let extra: MountTarget = Arc::new(MemMount::new(vec![("mytool", b"mytool-impl")]));
1551        ns.bind_mount("/bin", extra, BindFlag::After).unwrap();
1552
1553        // cat resolves from original
1554        let data = ns.cat("/bin/cat", &test_subject()).await.unwrap();
1555        assert_eq!(data, b"cat-impl");
1556
1557        // mytool falls through to the After mount
1558        let data = ns.cat("/bin/mytool", &test_subject()).await.unwrap();
1559        assert_eq!(data, b"mytool-impl");
1560    }
1561
1562    #[tokio::test]
1563    async fn bind_before_fallback_to_existing() {
1564        let mut ns = Namespace::new();
1565        let orig: MountTarget = Arc::new(MemMount::new(vec![("cat", b"cat-impl")]));
1566        ns.mount("/bin", orig).unwrap();
1567
1568        // Bind Before: new mount has "newtool" only
1569        let overlay: MountTarget = Arc::new(MemMount::new(vec![("newtool", b"newtool-impl")]));
1570        ns.bind_mount("/bin", overlay, BindFlag::Before).unwrap();
1571
1572        // "cat" falls through to existing mount
1573        let data = ns.cat("/bin/cat", &test_subject()).await.unwrap();
1574        assert_eq!(data, b"cat-impl");
1575
1576        // "newtool" found in Before mount
1577        let data = ns.cat("/bin/newtool", &test_subject()).await.unwrap();
1578        assert_eq!(data, b"newtool-impl");
1579    }
1580
1581    #[tokio::test]
1582    async fn union_readdir_merges_entries() {
1583        let mut ns = Namespace::new();
1584        let mount_a: MountTarget = Arc::new(MemMount::new(vec![("cat", b""), ("ls", b"")]));
1585        ns.mount("/bin", mount_a).unwrap();
1586
1587        let mount_b: MountTarget = Arc::new(MemMount::new(vec![("mytool", b""), ("cat", b"")]));
1588        ns.bind_mount("/bin", mount_b, BindFlag::After).unwrap();
1589
1590        let entries = ns.ls("/bin", &test_subject()).await.unwrap();
1591        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
1592
1593        // Should have "cat", "ls", and "mytool" — "cat" should not be duplicated.
1594        assert!(names.contains(&"cat"));
1595        assert!(names.contains(&"ls"));
1596        assert!(names.contains(&"mytool"));
1597        assert_eq!(names.iter().filter(|&&n| n == "cat").count(), 1);
1598    }
1599
1600    #[tokio::test]
1601    async fn bind_replace_still_works() {
1602        let mut ns = Namespace::new();
1603        let orig: MountTarget = Arc::new(MemMount::new(vec![("status", b"original")]));
1604        ns.mount("/bin", orig).unwrap();
1605
1606        // Add an After mount
1607        let extra: MountTarget = Arc::new(MemMount::new(vec![("extra", b"x")]));
1608        ns.bind_mount("/bin", extra, BindFlag::After).unwrap();
1609
1610        // Replace should clear all targets at /bin
1611        let replacement: MountTarget = Arc::new(MemMount::new(vec![("status", b"replaced")]));
1612        ns.mount("/bin", replacement).unwrap();
1613
1614        let data = ns.cat("/bin/status", &test_subject()).await.unwrap();
1615        assert_eq!(data, b"replaced");
1616
1617        // "extra" should be gone (replaced)
1618        assert!(ns.cat("/bin/extra", &test_subject()).await.is_err());
1619    }
1620
1621    // ── Intermediate directory synthesis ─────────────────────────────────────
1622
1623    /// `ls /srv` should synthesize directory entries when mounts exist at
1624    /// `/srv/model` but not at `/srv` itself.
1625    ///
1626    /// This catches the bug where intermediate paths between root and mount
1627    /// points returned "not found".
1628    #[tokio::test]
1629    async fn ls_intermediate_directory() {
1630        let mut ns = Namespace::new();
1631        let mount = Arc::new(MemMount::new(vec![("status", b"ok")]));
1632        ns.mount("/srv/model", mount).unwrap();
1633        let lang_mount = Arc::new(MemMount::new(vec![("interp", b"tcl")]));
1634        ns.mount("/lang/tcl", lang_mount).unwrap();
1635
1636        // /srv is not a mount point but /srv/model is — ls should synthesize.
1637        let entries = ns.ls("/srv", &test_subject()).await.unwrap();
1638        assert_eq!(entries.len(), 1);
1639        assert_eq!(entries[0].name, "model");
1640        assert!(entries[0].is_dir);
1641
1642        // /lang is not a mount point but /lang/tcl is — same pattern.
1643        let entries = ns.ls("/lang", &test_subject()).await.unwrap();
1644        assert_eq!(entries.len(), 1);
1645        assert_eq!(entries[0].name, "tcl");
1646        assert!(entries[0].is_dir);
1647
1648        // /nonexistent has no mounts beneath it — still errors.
1649        assert!(ns.ls("/nonexistent", &test_subject()).await.is_err());
1650    }
1651
1652    /// Multiple mounts under the same intermediate prefix synthesize correctly.
1653    #[tokio::test]
1654    async fn ls_intermediate_multiple_children() {
1655        let mut ns = Namespace::new();
1656        ns.mount("/a/b", Arc::new(MemMount::new(vec![("x", b"")])))
1657            .unwrap();
1658        ns.mount("/a/c", Arc::new(MemMount::new(vec![("y", b"")])))
1659            .unwrap();
1660        ns.mount("/a/d/e", Arc::new(MemMount::new(vec![("z", b"")])))
1661            .unwrap();
1662
1663        let entries = ns.ls("/a", &test_subject()).await.unwrap();
1664        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
1665        assert!(names.contains(&"b"));
1666        assert!(names.contains(&"c"));
1667        assert!(names.contains(&"d"));
1668        assert_eq!(entries.len(), 3);
1669
1670        // Deeper intermediate: /a/d should show "e"
1671        let entries = ns.ls("/a/d", &test_subject()).await.unwrap();
1672        assert_eq!(entries.len(), 1);
1673        assert_eq!(entries[0].name, "e");
1674    }
1675
1676    // ── Writable union / copy-up / create tests (#394) ──────────────────────
1677
1678    /// A read-only mount: reads succeed, all writes/create fail. This models
1679    /// the immutable `/oid` floor over which the writable upper is overlaid.
1680    struct ReadOnlyMemMount {
1681        files: HashMap<String, Vec<u8>>,
1682    }
1683
1684    impl ReadOnlyMemMount {
1685        fn new(files: Vec<(&str, &[u8])>) -> Self {
1686            Self {
1687                files: files
1688                    .into_iter()
1689                    .map(|(k, v)| (k.to_owned(), v.to_vec()))
1690                    .collect(),
1691            }
1692        }
1693    }
1694
1695    struct RoFid {
1696        path: String,
1697    }
1698
1699    #[async_trait]
1700    impl Mount for ReadOnlyMemMount {
1701        async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
1702            let path = components.join("/");
1703            Ok(Fid::new(RoFid { path }))
1704        }
1705        async fn open(&self, fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
1706            let base_mode = mode & 0x03;
1707            if base_mode == OWRITE {
1708                return Err(MountError::PermissionDenied("read-only floor".into()));
1709            }
1710            let _ = fid
1711                .downcast_ref::<RoFid>()
1712                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1713            Ok(())
1714        }
1715        async fn read(
1716            &self,
1717            fid: &Fid,
1718            offset: u64,
1719            _count: u32,
1720            _caller: &Subject,
1721        ) -> Result<Vec<u8>, MountError> {
1722            let inner = fid
1723                .downcast_ref::<RoFid>()
1724                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1725            match self.files.get(&inner.path) {
1726                Some(data) => {
1727                    let start = offset as usize;
1728                    if start >= data.len() {
1729                        Ok(vec![])
1730                    } else {
1731                        Ok(data[start..].to_vec())
1732                    }
1733                }
1734                None => Err(MountError::NotFound(inner.path.clone())),
1735            }
1736        }
1737        async fn write(
1738            &self,
1739            _fid: &Fid,
1740            _o: u64,
1741            _d: &[u8],
1742            _c: &Subject,
1743        ) -> Result<u32, MountError> {
1744            Err(MountError::PermissionDenied("read-only floor".into()))
1745        }
1746        async fn readdir(&self, _fid: &Fid, _c: &Subject) -> Result<Vec<DirEntry>, MountError> {
1747            Ok(vec![])
1748        }
1749        async fn stat(&self, fid: &Fid, _c: &Subject) -> Result<Stat, MountError> {
1750            let inner = fid
1751                .downcast_ref::<RoFid>()
1752                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1753            Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
1754        }
1755        async fn clunk(&self, _fid: Fid, _c: &Subject) {}
1756    }
1757
1758    /// A writable in-memory mount that persists writes and supports `create`.
1759    ///
1760    /// Unlike `MemMount` (which discards writes), this stores written bytes and
1761    /// honours `create` so the union copy-up path can be exercised end-to-end.
1762    struct WritableMemMount {
1763        files: std::sync::Mutex<HashMap<String, Vec<u8>>>,
1764    }
1765
1766    impl WritableMemMount {
1767        fn empty() -> Self {
1768            Self {
1769                files: std::sync::Mutex::new(HashMap::new()),
1770            }
1771        }
1772
1773        fn snapshot(&self) -> HashMap<String, Vec<u8>> {
1774            self.files.lock().unwrap().clone()
1775        }
1776    }
1777
1778    struct WritableFid {
1779        path: String,
1780        is_open: bool,
1781        mode: u8,
1782    }
1783
1784    #[async_trait]
1785    impl Mount for WritableMemMount {
1786        async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
1787            let path = components.join("/");
1788            Ok(Fid::new(WritableFid {
1789                path,
1790                is_open: false,
1791                mode: 0,
1792            }))
1793        }
1794
1795        async fn open(&self, fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
1796            let inner = fid
1797                .downcast_mut::<WritableFid>()
1798                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1799            let base_mode = mode & 0x03;
1800            // The root directory (empty path) always exists and is readable.
1801            if inner.path.is_empty() {
1802                inner.is_open = true;
1803                inner.mode = mode;
1804                return Ok(());
1805            }
1806            let files = self.files.lock().unwrap();
1807            if !files.contains_key(&inner.path) {
1808                return Err(MountError::NotFound(inner.path.clone()));
1809            }
1810            // Suppress unused-assignment lint when base_mode is unused otherwise.
1811            let _ = base_mode;
1812            inner.is_open = true;
1813            inner.mode = mode;
1814            Ok(())
1815        }
1816
1817        async fn read(
1818            &self,
1819            fid: &Fid,
1820            offset: u64,
1821            _count: u32,
1822            _caller: &Subject,
1823        ) -> Result<Vec<u8>, MountError> {
1824            let inner = fid
1825                .downcast_ref::<WritableFid>()
1826                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1827            let files = self.files.lock().unwrap();
1828            match files.get(&inner.path) {
1829                Some(data) => {
1830                    let start = offset as usize;
1831                    if start >= data.len() {
1832                        Ok(vec![])
1833                    } else {
1834                        Ok(data[start..].to_vec())
1835                    }
1836                }
1837                None => Err(MountError::NotFound(inner.path.clone())),
1838            }
1839        }
1840
1841        async fn write(
1842            &self,
1843            fid: &Fid,
1844            offset: u64,
1845            data: &[u8],
1846            _caller: &Subject,
1847        ) -> Result<u32, MountError> {
1848            let inner = fid
1849                .downcast_ref::<WritableFid>()
1850                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1851            let mut files = self.files.lock().unwrap();
1852            let entry = files.entry(inner.path.clone()).or_default();
1853            let start = offset as usize;
1854            if start > entry.len() {
1855                entry.resize(start, 0);
1856            }
1857            let end = start + data.len();
1858            if end > entry.len() {
1859                entry.resize(end, 0);
1860            }
1861            entry[start..end].copy_from_slice(data);
1862            Ok(data.len() as u32)
1863        }
1864
1865        async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
1866            let inner = fid
1867                .downcast_ref::<WritableFid>()
1868                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1869            let prefix = if inner.path.is_empty() {
1870                String::new()
1871            } else {
1872                format!("{}/", inner.path)
1873            };
1874            let files = self.files.lock().unwrap();
1875            let mut entries = Vec::new();
1876            for key in files.keys() {
1877                if let Some(rest) = key.strip_prefix(&prefix) {
1878                    if !rest.contains('/') {
1879                        entries.push(DirEntry {
1880                            name: rest.to_owned(),
1881                            is_dir: false,
1882                            size: 0,
1883                            stat: None,
1884                        });
1885                    }
1886                }
1887            }
1888            Ok(entries)
1889        }
1890
1891        async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
1892            let inner = fid
1893                .downcast_ref::<WritableFid>()
1894                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1895            Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
1896        }
1897
1898        async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
1899
1900        /// Override the default `create` — this is the writable layer.
1901        async fn create(
1902            &self,
1903            fid: &mut Fid,
1904            name: &str,
1905            _perm: u32,
1906            mode: u8,
1907            _caller: &Subject,
1908        ) -> Result<Stat, MountError> {
1909            let inner = fid
1910                .downcast_mut::<WritableFid>()
1911                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1912            let child_path = if inner.path.is_empty() {
1913                name.to_owned()
1914            } else {
1915                format!("{}/{}", inner.path, name)
1916            };
1917            // Create empty file.
1918            self.files
1919                .lock()
1920                .unwrap()
1921                .insert(child_path.clone(), Vec::new());
1922            // Re-point the fid at the new file, opened.
1923            inner.path = child_path;
1924            inner.is_open = true;
1925            inner.mode = mode;
1926            Ok(Stat::unknown_qid(0, 0, name.to_owned(), 0))
1927        }
1928    }
1929
1930    /// `create` on the namespace lands in the first writable target.
1931    #[tokio::test]
1932    async fn namespace_create_lands_in_writable_target() {
1933        let mut ns = Namespace::new();
1934        let writable: MountTarget = Arc::new(WritableMemMount::empty());
1935        ns.mount("/wt", writable).unwrap();
1936
1937        let caller = test_subject();
1938        let stat = ns.create("/wt/newfile.txt", 0o644, &caller).await.unwrap();
1939        assert_eq!(stat.name, "newfile.txt");
1940
1941        // The file exists and is empty.
1942        let data = ns.cat("/wt/newfile.txt", &caller).await.unwrap();
1943        assert_eq!(data, b"");
1944    }
1945
1946    /// Copy-up: a write to a file that exists only in a read-only lower layer
1947    /// copies the lower bytes into the writable upper layer first (#394).
1948    #[tokio::test]
1949    async fn copy_up_writes_to_upper_when_lower_is_readonly() {
1950        let mut ns = Namespace::new();
1951
1952        // Read-only floor (the immutable /oid layer): reads ok, writes denied.
1953        let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("config", b"floor-bytes")]));
1954        // Writable upper, empty to start. Keep a typed handle so the test can
1955        // inspect the upper layer's contents after the copy-up.
1956        let upper = Arc::new(WritableMemMount::empty());
1957
1958        // Bind the floor first (lower), upper after — readdir merges, writes go
1959        // to the first writable target that accepts them.
1960        ns.bind_mount("/union", floor, BindFlag::Replace).unwrap();
1961        ns.bind_mount("/union", Arc::clone(&upper) as MountTarget, BindFlag::After)
1962            .unwrap();
1963
1964        let caller = test_subject();
1965
1966        // Before write: cat reads from the floor.
1967        let before = ns.cat("/union/config", &caller).await.unwrap();
1968        assert_eq!(before, b"floor-bytes");
1969
1970        // Pass 1 (direct OWRITE): floor rejects (read-only), upper rejects
1971        // (file doesn't exist yet). Pass 2 (copy-up): reads floor bytes, creates
1972        // + writes into upper. Result: the upper holds the new content.
1973        ns.echo("/union/config", b"new-bytes", &caller)
1974            .await
1975            .unwrap();
1976
1977        let upper_files = upper.snapshot();
1978        assert!(upper_files.contains_key("config"));
1979        assert_eq!(upper_files.get("config").unwrap(), b"new-bytes");
1980    }
1981
1982    /// Copy-up leaves the immutable floor untouched.
1983    #[tokio::test]
1984    async fn copy_up_does_not_mutate_floor() {
1985        let mut ns = Namespace::new();
1986        // Read-only floor carrying existing content.
1987        let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("data", b"immutable")]));
1988        let upper = Arc::new(WritableMemMount::empty());
1989
1990        ns.bind_mount("/u", floor, BindFlag::Replace).unwrap();
1991        ns.bind_mount("/u", Arc::clone(&upper) as MountTarget, BindFlag::After)
1992            .unwrap();
1993
1994        let caller = test_subject();
1995        ns.echo("/u/data", b"mutated", &caller).await.unwrap();
1996
1997        // Upper received the copy-up + write.
1998        let upper_files = upper.snapshot();
1999        assert_eq!(upper_files.get("data").unwrap(), b"mutated");
2000
2001        // Reading back returns the upper's version (bound After = tried after
2002        // the floor; cat tries floor first, but the floor still reads the
2003        // original immutable bytes — the upper is only surfaced once the floor
2004        // read fails or via readdir merge). The invariant we care about: the
2005        // floor was never mutated (it can't be — it's read-only).
2006        let floor_read = ns.cat("/u/data", &caller).await.unwrap();
2007        assert_eq!(floor_read, b"immutable");
2008    }
2009
2010    /// The default `create` returns NotSupported — existing Mount impls are
2011    /// unaffected by the trait addition.
2012    #[tokio::test]
2013    async fn default_create_returns_not_supported() {
2014        let mut ns = Namespace::new();
2015        let mount: MountTarget = Arc::new(MemMount::new(vec![]));
2016        ns.mount("/ro", mount).unwrap();
2017
2018        let caller = test_subject();
2019        let err = ns.create("/ro/anything", 0o644, &caller).await.unwrap_err();
2020        match err {
2021            NamespaceError::Mount(MountError::NotSupported(_)) => {}
2022            other => panic!("expected NotSupported, got {other:?}"),
2023        }
2024    }
2025
2026    // ── Designated copy-up upper (BindFlag::Upper) tests (#370) ──────────────
2027
2028    /// A writable mount that denies every op unless the caller is a specific
2029    /// subject. Models a MAC-mediated upper: copy-up threads the caller through
2030    /// the create+write, so a wrong subject must fail closed.
2031    struct SubjectGatedMount {
2032        allow: String,
2033        files: std::sync::Mutex<HashMap<String, Vec<u8>>>,
2034    }
2035
2036    impl SubjectGatedMount {
2037        fn new(allow: &str) -> Self {
2038            Self {
2039                allow: allow.to_owned(),
2040                files: std::sync::Mutex::new(HashMap::new()),
2041            }
2042        }
2043        fn snapshot(&self) -> HashMap<String, Vec<u8>> {
2044            self.files.lock().unwrap().clone()
2045        }
2046        fn check(&self, caller: &Subject) -> Result<(), MountError> {
2047            if caller.name() == Some(self.allow.as_str()) {
2048                Ok(())
2049            } else {
2050                Err(MountError::PermissionDenied("subject not permitted".into()))
2051            }
2052        }
2053    }
2054
2055    #[async_trait]
2056    impl Mount for SubjectGatedMount {
2057        async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
2058            Ok(Fid::new(WritableFid {
2059                path: components.join("/"),
2060                is_open: false,
2061                mode: 0,
2062            }))
2063        }
2064        async fn open(&self, fid: &mut Fid, mode: u8, caller: &Subject) -> Result<(), MountError> {
2065            let inner = fid
2066                .downcast_mut::<WritableFid>()
2067                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2068            if inner.path.is_empty() {
2069                inner.is_open = true;
2070                inner.mode = mode;
2071                return Ok(());
2072            }
2073            // Writing needs the permitted subject; a read of an existing file is
2074            // fine (this mount is only ever a lower in the deny test).
2075            if mode & 0x03 == OWRITE {
2076                self.check(caller)?;
2077            }
2078            if !self.files.lock().unwrap().contains_key(&inner.path) {
2079                return Err(MountError::NotFound(inner.path.clone()));
2080            }
2081            inner.is_open = true;
2082            inner.mode = mode;
2083            Ok(())
2084        }
2085        async fn read(
2086            &self,
2087            fid: &Fid,
2088            offset: u64,
2089            _count: u32,
2090            _caller: &Subject,
2091        ) -> Result<Vec<u8>, MountError> {
2092            let inner = fid
2093                .downcast_ref::<WritableFid>()
2094                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2095            match self.files.lock().unwrap().get(&inner.path) {
2096                Some(data) => {
2097                    let start = offset as usize;
2098                    if start >= data.len() {
2099                        Ok(vec![])
2100                    } else {
2101                        Ok(data[start..].to_vec())
2102                    }
2103                }
2104                None => Err(MountError::NotFound(inner.path.clone())),
2105            }
2106        }
2107        async fn write(
2108            &self,
2109            fid: &Fid,
2110            offset: u64,
2111            data: &[u8],
2112            caller: &Subject,
2113        ) -> Result<u32, MountError> {
2114            self.check(caller)?;
2115            let inner = fid
2116                .downcast_ref::<WritableFid>()
2117                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2118            let mut files = self.files.lock().unwrap();
2119            let entry = files.entry(inner.path.clone()).or_default();
2120            let start = offset as usize;
2121            let end = start + data.len();
2122            if end > entry.len() {
2123                entry.resize(end, 0);
2124            }
2125            entry[start..end].copy_from_slice(data);
2126            Ok(data.len() as u32)
2127        }
2128        async fn readdir(
2129            &self,
2130            _fid: &Fid,
2131            _caller: &Subject,
2132        ) -> Result<Vec<DirEntry>, MountError> {
2133            Ok(vec![])
2134        }
2135        async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
2136            let inner = fid
2137                .downcast_ref::<WritableFid>()
2138                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2139            Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
2140        }
2141        async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
2142        async fn create(
2143            &self,
2144            fid: &mut Fid,
2145            name: &str,
2146            _perm: u32,
2147            mode: u8,
2148            caller: &Subject,
2149        ) -> Result<Stat, MountError> {
2150            self.check(caller)?;
2151            let inner = fid
2152                .downcast_mut::<WritableFid>()
2153                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2154            let child = if inner.path.is_empty() {
2155                name.to_owned()
2156            } else {
2157                format!("{}/{}", inner.path, name)
2158            };
2159            self.files.lock().unwrap().insert(child.clone(), Vec::new());
2160            inner.path = child;
2161            inner.is_open = true;
2162            inner.mode = mode;
2163            Ok(Stat::unknown_qid(0, 0, name.to_owned(), 0))
2164        }
2165    }
2166
2167    /// A read-only mount that also lists its files via readdir, so union
2168    /// readdir-merge can be exercised. (`ReadOnlyMemMount` returns an empty
2169    /// readdir; this one reports its entries.)
2170    struct ReadOnlyReaddirMount {
2171        files: HashMap<String, Vec<u8>>,
2172    }
2173
2174    impl ReadOnlyReaddirMount {
2175        fn new(files: Vec<(&str, &[u8])>) -> Self {
2176            Self {
2177                files: files
2178                    .into_iter()
2179                    .map(|(k, v)| (k.to_owned(), v.to_vec()))
2180                    .collect(),
2181            }
2182        }
2183    }
2184
2185    #[async_trait]
2186    impl Mount for ReadOnlyReaddirMount {
2187        async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
2188            Ok(Fid::new(RoFid {
2189                path: components.join("/"),
2190            }))
2191        }
2192        async fn open(&self, fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
2193            if mode & 0x03 == OWRITE {
2194                return Err(MountError::PermissionDenied("read-only".into()));
2195            }
2196            let _ = fid
2197                .downcast_ref::<RoFid>()
2198                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2199            Ok(())
2200        }
2201        async fn read(
2202            &self,
2203            fid: &Fid,
2204            offset: u64,
2205            _count: u32,
2206            _caller: &Subject,
2207        ) -> Result<Vec<u8>, MountError> {
2208            let inner = fid
2209                .downcast_ref::<RoFid>()
2210                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2211            match self.files.get(&inner.path) {
2212                Some(data) => {
2213                    let start = offset as usize;
2214                    if start >= data.len() {
2215                        Ok(vec![])
2216                    } else {
2217                        Ok(data[start..].to_vec())
2218                    }
2219                }
2220                // The root dir (empty path) has no bytes but is a valid open target.
2221                None if inner.path.is_empty() => Ok(vec![]),
2222                None => Err(MountError::NotFound(inner.path.clone())),
2223            }
2224        }
2225        async fn write(
2226            &self,
2227            _fid: &Fid,
2228            _o: u64,
2229            _d: &[u8],
2230            _c: &Subject,
2231        ) -> Result<u32, MountError> {
2232            Err(MountError::PermissionDenied("read-only".into()))
2233        }
2234        async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
2235            let inner = fid
2236                .downcast_ref::<RoFid>()
2237                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2238            let prefix = if inner.path.is_empty() {
2239                String::new()
2240            } else {
2241                format!("{}/", inner.path)
2242            };
2243            let mut entries = Vec::new();
2244            for key in self.files.keys() {
2245                if let Some(rest) = key.strip_prefix(&prefix) {
2246                    if !rest.contains('/') {
2247                        entries.push(DirEntry {
2248                            name: rest.to_owned(),
2249                            is_dir: false,
2250                            size: 0,
2251                            stat: None,
2252                        });
2253                    }
2254                }
2255            }
2256            Ok(entries)
2257        }
2258        async fn stat(&self, fid: &Fid, _c: &Subject) -> Result<Stat, MountError> {
2259            let inner = fid
2260                .downcast_ref::<RoFid>()
2261                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2262            Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
2263        }
2264        async fn clunk(&self, _fid: Fid, _c: &Subject) {}
2265    }
2266
2267    /// Copy-up targets the *designated* upper, not merely the first writable
2268    /// target in bind order. Two writable targets are bound After the floor;
2269    /// only the one marked `BindFlag::Upper` must receive the copied-up file.
2270    #[tokio::test]
2271    async fn copy_up_targets_designated_upper_not_bind_order() {
2272        let mut ns = Namespace::new();
2273        let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("weights", b"shared-ro")]));
2274        // Two writable layers. `first` is bound earlier (would win the bind-order
2275        // heuristic); `chosen` is the explicitly designated upper.
2276        let first = Arc::new(WritableMemMount::empty());
2277        let chosen = Arc::new(WritableMemMount::empty());
2278
2279        ns.bind_mount("/m", floor, BindFlag::Replace).unwrap();
2280        ns.bind_mount("/m", Arc::clone(&first) as MountTarget, BindFlag::After)
2281            .unwrap();
2282        ns.bind_mount("/m", Arc::clone(&chosen) as MountTarget, BindFlag::Upper)
2283            .unwrap();
2284
2285        assert!(ns.has_designated_upper("/m"));
2286
2287        let caller = test_subject();
2288        ns.echo("/m/weights", b"tenant-edit", &caller)
2289            .await
2290            .unwrap();
2291
2292        // The copied-up file landed in the designated upper only.
2293        assert_eq!(chosen.snapshot().get("weights").unwrap(), b"tenant-edit");
2294        assert!(
2295            !first.snapshot().contains_key("weights"),
2296            "first writable must NOT receive the copy-up"
2297        );
2298    }
2299
2300    /// A write to a path already present in the upper goes straight to the
2301    /// upper (Pass 1 direct write) — no copy-up create is triggered.
2302    #[tokio::test]
2303    async fn write_to_existing_upper_file_skips_copy_up() {
2304        let mut ns = Namespace::new();
2305        let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("f", b"floor")]));
2306        let upper = Arc::new(WritableMemMount::empty());
2307        // Seed the upper with the file already present (same length as the new
2308        // write so the test mount's non-truncating write leaves no stale tail —
2309        // the point here is Pass-1 direct write, not truncation semantics).
2310        upper
2311            .files
2312            .lock()
2313            .unwrap()
2314            .insert("f".to_owned(), b"upperorig".to_vec());
2315
2316        ns.bind_mount("/x", floor, BindFlag::Replace).unwrap();
2317        ns.bind_mount("/x", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2318            .unwrap();
2319
2320        let caller = test_subject();
2321        ns.echo("/x/f", b"upper-new", &caller).await.unwrap();
2322
2323        assert_eq!(upper.snapshot().get("f").unwrap(), b"upper-new");
2324    }
2325
2326    /// A write to a brand-new path (in neither layer) creates it in the
2327    /// designated upper, unchanged from the pre-#370 create path.
2328    #[tokio::test]
2329    async fn write_new_path_creates_in_designated_upper() {
2330        let mut ns = Namespace::new();
2331        let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("existing", b"ro")]));
2332        let upper = Arc::new(WritableMemMount::empty());
2333
2334        ns.bind_mount("/n", floor, BindFlag::Replace).unwrap();
2335        ns.bind_mount("/n", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2336            .unwrap();
2337
2338        let caller = test_subject();
2339        // Pass 1 direct write fails (not present); no lower source either, so the
2340        // create path in the upper is exercised via create() then echo.
2341        ns.create("/n/fresh", 0o644, &caller).await.unwrap();
2342        ns.echo("/n/fresh", b"brand-new", &caller).await.unwrap();
2343
2344        assert_eq!(upper.snapshot().get("fresh").unwrap(), b"brand-new");
2345    }
2346
2347    /// After a copy-up, readdir/ls merges lower + upper and the copied file
2348    /// appears exactly once (deduped by name).
2349    #[tokio::test]
2350    async fn readdir_after_copy_up_shows_file_once() {
2351        let mut ns = Namespace::new();
2352        // Floor exposes `shared` via readdir; also readable so copy-up can source it.
2353        let floor: MountTarget =
2354            Arc::new(ReadOnlyReaddirMount::new(vec![("shared", b"floor-bytes")]));
2355        let upper = Arc::new(WritableMemMount::empty());
2356
2357        ns.bind_mount("/r", floor, BindFlag::Replace).unwrap();
2358        ns.bind_mount("/r", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2359            .unwrap();
2360
2361        let caller = test_subject();
2362        ns.echo("/r/shared", b"edited", &caller).await.unwrap();
2363
2364        let entries = ns.ls("/r", &caller).await.unwrap();
2365        let shared_count = entries.iter().filter(|e| e.name == "shared").count();
2366        assert_eq!(
2367            shared_count, 1,
2368            "copied-up file must appear once, not once per layer"
2369        );
2370    }
2371
2372    /// Copy-up threads the caller through create+write, so a denied subject on
2373    /// the upper fails closed — the copy-up does not succeed with a wrong
2374    /// subject, and the upper stays empty.
2375    #[tokio::test]
2376    async fn copy_up_fails_closed_for_denied_subject() {
2377        let mut ns = Namespace::new();
2378        let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("secret", b"floor")]));
2379        // Upper only permits subject "alice".
2380        let upper = Arc::new(SubjectGatedMount::new("alice"));
2381
2382        ns.bind_mount("/g", floor, BindFlag::Replace).unwrap();
2383        ns.bind_mount("/g", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2384            .unwrap();
2385
2386        // "mallory" is not permitted on the upper.
2387        let mallory = Subject::new("mallory");
2388        let err = ns.echo("/g/secret", b"evil", &mallory).await.unwrap_err();
2389        match err {
2390            NamespaceError::Mount(MountError::PermissionDenied(_)) => {}
2391            other => panic!("expected PermissionDenied (fail closed), got {other:?}"),
2392        }
2393        assert!(
2394            upper.snapshot().is_empty(),
2395            "denied copy-up must not write the upper"
2396        );
2397
2398        // The permitted subject succeeds — confirms the deny was about the
2399        // subject, not a broken path.
2400        let alice = Subject::new("alice");
2401        ns.echo("/g/secret", b"ok", &alice).await.unwrap();
2402        assert_eq!(upper.snapshot().get("secret").unwrap(), b"ok");
2403    }
2404
2405    /// Copy-up works through the `/` catch-all (the FS-D rootfs case): a
2406    /// `/`-rooted union of a read-only image lower + a designated writable
2407    /// upper copy-ups on write, and the designated-upper routing survives the
2408    /// catch-all's full-path remainder (`resolve_entry` returns the owning
2409    /// `MountEntry` — including `upper` — for the root mount, not just its
2410    /// target list).
2411    ///
2412    /// NOTE: uses a top-level file because namespace copy-up does not yet
2413    /// provision intermediate parent directories in the upper — nested-path
2414    /// copy-up (e.g. `etc/hostname`) fails on ANY prefix today (pre-existing,
2415    /// not catch-all-specific). Tracked with overlay v2 semantics in #656.
2416    #[tokio::test]
2417    async fn copy_up_through_root_catch_all() {
2418        let mut ns = Namespace::new();
2419        let image: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("hostname", b"worker\n")]));
2420        let upper = Arc::new(WritableMemMount::empty());
2421
2422        ns.bind_mount("/", image, BindFlag::Replace).unwrap();
2423        ns.bind_mount("/", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2424            .unwrap();
2425        assert!(ns.has_designated_upper("/"));
2426
2427        let caller = test_subject();
2428
2429        // Read-through to the RO lower via the catch-all.
2430        assert_eq!(ns.cat("/hostname", &caller).await.unwrap(), b"worker\n");
2431
2432        // Write to a lower-only path → copy-up into the designated upper,
2433        // routed via the MountEntry the catch-all branch returns.
2434        ns.echo("/hostname", b"tenant\n", &caller).await.unwrap();
2435        assert_eq!(upper.snapshot().get("hostname").unwrap(), b"tenant\n");
2436
2437        // The lower is untouched and the union now reads the upper's version.
2438        assert_eq!(ns.cat("/hostname", &caller).await.unwrap(), b"tenant\n");
2439
2440        // A longer prefix still wins over the root union (longest-prefix order
2441        // is unaffected by the Upper designation on "/").
2442        let stream: MountTarget = Arc::new(MemMount::new(vec![("job", b"chunk")]));
2443        ns.mount("/stream", stream).unwrap();
2444        assert_eq!(ns.cat("/stream/job", &caller).await.unwrap(), b"chunk");
2445    }
2446
2447    // ── MAC PEP integration (#1272) ──────────────────────────────────────────
2448
2449    use crate::mac_pep::{
2450        DenyAllNamespace, DenyAllSubjects, NamespaceAccessDecider, NamespaceAction, NamespacePep,
2451        SubjectContextResolver,
2452    };
2453    use hyprstream_rpc::auth::mac::{
2454        Assurance, CompartmentSet, Level, MacDecision, MacDenyReason, RpcObjectLabelResolver,
2455        SecurityContext, SecurityLabel, VerifiedKeyMaterial,
2456    };
2457
2458    fn sec_label(level: Level) -> SecurityLabel {
2459        SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY)
2460    }
2461    fn sec_ctx(level: Level) -> SecurityContext {
2462        SecurityContext::from_clearance(sec_label(level), VerifiedKeyMaterial::Classical)
2463    }
2464
2465    /// A resolver that admits one named subject at a fixed clearance.
2466    struct OneSubject {
2467        name: &'static str,
2468        ctx: SecurityContext,
2469    }
2470    #[async_trait::async_trait]
2471    impl SubjectContextResolver for OneSubject {
2472        async fn resolve(&self, s: &Subject) -> Option<SecurityContext> {
2473            (s.name() == Some(self.name)).then(|| self.ctx.clone())
2474        }
2475    }
2476
2477    /// Labels `/public/**` Public and everything else `None` (deny).
2478    struct PublicOnlyResolver;
2479    impl RpcObjectLabelResolver for PublicOnlyResolver {
2480        fn resolve(&self, service_domain: &str, _method: Option<&[u16]>) -> Option<SecurityLabel> {
2481            service_domain
2482                .strip_prefix("/public")
2483                .filter(|suffix| suffix.is_empty() || suffix.starts_with('/'))
2484                .map(|_| sec_label(Level::Public))
2485        }
2486    }
2487
2488    /// Read-floor decider: reads permitted when clearance dominates the label;
2489    /// all write/create/mount-class ops denied (write-direction pause).
2490    struct ReadFloorDecider;
2491    impl NamespaceAccessDecider for ReadFloorDecider {
2492        fn check(
2493            &self,
2494            ctx: Option<&SecurityContext>,
2495            object_label: Option<SecurityLabel>,
2496            action: NamespaceAction,
2497        ) -> MacDecision {
2498            let Some(ctx) = ctx else {
2499                return MacDecision::Deny(MacDenyReason::NoClearance);
2500            };
2501            let Some(object_label) = object_label else {
2502                return MacDecision::Deny(MacDenyReason::UnlabeledObject);
2503            };
2504            if action != NamespaceAction::Read {
2505                return MacDecision::Deny(MacDenyReason::FloorDeny);
2506            }
2507            if ctx.clearance().can_access(&object_label) {
2508                MacDecision::Permit
2509            } else {
2510                MacDecision::Deny(MacDenyReason::FloorDeny)
2511            }
2512        }
2513    }
2514
2515    fn deny_all_pep() -> Arc<NamespacePep> {
2516        Arc::new(NamespacePep::new(
2517            Arc::new(DenyAllSubjects),
2518            Arc::new(crate::mac_pep::DenyUnlabeledResolver),
2519            Arc::new(DenyAllNamespace),
2520        ))
2521    }
2522
2523    /// An un-armed namespace is the dormant status quo — all ops behave as
2524    /// before. This is the non-regression guard for the activation gate.
2525    #[tokio::test]
2526    async fn un_unarmed_namespace_is_unenforced() {
2527        let mut ns = Namespace::new();
2528        ns.mount(
2529            "/public",
2530            Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2531        )
2532        .unwrap();
2533        assert!(!ns.pep_armed());
2534        assert_eq!(
2535            ns.cat("/public/f", &Subject::new("anyone")).await.unwrap(),
2536            b"data"
2537        );
2538    }
2539
2540    /// Arming the fail-closed PEP denies every op for every subject — there is
2541    /// no permissive default once the monitor is installed (#547).
2542    #[tokio::test]
2543    async fn armed_deny_all_pep_denies_reads() {
2544        let mut ns = Namespace::new();
2545        ns.mount(
2546            "/public",
2547            Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2548        )
2549        .unwrap();
2550        ns.set_pep(deny_all_pep());
2551        assert!(ns.pep_armed());
2552        let err = ns
2553            .cat("/public/f", &Subject::new("anyone"))
2554            .await
2555            .unwrap_err();
2556        assert!(matches!(
2557            err,
2558            NamespaceError::Denied(NamespaceAction::Read, _)
2559        ));
2560    }
2561
2562    /// A caller cannot bypass an armed PEP by extracting the raw mount target.
2563    /// The capability boundary must deny before returning a handle when the
2564    /// caller has no verified clearance.
2565    #[tokio::test]
2566    async fn resolve_targets_denies_without_clearance() {
2567        let mut ns = Namespace::new();
2568        ns.mount(
2569            "/public",
2570            Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2571        )
2572        .unwrap();
2573        ns.set_pep(deny_all_pep());
2574
2575        assert!(matches!(
2576            ns.resolve_targets("/public/f", &Subject::new("unverified"))
2577                .await,
2578            Err(NamespaceError::Denied(NamespaceAction::ResolveHandle, _))
2579        ));
2580    }
2581
2582    /// A subject whose clearance dominates the object label is permitted a
2583    /// read; an unenrolled subject is denied (fail-closed clearance, #698).
2584    #[tokio::test]
2585    async fn armed_pep_permits_cleared_read_denies_uncleared() {
2586        let mut ns = Namespace::new();
2587        ns.mount(
2588            "/public",
2589            Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2590        )
2591        .unwrap();
2592        let pep = Arc::new(NamespacePep::new(
2593            Arc::new(OneSubject {
2594                name: "alice",
2595                ctx: sec_ctx(Level::Public),
2596            }),
2597            Arc::new(PublicOnlyResolver),
2598            Arc::new(ReadFloorDecider),
2599        ));
2600        ns.set_pep(pep);
2601
2602        // alice (Public clearance) reading /public/f ⇒ permit.
2603        assert_eq!(
2604            ns.cat("/public/f", &Subject::new("alice")).await.unwrap(),
2605            b"data"
2606        );
2607        // mallory is unenrolled ⇒ clearance unprovable ⇒ deny.
2608        let err = ns
2609            .cat("/public/f", &Subject::new("mallory"))
2610            .await
2611            .unwrap_err();
2612        assert!(matches!(
2613            err,
2614            NamespaceError::Denied(NamespaceAction::Read, _)
2615        ));
2616    }
2617
2618    /// Write-class ops deny under the read-floor decider (write-direction
2619    /// pause) even for a cleared subject — the PEP mediates writes too.
2620    #[tokio::test]
2621    async fn armed_pep_denies_writes_under_read_floor_decider() {
2622        let mut ns = Namespace::new();
2623        ns.mount(
2624            "/public",
2625            Arc::new(MemMount::new(vec![("ctl", b"")])) as MountTarget,
2626        )
2627        .unwrap();
2628        let pep = Arc::new(NamespacePep::new(
2629            Arc::new(OneSubject {
2630                name: "alice",
2631                ctx: sec_ctx(Level::Secret),
2632            }),
2633            Arc::new(PublicOnlyResolver),
2634            Arc::new(ReadFloorDecider),
2635        ));
2636        ns.set_pep(pep);
2637
2638        let err = ns
2639            .echo("/public/ctl", b"x", &Subject::new("alice"))
2640            .await
2641            .unwrap_err();
2642        assert!(matches!(
2643            err,
2644            NamespaceError::Denied(NamespaceAction::Write, _)
2645        ));
2646    }
2647
2648    /// An unlabeled object (no carrier resolves it) denies even for a cleared
2649    /// subject — the "no unlabeled-default-allow" invariant (design §1.2).
2650    #[tokio::test]
2651    async fn armed_pep_denies_unlabeled_object() {
2652        let mut ns = Namespace::new();
2653        // /secret has no label carrier ⇒ PublicOnlyResolver returns None.
2654        ns.mount(
2655            "/secret",
2656            Arc::new(MemMount::new(vec![("f", b"x")])) as MountTarget,
2657        )
2658        .unwrap();
2659        let pep = Arc::new(NamespacePep::new(
2660            Arc::new(OneSubject {
2661                name: "alice",
2662                ctx: sec_ctx(Level::Secret),
2663            }),
2664            Arc::new(PublicOnlyResolver),
2665            Arc::new(ReadFloorDecider),
2666        ));
2667        ns.set_pep(pep);
2668
2669        let err = ns
2670            .cat("/secret/f", &Subject::new("alice"))
2671            .await
2672            .unwrap_err();
2673        assert!(matches!(
2674            err,
2675            NamespaceError::Denied(NamespaceAction::Read, _)
2676        ));
2677    }
2678
2679    /// Subject-less mount/unmount deny once the PEP is armed; the `_as`
2680    /// variants mediate. (Read-floor decider denies mount-class, so even `_as`
2681    /// denies here — the point is the mediation runs, not the policy outcome.)
2682    #[tokio::test]
2683    async fn armed_pep_blocks_subjectless_mutation() {
2684        let mut ns = Namespace::new();
2685        ns.set_pep(deny_all_pep());
2686
2687        // Subject-less construction path denies on an armed namespace.
2688        let err = ns
2689            .mount("/x", Arc::new(MemMount::new(vec![])) as MountTarget)
2690            .unwrap_err();
2691        assert!(matches!(
2692            err,
2693            NamespaceError::Denied(NamespaceAction::BindMount, _)
2694        ));
2695
2696        let err = ns.unmount("/x").unwrap_err();
2697        assert!(matches!(
2698            err,
2699            NamespaceError::Denied(NamespaceAction::Unmount, _)
2700        ));
2701
2702        // The mediated `_as` path consults the PEP (deny-all ⇒ denied).
2703        let err = ns
2704            .mount_as(
2705                "/x",
2706                Arc::new(MemMount::new(vec![])) as MountTarget,
2707                &Subject::new("a"),
2708            )
2709            .await
2710            .unwrap_err();
2711        assert!(matches!(
2712            err,
2713            NamespaceError::Denied(NamespaceAction::Mount, _)
2714        ));
2715    }
2716
2717    /// `fork` inherits the armed PEP — a sandboxed child cannot escape the
2718    /// reference monitor by forking.
2719    #[tokio::test]
2720    async fn fork_inherits_pep() {
2721        let mut ns = Namespace::new();
2722        ns.mount(
2723            "/public",
2724            Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2725        )
2726        .unwrap();
2727        ns.set_pep(deny_all_pep());
2728
2729        let child = ns.fork();
2730        assert!(child.pep_armed());
2731        let err = child
2732            .cat("/public/f", &Subject::new("anyone"))
2733            .await
2734            .unwrap_err();
2735        assert!(matches!(
2736            err,
2737            NamespaceError::Denied(NamespaceAction::Read, _)
2738        ));
2739    }
2740
2741    #[tokio::test]
2742    async fn read_target_never_opens_writable_even_if_backing_mount_accepts_it() {
2743        let mut ns = Namespace::new();
2744        ns.mount(
2745            "/srv/registry",
2746            Arc::new(MemMount::new(vec![("repo/main/file", b"proof")])) as MountTarget,
2747        )
2748        .unwrap();
2749        let caller = test_subject();
2750        let (mut targets, relative) = ns
2751            .resolve_read_targets("/srv/registry/repo/main/file", &caller)
2752            .await
2753            .unwrap();
2754        assert_eq!(relative, ["repo", "main", "file"]);
2755        let target = targets.remove(0);
2756        let mut fid = target
2757            .walk(&["repo", "main", "file"], &caller)
2758            .await
2759            .unwrap();
2760        assert!(matches!(
2761            target.open(&mut fid, 1, &caller).await,
2762            Err(MountError::PermissionDenied(_))
2763        ));
2764        target.open(&mut fid, 0, &caller).await.unwrap();
2765        assert_eq!(target.read(&fid, 0, 16, &caller).await.unwrap(), b"proof");
2766        target.clunk(fid, &caller).await;
2767    }
2768}