Skip to main content

hyprstream_9p/
mount_backend.rs

1//! `MountBackend` — a [`Backend`] that exports an in-process VFS [`Mount`].
2//!
3//! This is the server-side adapter used by the UDS 9P listener (#506). It is
4//! the local-mount counterpart to the `hyprstream` crate's capnp-RPC
5//! `ModelBackend`: both implement the same [`Backend`] seam the [`Translator`]
6//! dispatches to, so the accept/serve/fid-table machinery is shared verbatim —
7//! only the object behind the `Backend` differs.
8//!
9//! ```text
10//!   Wanix (p9kit.ClientFS) ──► UnixListener ──► Translator ──► MountBackend ──► dyn Mount
11//!         9P2000.L wire            UDS            fid table      Subject-scoped     policy PEP
12//! ```
13//!
14//! ## Subject threading (MAC-load-bearing)
15//!
16//! Every [`Mount`] method takes the verified caller [`Subject`]. The listener
17//! serves exactly one tenant's export, so the `Subject` is fixed at construction
18//! and threaded onto every op; the served mount remains the single policy
19//! enforcement point. There is no path by which a 9P op reaches the mount without
20//! the tenant's `Subject`.
21//!
22//! ## Fid mapping
23//!
24//! The translator allocates opaque `u32` 9P fids; a [`Mount`] hands back opaque
25//! [`Fid`] handles from `walk`. `MountBackend` owns the `u32 → (path, Fid)`
26//! mapping. Because a [`Mount::walk`] resolves a path from the mount root (not
27//! relative to a source fid), each fid also remembers its absolute path so a
28//! subsequent relative walk can re-resolve `parent_path + components`.
29
30use std::sync::Arc;
31
32use anyhow::{anyhow, Context as _, Result};
33use async_trait::async_trait;
34use dashmap::DashMap;
35use hyprstream_rpc::Subject;
36use hyprstream_vfs::{DirEntry, Fid, Mount, MountError};
37use tokio::sync::{Mutex, OnceCell};
38
39use crate::backend::{Backend, OpenResult, StatResult, WalkResult};
40pub use crate::mac_seam::AttachAuthenticator as AttachAuthorizer;
41use crate::mac_seam::VerifiedAttach;
42use crate::msg::{self, Qid, ReaddirEntry};
43
44/// Resolves the mount ticket a client presents in `Tattach.uname` to the
45/// verified session [`Subject`] the export is scoped to.
46///
47/// This is the attach-time credential seam for transports where the caller
48/// identity is not fixed at listener construction: the H1b `/9p` WebTransport
49/// plane serves a cert-pinned mesh session over which many tenants could
50/// attach, so the ticket rides `Tattach.uname` and is validated here — the
51/// per-session analogue of the RPC `EnvelopeContext` (MAC interface policy:
52/// "extend at attach time, never per-op"). The concrete impl lives in the
53/// `hyprstream` crate (it owns the JWT/OAuth verification chain); this trait
54/// keeps `hyprstream-9p` free of that dependency.
55///
56/// On denial, return a [`MountError`] — the translator maps it to an `Rlerror`
57/// errno (e.g. [`MountError::PermissionDenied`] → `EACCES`).
58/// Max bytes a single read/write returns. Kept below the translator's `MSG_SIZE`
59/// (8 KiB) so an `Rread` carrying a full iounit plus its 9P header still fits the
60/// negotiated msize.
61const IOUNIT: u32 = 8 * 1024 - 64;
62
63/// 9P qtype bit for a directory (`QTDIR`).
64const QTDIR: u8 = 0x80;
65
66/// Per-fid state: the absolute path it resolves to plus the live mount handle.
67///
68/// The handle lives behind an async `Mutex` so a mount op can be awaited without
69/// holding a `DashMap` shard guard. `Option` because `clunk` takes ownership of
70/// the [`Fid`] to hand back to the mount.
71struct MountFidEntry {
72    path: Vec<String>,
73    handle: Mutex<Option<Fid>>,
74}
75
76/// A [`Backend`] backed by a single Subject-scoped VFS [`Mount`].
77///
78/// The session [`Subject`] is either fixed at construction ([`MountBackend::new`],
79/// the UDS/vsock listeners) or resolved from the client's `Tattach.uname` ticket
80/// at attach time ([`MountBackend::with_authorizer`], the H1b `/9p` WebTransport
81/// plane). It lives behind a [`OnceCell`] so per-op code reads one bound value
82/// either way; ops before a successful attach fail closed.
83pub struct MountBackend {
84    mount: Arc<dyn Mount>,
85    subject: OnceCell<Subject>,
86    /// Present only for the attach-time path; resolves `uname` → `Subject`.
87    authorizer: Option<Arc<dyn AttachAuthorizer>>,
88    fids: DashMap<u32, Arc<MountFidEntry>>,
89}
90
91impl MountBackend {
92    /// Wrap `mount` as the 9P export root for a `subject` fixed at construction.
93    pub fn new(mount: Arc<dyn Mount>, subject: Subject) -> Self {
94        let cell = OnceCell::new();
95        // Infallible on a fresh cell.
96        let _ = cell.set(subject);
97        Self {
98            mount,
99            subject: cell,
100            authorizer: None,
101            fids: DashMap::new(),
102        }
103    }
104
105    /// Wrap `mount` as the 9P export root whose session [`Subject`] is resolved
106    /// from the `Tattach.uname` ticket by `authorizer` (H1b `/9p` WebTransport).
107    ///
108    /// The `Subject` is unbound until a successful [`Backend::attach`]; any op
109    /// arriving before attach fails closed.
110    pub fn with_authorizer(mount: Arc<dyn Mount>, authorizer: Arc<dyn AttachAuthorizer>) -> Self {
111        Self {
112            mount,
113            subject: OnceCell::new(),
114            authorizer: Some(authorizer),
115            fids: DashMap::new(),
116        }
117    }
118
119    /// The bound session [`Subject`], or an error if no attach has bound it yet
120    /// (fail-closed: a 9P op must never reach the mount without a caller).
121    fn caller(&self) -> Result<&Subject> {
122        self.subject
123            .get()
124            .ok_or_else(|| anyhow!("9P op before Tattach: session Subject not bound"))
125    }
126
127    /// Clone out the `Arc` for a fid, dropping the `DashMap` guard so the mount
128    /// call can await without holding a shard lock.
129    fn entry(&self, fid: u32) -> Result<Arc<MountFidEntry>> {
130        self.fids
131            .get(&fid)
132            .map(|e| Arc::clone(&e))
133            .ok_or_else(|| anyhow!("fid {fid} not walked"))
134    }
135
136    /// Build the leaf [`Qid`] for a mount handle by stat-ing it.
137    async fn qid_of(&self, handle: &Fid) -> Result<Qid> {
138        let st = self
139            .mount
140            .stat(handle, self.caller()?)
141            .await
142            .context("mount stat failed")?;
143        Ok(Qid {
144            qtype: st.qtype,
145            version: st.version,
146            path: st.path,
147        })
148    }
149}
150
151#[async_trait]
152impl Backend for MountBackend {
153    async fn attach(
154        &self,
155        uname: &str,
156        aname: &str,
157        verified: Option<VerifiedAttach>,
158    ) -> Result<Option<VerifiedAttach>> {
159        // Fixed-subject listeners have no authorizer; the Subject is already
160        // bound and `uname`/`aname` are advisory (ignored, as on the UDS/vsock
161        // paths).
162        let Some(authorizer) = self.authorizer.as_ref() else {
163            if let Some(verified) = verified {
164                let existing = self
165                    .subject
166                    .get()
167                    .ok_or_else(|| anyhow!("fixed 9P subject missing"))?;
168                if existing != verified.subject() {
169                    return Err(anyhow::Error::new(MountError::PermissionDenied(
170                        "verified attach subject differs from fixed VFS subject".to_owned(),
171                    )));
172                }
173                return Ok(Some(verified));
174            }
175            return Ok(None);
176        };
177        // Attach-time ticket path (H1b): resolve+narrow the Subject AND validate
178        // the requested `aname` export against the ticket's namespace grant in
179        // one authorization. A MountError here maps to an Rlerror errno
180        // (PermissionDenied → EACCES) via the translator, before any fid exists.
181        let verified = match verified {
182            Some(verified) => verified,
183            None => authorizer
184                .authenticate(uname, aname)
185                .await
186                .map_err(anyhow::Error::new)?,
187        };
188        let subject = verified.subject().clone();
189        let attempted_subject = subject.clone();
190        // First attach wins; a second attach on the same connection must not
191        // silently re-scope the session. Ignore a redundant identical set,
192        // reject a conflicting one.
193        match self.subject.set(subject) {
194            Ok(()) => Ok(Some(verified)),
195            Err(_) => {
196                let existing = self
197                    .subject
198                    .get()
199                    .ok_or_else(|| anyhow!("bind session Subject: cell rejected without value"))?;
200                if existing == &attempted_subject {
201                    Ok(Some(verified))
202                } else {
203                    Err(anyhow::Error::new(MountError::PermissionDenied(
204                        "conflicting attach subject".to_owned(),
205                    )))
206                }
207            }
208        }
209    }
210
211    async fn walk(&self, fid: u32, newfid: u32, components: &[String]) -> Result<WalkResult> {
212        // A Mount walk resolves from the root, so build the target's absolute
213        // path as parent_path + components. An empty-components walk (attach /
214        // clone) re-resolves the source fid's own path.
215        let parent_path = self
216            .fids
217            .get(&fid)
218            .map(|e| e.path.clone())
219            .unwrap_or_default();
220        let parent_len = parent_path.len();
221        let mut new_path = parent_path;
222        new_path.extend(components.iter().cloned());
223
224        // Resolve each component independently so the 9P result carries one
225        // QID for every object the new fid actually traversed. Returning only a
226        // leaf QID while binding `newfid` to the complete path would let the
227        // translator cache a shallower, incorrectly authorized name.
228        let mut qids = Vec::with_capacity(components.len().max(1));
229        let mut handle = None;
230        let mut reached = Vec::with_capacity(components.len());
231        for component_count in 1..=components.len() {
232            let refs: Vec<&str> = new_path[..parent_len + component_count]
233                .iter()
234                .map(String::as_str)
235                .collect();
236            // On any failure past the first successful hop, `handle` still
237            // holds the previously-resolved mount `Fid`. That `Fid` has no
238            // `Drop` cleanup (see `hyprstream_vfs::Fid`) — for a remote mount
239            // it is a live 9P fid held open on the peer — so it must be
240            // explicitly clunked before returning the error, or every walk
241            // that fails past its first component (e.g. `/a/b` where `a`
242            // exists but `b` does not) leaks one backend handle.
243            let next = match self.mount.walk(&refs, self.caller()?).await {
244                Ok(next) => next,
245                Err(e) => {
246                    if let Some(previous) = handle.take() {
247                        self.mount.clunk(previous, self.caller()?).await;
248                    }
249                    return Err(anyhow::Error::new(e).context("mount walk failed"));
250                }
251            };
252            let qid = match self.qid_of(&next).await {
253                Ok(qid) => qid,
254                Err(e) => {
255                    self.mount.clunk(next, self.caller()?).await;
256                    if let Some(previous) = handle.take() {
257                        self.mount.clunk(previous, self.caller()?).await;
258                    }
259                    return Err(e);
260                }
261            };
262            if let Some(previous) = handle.replace(next) {
263                self.mount.clunk(previous, self.caller()?).await;
264            }
265            qids.push(qid);
266            reached.push(components[component_count - 1].clone());
267        }
268
269        if components.is_empty() {
270            let refs: Vec<&str> = new_path.iter().map(String::as_str).collect();
271            let next = self
272                .mount
273                .walk(&refs, self.caller()?)
274                .await
275                .context("mount walk failed")?;
276            qids.push(self.qid_of(&next).await?);
277            handle = Some(next);
278        }
279        let handle = handle.ok_or_else(|| anyhow!("mount walk returned no handle"))?;
280        self.fids.insert(
281            newfid,
282            Arc::new(MountFidEntry {
283                path: new_path,
284                handle: Mutex::new(Some(handle)),
285            }),
286        );
287        Ok(WalkResult { qids, reached })
288    }
289
290    async fn open(&self, fid: u32, flags: u32) -> Result<OpenResult> {
291        let entry = self.entry(fid)?;
292        let mut guard = entry.handle.lock().await;
293        let handle = guard
294            .as_mut()
295            .ok_or_else(|| anyhow!("open: fid {fid} is clunked"))?;
296        let mode = lopen_flags_to_mode(flags);
297        self.mount
298            .open(handle, mode, self.caller()?)
299            .await
300            .context("mount open failed")?;
301        let qid = self.qid_of(handle).await?;
302        Ok(OpenResult {
303            qid,
304            iounit: IOUNIT,
305        })
306    }
307
308    async fn read(&self, fid: u32, offset: u64, count: u32) -> Result<Vec<u8>> {
309        let entry = self.entry(fid)?;
310        let guard = entry.handle.lock().await;
311        let handle = guard
312            .as_ref()
313            .ok_or_else(|| anyhow!("read: fid {fid} is clunked"))?;
314        self.mount
315            .read(handle, offset, count, self.caller()?)
316            .await
317            .context("mount read failed")
318    }
319
320    async fn write(&self, fid: u32, offset: u64, data: &[u8]) -> Result<u32> {
321        let entry = self.entry(fid)?;
322        let guard = entry.handle.lock().await;
323        let handle = guard
324            .as_ref()
325            .ok_or_else(|| anyhow!("write: fid {fid} is clunked"))?;
326        self.mount
327            .write(handle, offset, data, self.caller()?)
328            .await
329            .context("mount write failed")
330    }
331
332    async fn stat(&self, fid: u32) -> Result<StatResult> {
333        let entry = self.entry(fid)?;
334        let guard = entry.handle.lock().await;
335        let handle = guard
336            .as_ref()
337            .ok_or_else(|| anyhow!("stat: fid {fid} is clunked"))?;
338        let st = self
339            .mount
340            .stat(handle, self.caller()?)
341            .await
342            .context("mount stat failed")?;
343        let is_dir = st.qtype & QTDIR != 0;
344        let mode = if is_dir { 0o040755 } else { 0o100644 };
345        Ok(StatResult {
346            qid: Qid {
347                qtype: st.qtype,
348                version: st.version,
349                path: st.path,
350            },
351            mode,
352            size: st.size,
353            mtime_sec: st.mtime,
354        })
355    }
356
357    async fn readdir(&self, fid: u32, offset: u64, count: u32) -> Result<Vec<u8>> {
358        let entry = self.entry(fid)?;
359        let entries = {
360            let guard = entry.handle.lock().await;
361            let handle = guard
362                .as_ref()
363                .ok_or_else(|| anyhow!("readdir: fid {fid} is clunked"))?;
364            self.mount
365                .readdir(handle, self.caller()?)
366                .await
367                .context("mount readdir failed")?
368        };
369        Ok(encode_dir_entries(&entries, offset, count))
370    }
371
372    async fn clunk(&self, fid: u32) -> Result<()> {
373        // Drop local state and hand the mount handle back for release.
374        if let Some((_, entry)) = self.fids.remove(&fid) {
375            let handle = entry.handle.lock().await.take();
376            if let Some(handle) = handle {
377                self.mount.clunk(handle, self.caller()?).await;
378            }
379        }
380        Ok(())
381    }
382
383    async fn close_connection(&self) {
384        let fids: Vec<u32> = self.fids.iter().map(|entry| *entry.key()).collect();
385        for fid in fids {
386            let _ = self.clunk(fid).await;
387        }
388    }
389}
390
391/// Encode directory entries as a page of **standard 9P2000.L Rreaddir dirent
392/// records** (`qid[13] · offset[8] · type[1] · name[s]`) via
393/// [`msg::encode_readdir_page`].
394///
395/// This is the wire-faithful format a standard 9P client (Wanix `p9kit` over
396/// `progrium/p9`) requires — not the hyprstream-internal
397/// `name_len/name/is_dir/size` dialect. `offset` is a dirent cookie and `count`
398/// a byte budget; records are packed whole (see `encode_readdir_page`).
399///
400/// Per-entry qid: a `DirEntry` may carry a `stat` with a real qid; when it does
401/// we use it, otherwise we synthesize the qtype from `is_dir` with an unknown
402/// (`version=0, path=0`) identity — sound per `Stat`'s qid invariant, and
403/// sufficient because standard clients re-walk each name to stat it.
404fn encode_dir_entries(entries: &[DirEntry], offset: u64, count: u32) -> Vec<u8> {
405    let records: Vec<ReaddirEntry> = entries
406        .iter()
407        .map(|e| {
408            let qid = match &e.stat {
409                Some(st) => Qid {
410                    qtype: st.qtype,
411                    version: st.version,
412                    path: st.path,
413                },
414                None => Qid {
415                    qtype: if e.is_dir { QTDIR } else { 0 },
416                    version: 0,
417                    path: 0,
418                },
419            };
420            ReaddirEntry {
421                qid,
422                name: e.name.clone(),
423            }
424        })
425        .collect();
426    msg::encode_readdir_page(&records, offset, count)
427}
428
429/// Map 9P2000.L `Tlopen` flags (Linux `O_*` bits) to a 9P open-mode byte
430/// (`OREAD=0` / `OWRITE=1` / `ORDWR=2`). Only read/write intent is preserved;
431/// `O_CREAT`/`O_TRUNC`/`O_APPEND` are advisory here. Mirrors the equivalent
432/// mapping in the capnp-RPC `ModelBackend`.
433fn lopen_flags_to_mode(flags: u32) -> u8 {
434    const O_WRONLY: u32 = 0o1;
435    const O_RDWR: u32 = 0o2;
436    match flags & 0o3 {
437        O_WRONLY => 1, // OWRITE
438        O_RDWR => 2,   // ORDWR
439        _ => 0,        // OREAD
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446
447    #[test]
448    fn lopen_flags_mapping() {
449        assert_eq!(lopen_flags_to_mode(0), 0);
450        assert_eq!(lopen_flags_to_mode(0o1), 1);
451        assert_eq!(lopen_flags_to_mode(0o2), 2);
452        assert_eq!(lopen_flags_to_mode(0o101), 1);
453    }
454
455    /// Regression: a multi-component walk that fails past its first hop must
456    /// clunk every intermediate `Fid` it resolved before returning the error.
457    /// `Fid` has no `Drop` cleanup — for a remote mount it is a live 9P fid
458    /// held open on the peer — so a dropped-without-clunking handle leaks on
459    /// every walk that ENOENTs past its first component (e.g. `/a/b` where
460    /// `a` exists but `b` does not).
461    #[tokio::test]
462    async fn walk_clunks_intermediate_handle_on_mid_path_failure() {
463        use async_trait::async_trait;
464        use hyprstream_vfs::{DirEntry, Stat};
465        use std::sync::atomic::{AtomicUsize, Ordering};
466
467        struct TrackedMount {
468            clunks: AtomicUsize,
469        }
470
471        #[async_trait]
472        impl Mount for TrackedMount {
473            async fn walk(&self, components: &[&str], _c: &Subject) -> Result<Fid, MountError> {
474                match components {
475                    [] | ["a"] => Ok(Fid::new(components.len())),
476                    ["a", "b"] => Err(MountError::NotFound("a/b".into())),
477                    other => panic!("unexpected walk: {other:?}"),
478                }
479            }
480            async fn open(&self, _f: &mut Fid, _m: u8, _c: &Subject) -> Result<(), MountError> {
481                Err(MountError::PermissionDenied("open".into()))
482            }
483            async fn read(
484                &self,
485                _f: &Fid,
486                _o: u64,
487                _n: u32,
488                _c: &Subject,
489            ) -> Result<Vec<u8>, MountError> {
490                Err(MountError::Io("read".into()))
491            }
492            async fn write(
493                &self,
494                _f: &Fid,
495                _o: u64,
496                _d: &[u8],
497                _c: &Subject,
498            ) -> Result<u32, MountError> {
499                Err(MountError::NotSupported("write".into()))
500            }
501            async fn readdir(&self, _f: &Fid, _c: &Subject) -> Result<Vec<DirEntry>, MountError> {
502                Err(MountError::NotDirectory("readdir".into()))
503            }
504            async fn stat(&self, f: &Fid, _c: &Subject) -> Result<Stat, MountError> {
505                let depth = *f.downcast_ref::<usize>().unwrap_or(&0);
506                Ok(Stat::unknown_qid(0, depth as u64, "x".into(), 0))
507            }
508            async fn clunk(&self, _f: Fid, _c: &Subject) {
509                self.clunks.fetch_add(1, Ordering::SeqCst);
510            }
511        }
512
513        let mount = Arc::new(TrackedMount {
514            clunks: AtomicUsize::new(0),
515        });
516        let backend = MountBackend::new(mount.clone(), Subject::new("tenant"));
517
518        // Attach (empty walk) binds fid 0 to the root. `MountBackend::new`
519        // fixes the Subject, so `uname`/`aname` are advisory here.
520        backend.attach("tenant", "", None).await.unwrap();
521        backend.fids.insert(
522            0,
523            Arc::new(MountFidEntry {
524                path: vec![],
525                handle: Mutex::new(Some(Fid::new(0usize))),
526            }),
527        );
528
529        // Walk fid 0 -> newfid 1 via ["a", "b"]: "a" resolves (handle A is
530        // held), "b" fails. Handle A must be clunked on this error path.
531        let err = backend.walk(0, 1, &["a".to_owned(), "b".to_owned()]).await;
532        assert!(err.is_err(), "walk into a missing leaf must fail");
533        assert_eq!(
534            mount.clunks.load(Ordering::SeqCst),
535            1,
536            "the intermediate handle for \"a\" must be clunked on the \"a/b\" failure, not leaked"
537        );
538
539        // No Tclunk arrives for the attached root when the peer disappears.
540        // Connection teardown must still release that retained mount handle.
541        backend.close_connection().await;
542        assert_eq!(mount.clunks.load(Ordering::SeqCst), 2);
543        assert!(backend.fids.is_empty());
544    }
545
546    #[test]
547    fn encode_dir_entries_emits_standard_rreaddir_records() {
548        use crate::msg::parse_readdir_entries;
549
550        let entries = vec![
551            DirEntry {
552                name: "a".into(),
553                is_dir: true,
554                size: 0,
555                stat: None,
556            },
557            DirEntry {
558                name: "bb".into(),
559                is_dir: false,
560                size: 7,
561                stat: None,
562            },
563        ];
564        let full = encode_dir_entries(&entries, 0, u32::MAX);
565        assert!(!full.is_empty());
566
567        // Standard record layout: qid[13] · offset[8] · type[1] · name[2+len].
568        // First entry "a" (a dir): qid.qtype = QTDIR at byte 0, dirent type at
569        // byte 21 also QTDIR, name length u16=1 at bytes 22..24, 'a' at 24.
570        assert_eq!(full[0], QTDIR); // qid.qtype
571        assert_eq!(&full[13..21], &1u64.to_le_bytes()); // offset cookie = 1
572        assert_eq!(full[21], QTDIR); // dirent type = dir
573        assert_eq!(&full[22..24], &1u16.to_le_bytes()); // name len
574        assert_eq!(full[24], b'a');
575
576        // Round-trips through the standard client-side parser.
577        let parsed = parse_readdir_entries(&full).unwrap();
578        assert_eq!(parsed.len(), 2);
579        assert_eq!(parsed[0].name, "a");
580        assert!(parsed[0].qid.is_dir());
581        assert_eq!(parsed[0].offset, 1);
582        assert_eq!(parsed[1].name, "bb");
583        assert!(!parsed[1].qid.is_dir());
584        assert_eq!(parsed[1].offset, 2);
585
586        // Cookie paging: offset past the last cookie yields nothing.
587        assert!(encode_dir_entries(&entries, 2, u32::MAX).is_empty());
588        // Resuming after cookie 1 yields only the second entry.
589        let rest = parse_readdir_entries(&encode_dir_entries(&entries, 1, u32::MAX)).unwrap();
590        assert_eq!(rest.len(), 1);
591        assert_eq!(rest[0].name, "bb");
592    }
593}