Skip to main content

hyprstream_9p/
translator.rs

1//! Server-side 9P2000.L translator.
2//!
3//! Accepts 9P connections (TCP for now; virtio-9P later) and translates each
4//! T-message into a [`Backend`] call. The backend is the capnp-RPC seam:
5//! the `hyprstream` binary crate wraps `ModelClient` to turn each call into a
6//! `nine.capnp` envelope against the model service's `fs` scope, mirroring
7//! `RemoteModelMount` (which goes the other way: VFS → RPC).
8//!
9//! ## Server-side fid table
10//!
11//! The translator owns a [`FidTable`] mapping 9P fid → backend fid + metadata
12//! (qtype, opened flag). This is the inverse of `RemoteModelMount`'s
13//! client-side fid table.
14//!
15//! ## Transport
16//!
17//! [`Translator::serve`] runs a TCP accept loop; [`Translator::serve_uds`] runs
18//! the same loop over a Unix domain socket ([`tokio::net::UnixListener`]);
19//! [`Translator::serve_vsock`] runs it over a Cloud-Hypervisor **hybrid-vsock**
20//! host socket. All three delegate to one transport-agnostic accept loop
21//! (`serve_listener`) and the same per-connection
22//! [`Translator::serve_connection`] core, which operates on any
23//! `AsyncRead + AsyncWrite` stream. The UDS entry point is how a native Wanix
24//! workload consumes a Subject-scoped export via its `p9kit.ClientFS` 9P client
25//! (#506); the vsock entry point is how a **kata guest** dials the host VFS over
26//! native 9P (the CH `ch` path has no virtio-9p, so vsock is the 9P transport
27//! into the guest — #730). [`Translator::from_mount`] / [`serve_mount_uds`] /
28//! [`serve_mount_vsock`] build the translator directly from an
29//! `Arc<dyn Mount>` + `Subject`.
30//!
31//! ### Hybrid-vsock
32//!
33//! Cloud Hypervisor exposes guest vsock as a host Unix socket that multiplexes
34//! guest ports with a `connect <port>\n` text handshake — the same handshake
35//! `hyprstream_workers::runtime::kata_agent::hybrid_vsock_connect` performs in
36//! the opposite direction (host→guest agent). [`Translator::serve_vsock`]
37//! plays the host multiplexer role: it strips and acknowledges that preamble
38//! per connection, then hands the bare stream to the shared 9P core, so
39//! hybrid-vsock reuses byte-identical connection handling with TCP and UDS and
40//! adds no new dependency. Firecracker/Dragonball raw `AF_VSOCK`
41//! (`vsock://<cid>`, mirroring `AgentAddress::Vsock`) is a follow-up: CH — the
42//! actual target — uses hybrid-vsock, and the raw-vsock hypervisors are not
43//! booted here.
44
45use std::path::Path;
46use std::sync::Arc;
47
48use anyhow::{Context, Result};
49use async_trait::async_trait;
50use dashmap::DashMap;
51use hyprstream_rpc::auth::mac::ObjectRef;
52use hyprstream_rpc::Subject;
53use hyprstream_vfs::Mount;
54use tokio::io::{split, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
55use tokio::net::{TcpListener, TcpStream, UnixListener, UnixStream};
56use tokio::sync::OnceCell;
57use tracing::{debug, error, info, warn};
58
59use crate::backend::Backend;
60use crate::mac_seam::{anonymous_floor, AccessDecider, Action, ReferenceMonitor, SessionContext};
61use crate::mount_backend::MountBackend;
62use crate::msg::{self, encode_response, parse_request, rflush, Request, Response};
63
64/// Negotiated maximum message size. Generous: Kata guest mounts may issue
65/// large read-ahead. The backend's iounit still bounds individual reads.
66const MSG_SIZE: u32 = 8 * 1024;
67
68/// Per-fid state held by the translator (server side).
69#[derive(Clone, Debug)]
70struct FidState {
71    /// Qtype of the walked file (QTDIR=0x80 / QTFILE=0x00).
72    qtype: u8,
73    /// Whether open() has succeeded on this fid.
74    opened: bool,
75    /// Session derived once from the verified `Tattach` credential and
76    /// inherited by every descendant fid. `None` when the translator runs
77    /// without a [`ReferenceMonitor`] (the dormant pre-activation default).
78    session: Option<SessionContext>,
79    /// Absolute path of this walked fid, relative to the export root. The
80    /// reference monitor resolves this path through the trusted
81    /// manifest/genesis label resolver before every mediated operation.
82    path: Vec<String>,
83}
84
85/// Server-side fid table: 9P fid → state.
86///
87/// `DashMap` so the translator can be shared across per-connection tasks.
88#[derive(Default)]
89pub struct FidTable {
90    fids: DashMap<u32, FidState>,
91}
92
93impl FidTable {
94    /// Insert state for a fid, inheriting the verified attach session (when a
95    /// monitor is installed) and carrying the absolute walked path used for
96    /// content-label resolution.
97    pub fn insert(&self, fid: u32, qtype: u8, session: Option<SessionContext>, path: Vec<String>) {
98        self.fids.insert(
99            fid,
100            FidState {
101                qtype,
102                opened: false,
103                session,
104                path,
105            },
106        );
107    }
108
109    /// Mark a fid as opened.
110    pub fn set_opened(&self, fid: u32) {
111        if let Some(mut s) = self.fids.get_mut(&fid) {
112            s.opened = true;
113        }
114    }
115
116    /// Look up a fid's qtype.
117    pub fn qtype(&self, fid: u32) -> Option<u8> {
118        self.fids.get(&fid).map(|s| s.qtype)
119    }
120
121    /// Look up the verified attach session inherited by a fid (`None` when
122    /// the fid is unknown or the translator runs without a monitor).
123    pub fn session(&self, fid: u32) -> Option<SessionContext> {
124        self.fids.get(&fid).and_then(|s| s.session.clone())
125    }
126
127    /// Look up a fid's absolute export-relative path for trusted label lookup.
128    pub fn path(&self, fid: u32) -> Option<Vec<String>> {
129        self.fids.get(&fid).map(|s| s.path.clone())
130    }
131
132    /// Remove a fid (clunk).
133    pub fn remove(&self, fid: u32) {
134        self.fids.remove(&fid);
135    }
136}
137
138/// The translator: a backend plus a shared fid table.
139///
140/// Cloning is cheap (Arc internals); one translator serves many connections.
141pub struct Translator {
142    backend: Arc<dyn Backend>,
143    backend_factory: Arc<dyn Fn() -> Arc<dyn Backend> + Send + Sync>,
144    fids: Arc<FidTable>,
145    attach_session: OnceCell<SessionContext>,
146    /// Mandatory resolver-backed, audited policy-enforcement point.
147    decider: Arc<dyn AccessDecider>,
148    /// Optional S2 token/IFC composition. The mandatory decider remains active
149    /// when this richer attach-time monitor is not installed.
150    monitor: Option<Arc<ReferenceMonitor>>,
151    /// Production-only coverage-gated subject-context selection. Tests and
152    /// embeddings that explicitly install a monitor retain direct
153    /// identity-aware behavior unless they opt into this control.
154    activation_controlled: bool,
155}
156
157impl Translator {
158    /// Build a translator over the given backend and mandatory audited PEP.
159    pub fn new(backend: Arc<dyn Backend>, decider: Arc<dyn AccessDecider>) -> Self {
160        let backend_factory_backend = Arc::clone(&backend);
161        Self {
162            backend,
163            backend_factory: Arc::new(move || Arc::clone(&backend_factory_backend)),
164            fids: Arc::new(FidTable::default()),
165            attach_session: OnceCell::new(),
166            decider,
167            monitor: None,
168            activation_controlled: false,
169        }
170    }
171
172    /// Install the S2 reference monitor: every dispatched op on every fid is
173    /// then mediated (attach-time token verification, trusted label
174    /// resolution, token gate, independent IFC dominance, then the local
175    /// AVC/PDP), failing closed at each step. Without this call the translator
176    /// enforces nothing — the dormant pre-activation default.
177    pub fn with_reference_monitor(mut self, monitor: Arc<ReferenceMonitor>) -> Self {
178        self.monitor = Some(monitor);
179        self
180    }
181
182    /// Build a translator that exports a single Subject-scoped VFS [`Mount`] as
183    /// its 9P root.
184    ///
185    /// This is the entry point for #506: `mount` is the tenant's export root
186    /// (already the single MAC policy-enforcement point) and `subject` is the
187    /// verified caller identity threaded onto every backend op. It wraps the
188    /// mount in a [`MountBackend`] — the same [`Backend`] seam the capnp-RPC
189    /// `ModelBackend` uses on the TCP path — so no new attachment mechanism is
190    /// introduced; only the export root differs.
191    pub fn from_mount(
192        mount: Arc<dyn Mount>,
193        subject: Subject,
194        decider: Arc<dyn AccessDecider>,
195    ) -> Self {
196        let backend: Arc<dyn Backend> =
197            Arc::new(MountBackend::new(Arc::clone(&mount), subject.clone()));
198        Self {
199            backend,
200            backend_factory: Arc::new(move || {
201                Arc::new(MountBackend::new(Arc::clone(&mount), subject.clone())) as Arc<dyn Backend>
202            }),
203            fids: Arc::new(FidTable::default()),
204            attach_session: OnceCell::new(),
205            decider,
206            monitor: None,
207            activation_controlled: false,
208        }
209    }
210
211    /// Build a translator that exports `mount`, resolving the session
212    /// [`Subject`] from the mount ticket the client presents in `Tattach.uname`
213    /// via `authorizer` (H1b `/9p` WebTransport plane, #765).
214    ///
215    /// Unlike [`from_mount`](Self::from_mount) — where the caller identity is
216    /// fixed at construction (a UDS/vsock listener serves exactly one tenant) —
217    /// the WebTransport plane serves a cert-pinned mesh session over which a
218    /// tenant proves identity at attach. The `Subject` is bound once, at the
219    /// first successful `Tattach`, and threaded onto every op by
220    /// [`MountBackend`] thereafter; a denied ticket fails the attach with an
221    /// `Rlerror` (see [`MountBackend::with_authorizer`]). Every other layer —
222    /// the serve loop, fid table, errno mapping — is identical to `from_mount`.
223    pub fn from_mount_authorized(
224        mount: Arc<dyn Mount>,
225        authorizer: Arc<dyn crate::mount_backend::AttachAuthorizer>,
226        decider: Arc<dyn AccessDecider>,
227    ) -> Self {
228        let backend: Arc<dyn Backend> = Arc::new(MountBackend::with_authorizer(
229            Arc::clone(&mount),
230            Arc::clone(&authorizer),
231        ));
232        Self {
233            backend,
234            backend_factory: Arc::new(move || {
235                Arc::new(MountBackend::with_authorizer(
236                    Arc::clone(&mount),
237                    Arc::clone(&authorizer),
238                )) as Arc<dyn Backend>
239            }),
240            fids: Arc::new(FidTable::default()),
241            attach_session: OnceCell::new(),
242            decider,
243            monitor: None,
244            activation_controlled: false,
245        }
246    }
247
248    /// Build a fresh per-connection translator state over the same wiring.
249    ///
250    /// The accept loop shares only immutable policy/auth seams. Fid state,
251    /// attach context, and stateful mount backends are connection-local so one
252    /// client cannot reuse another client's fid numbers or attach subject.
253    fn connection_scoped(&self) -> Self {
254        Self {
255            backend: (self.backend_factory)(),
256            backend_factory: Arc::clone(&self.backend_factory),
257            fids: Arc::new(FidTable::default()),
258            attach_session: OnceCell::new(),
259            decider: Arc::clone(&self.decider),
260            monitor: self.monitor.clone(),
261            activation_controlled: self.activation_controlled,
262        }
263    }
264
265    /// Use the process-global coverage-gated widen/narrow control. Production
266    /// constructors call this after installing the mandatory monitor.
267    pub fn with_activation_control(mut self) -> Self {
268        self.activation_controlled = true;
269        self
270    }
271
272    fn identity_aware(&self) -> bool {
273        self.monitor.is_some()
274            && (!self.activation_controlled
275                || hyprstream_rpc::auth::mac::global_mac_activation_control().mode()
276                    == hyprstream_rpc::auth::mac::MacActivationMode::IdentityAware)
277    }
278
279    /// Run a TCP accept loop until the listener errors or is closed.
280    ///
281    /// Each connection runs on its own task. Errors on one connection do not
282    /// affect siblings.
283    pub async fn serve(self, listener: TcpListener) -> Result<()> {
284        self.serve_listener(listener).await
285    }
286
287    /// Run the accept loop over a Unix domain socket.
288    ///
289    /// Identical per-connection handling to [`Translator::serve`]; only the
290    /// transport differs. This is how a native Wanix workload attaches to a
291    /// Subject-scoped export over a UDS via its `p9kit.ClientFS` 9P client.
292    pub async fn serve_uds(self, listener: UnixListener) -> Result<()> {
293        self.serve_listener(listener).await
294    }
295
296    /// Run the accept loop over a Cloud-Hypervisor **hybrid-vsock** host socket.
297    ///
298    /// The vsock sibling of [`serve_uds`](Self::serve_uds), and the entry point
299    /// a kata guest dials to operate the host VFS over native 9P (#730). CH's
300    /// `ch` path has no virtio-9p, so the guest reaches the host by opening a
301    /// vsock connection; CH surfaces that as a host Unix socket whose accepted
302    /// connections each begin with a `connect <port>\n` text preamble (the
303    /// firecracker/CH multiplexer handshake — the reverse of
304    /// `kata_agent::hybrid_vsock_connect`). This entry strips and acknowledges
305    /// that preamble per connection, then runs the identical
306    /// [`serve_connection`](Self::serve_connection) core as
307    /// [`serve`](Self::serve) / [`serve_uds`](Self::serve_uds); the
308    /// `Subject`-per-op enforcement is unchanged — only the transport differs.
309    pub async fn serve_vsock(self, listener: UnixListener) -> Result<()> {
310        self.serve_listener(HybridVsockListener { inner: listener })
311            .await
312    }
313
314    /// Run the accept loop over a **raw** (no-handshake) hybrid-vsock host
315    /// socket: a per-port host UDS the **guest dials**.
316    ///
317    /// The raw sibling of [`serve_vsock`](Self::serve_vsock). Where
318    /// [`serve_vsock`] plays the CH host-multiplexer role for connections
319    /// *hyprstream* initiates — and therefore strips a `connect <port>\n` text
320    /// preamble off each accepted stream — this entry point serves a **per-port
321    /// host listener** (`<vsock-base>_<port>`, e.g. `VFS_9P_VSOCK_PORT=564`) that
322    /// the guest connects to. Per the Firecracker/CH hybrid-vsock spec,
323    /// guest-initiated connections to a per-port host UDS arrive **raw**: there is
324    /// no `connect <port>\n` preamble (the port is already encoded in the socket
325    /// path, not in an in-band handshake). Stripping a preamble here would eat the
326    /// guest's first 9P `Tversion` bytes and break the handshake (#741).
327    ///
328    /// So this hands each accepted [`UnixStream`] straight to the shared
329    /// [`serve_connection`](Self::serve_connection) core with **no** preamble
330    /// strip. The `Subject`-per-op enforcement and wire-faithful 9P2000.L framing
331    /// are byte-identical to every other transport; only the accept surface
332    /// differs (raw, via [`RawVsockListener`]).
333    pub async fn serve_vsock_raw(self, listener: UnixListener) -> Result<()> {
334        self.serve_listener(RawVsockListener { inner: listener })
335            .await
336    }
337
338    /// Transport-agnostic accept loop shared by [`serve`](Self::serve) and
339    /// [`serve_uds`](Self::serve_uds). Each accepted connection is served on its
340    /// own task via [`serve_connection`](Self::serve_connection); errors on one
341    /// connection do not affect siblings.
342    async fn serve_listener<L: Listen>(self, listener: L) -> Result<()> {
343        let this = Arc::new(self);
344        info!(endpoint = %listener.describe(), "9P translator: listening");
345        loop {
346            let (stream, peer) = match listener.accept_conn().await {
347                Ok(v) => v,
348                Err(e) => {
349                    error!(error = %e, "9P translator: accept failed, shutting down");
350                    return Err(e).context("9P accept loop terminated");
351                }
352            };
353            let this = Arc::new(this.connection_scoped());
354            tokio::spawn(async move {
355                debug!(%peer, "9P connection accepted");
356                if let Err(e) = this.serve_connection(stream).await {
357                    warn!(%peer, error = %e, "9P connection ended with error");
358                }
359            });
360        }
361    }
362
363    /// Serve a single connection to completion (until EOF, parse error, or
364    /// the peer resets).
365    ///
366    /// Generic over the byte stream so the same core serves TCP, UDS, and any
367    /// future `AsyncRead + AsyncWrite` transport.
368    pub async fn serve_connection<S>(self: &Arc<Self>, stream: S) -> Result<()>
369    where
370        S: AsyncRead + AsyncWrite + Send + 'static,
371    {
372        let result = self.serve_connection_inner(stream).await;
373        self.backend.close_connection().await;
374        self.fids.fids.clear();
375        result
376    }
377
378    async fn serve_connection_inner<S>(self: &Arc<Self>, stream: S) -> Result<()>
379    where
380        S: AsyncRead + AsyncWrite + Send + 'static,
381    {
382        let (mut rx, mut tx) = split(stream);
383        // Reusable growable read buffer; capped per-message by msize.
384        let mut len_buf = [0u8; 4];
385
386        loop {
387            // Read the 4-byte length prefix.
388            let n = rx.read(&mut len_buf).await?;
389            if n == 0 {
390                debug!("9P peer closed connection");
391                return Ok(());
392            }
393            if n < 4 {
394                rx.read_exact(&mut len_buf[n..]).await?;
395            }
396            let total = u32::from_le_bytes(len_buf) as usize;
397            if total < 7 || total > MSG_SIZE as usize {
398                anyhow::bail!("invalid 9P message length: {total}");
399            }
400
401            // Read the rest of the message.
402            let mut buf = vec![0u8; total];
403            buf[..4].copy_from_slice(&len_buf);
404            rx.read_exact(&mut buf[4..]).await?;
405
406            // Tflush is handled inline: requests are processed serially per
407            // connection, so there is never an outstanding request to cancel —
408            // acknowledge with Rflush and continue. (Response has no Flush
409            // variant because flush is a no-op at this layer.)
410            let msg_type = buf.get(4).copied().unwrap_or(0);
411            if msg_type == msg::TFLUSH {
412                let tag = tag_or_notag(&buf);
413                tx.write_all(&rflush(tag)).await?;
414                continue;
415            }
416
417            let (tag, response) = match self.handle_message(&buf).await {
418                Ok(r) => r,
419                Err(e) => {
420                    // Map a typed backend error to a real 9P2000.L `Rlerror`
421                    // errno (H1a / #764). `wanix serve` clients and shell UX
422                    // depend on distinguishing ENOENT/EACCES/ENOTDIR from a
423                    // blanket EIO; [`errno_from_error`] walks the anyhow cause
424                    // chain for a [`hyprstream_vfs::MountError`] and maps it,
425                    // falling back to EIO for untyped errors.
426                    let err_tag = tag_or_notag(&buf);
427                    let ecode = errno_from_error(&e);
428                    warn!(error = %e, tag = err_tag, ecode, "9P handler error");
429                    (err_tag, Response::Error { ecode })
430                }
431            };
432
433            let out = encode_response(tag, &response);
434            tx.write_all(&out).await?;
435        }
436    }
437
438    /// Decode one T-message, dispatch it to the backend, and produce the
439    /// R-message. Returns `(tag, response)`.
440    async fn handle_message(&self, buf: &[u8]) -> Result<(u16, Response)> {
441        let (tag, req) = parse_request(buf).context("decode 9P T-message")?;
442        let resp = match req {
443            Request::Version { msize, version } => self.handle_version(msize, version),
444            Request::Attach {
445                fid, uname, aname, ..
446            } => self.handle_attach(fid, &uname, &aname).await?,
447            // Flush is intercepted in serve_connection before reaching here;
448            // this arm is unreachable but kept exhaustive.
449            Request::Flush { .. } => Response::Clunk,
450            Request::Walk {
451                fid,
452                newfid,
453                wnames,
454            } => self.handle_walk(fid, newfid, wnames).await?,
455            Request::Lopen { fid, flags } => self.handle_lopen(fid, flags).await?,
456            Request::Read { fid, offset, count } => self.handle_read(fid, offset, count).await?,
457            Request::Write { fid, offset, data } => self.handle_write(fid, offset, &data).await?,
458            Request::Clunk { fid } => self.handle_clunk(fid).await,
459            Request::Getattr { fid, .. } => self.handle_getattr(fid).await?,
460            Request::Readdir { fid, offset, count } => {
461                self.handle_readdir(fid, offset, count).await?
462            }
463        };
464        Ok((tag, resp))
465    }
466
467    // ────────────────────────────────────────────────────────────────────
468    // Per-message handlers
469    // ────────────────────────────────────────────────────────────────────
470
471    fn handle_version(&self, requested: u32, version: String) -> Response {
472        if version != "9P2000.L" && !version.starts_with("9P2000") {
473            return Response::Error {
474                ecode: libc_einval(),
475            };
476        }
477        let msize = requested.clamp(256, MSG_SIZE);
478        Response::Version {
479            msize,
480            version: "9P2000.L".into(),
481        }
482    }
483
484    async fn handle_attach(&self, fid: u32, uname: &str, aname: &str) -> Result<Response> {
485        // The monitor is always present in production. The operator control
486        // narrows/widens only the subject context it evaluates; it never
487        // removes mediation.
488        let (verified, session) = if self.identity_aware() {
489            let Some(monitor) = &self.monitor else {
490                return Ok(Response::Error {
491                    ecode: libc_eperm(),
492                });
493            };
494            // One credential verification yields the unified MAC+VFS bundle.
495            // Nothing independently derives a Subject after this point.
496            let verified = match monitor.authenticate(uname, aname).await {
497                Ok(verified) => verified,
498                Err(_) => {
499                    return Ok(Response::Error {
500                        ecode: libc_eperm(),
501                    })
502                }
503            };
504            let session = verified.session().clone();
505            if !monitor.authorize(&session, &[], Action::Attach) {
506                return Ok(Response::Error {
507                    ecode: libc_eperm(),
508                });
509            }
510            self.ensure_attach_session_compatible(&session)?;
511            (Some(verified), Some(session))
512        } else {
513            let root: [&str; 0] = [];
514            if !self
515                .decider
516                .check(&anonymous_floor(), ObjectRef::Path(&root), Action::Attach)
517            {
518                return Ok(Response::Error {
519                    ecode: libc_eperm(),
520                });
521            }
522            // A ticket-authorized backend authenticates exactly once below.
523            // Fixed-subject backends were bound by their production
524            // constructor and do not require a client credential at floor.
525            (None, None)
526        };
527
528        // Only an attach that cleared monitor authorization may bind a backend
529        // subject. Forward BOTH `uname` and `aname` so the backend's
530        // authorizer can validate the requested export against the ticket's
531        // granted namespace and deny an unknown/forbidden selector with EACCES
532        // before any fid exists. Walk the empty path to materialize a root qid
533        // from the backend, then record it.
534        let bound = self.backend.attach(uname, aname, verified.clone()).await?;
535        if let Some(expected) = verified.as_ref() {
536            if bound.as_ref() != Some(expected) {
537                return Err(anyhow::Error::new(
538                    hyprstream_vfs::MountError::PermissionDenied(
539                        "backend did not bind the verified attach bundle".to_owned(),
540                    ),
541                ));
542            }
543        }
544        if self.identity_aware() && bound.is_none() {
545            return Err(anyhow::Error::new(
546                hyprstream_vfs::MountError::PermissionDenied(
547                    "backend did not bind a verified attach bundle".to_owned(),
548                ),
549            ));
550        }
551        let session = session.or_else(|| bound.as_ref().map(|attach| attach.session().clone()));
552        let walk = self.backend.walk(fid, fid, &[]).await?;
553        if let Some(session) = &session {
554            self.bind_attach_session(session)?;
555        }
556        let qtype = walk.qids.last().map(|q| q.qtype).unwrap_or(0);
557        self.fids.insert(fid, qtype, session, Vec::new());
558        let qid = walk.qids.into_iter().next().unwrap_or_default();
559        Ok(Response::Attach { qid })
560    }
561
562    fn ensure_attach_session_compatible(&self, session: &SessionContext) -> Result<()> {
563        match self.attach_session.get() {
564            // Compare by *attach identity*, not value equality: a real
565            // authenticator re-stamps the token deadline on every verification
566            // of the same ticket, so a value comparison would reject a
567            // legitimate re-attach of an identical, still-valid session (F2).
568            Some(existing) if existing.same_attach_identity(session) => Ok(()),
569            Some(_) => Err(anyhow::Error::new(
570                hyprstream_vfs::MountError::PermissionDenied(
571                    "conflicting attach session context".to_owned(),
572                ),
573            )),
574            None => Ok(()),
575        }
576    }
577
578    fn bind_attach_session(&self, session: &SessionContext) -> Result<()> {
579        if self.attach_session.set(session.clone()).is_ok() {
580            return Ok(());
581        }
582        self.ensure_attach_session_compatible(session)
583    }
584
585    async fn handle_walk(&self, fid: u32, newfid: u32, wnames: Vec<String>) -> Result<Response> {
586        // The session is inherited from the fid being walked (#568 — the
587        // credential is verified once at attach, never re-verified per op).
588        // The destination path extends the source fid's already-walked path.
589        let session = self.fids.session(fid);
590        let base = self.fids.path(fid).unwrap_or_default();
591
592        // Complete mediation: authorize every hop, not only the final
593        // destination. Labels need not be monotone with path depth. An empty
594        // walk is a fid clone and still mediates the object bound to the source
595        // fid; otherwise an unattached connection could clone another
596        // connection's fid without passing the monitor.
597        let mut prefix = base.clone();
598        if wnames.is_empty() && !self.authorize_path(session.as_ref(), &prefix, Action::Walk) {
599            return Ok(Response::Error {
600                ecode: libc_eperm(),
601            });
602        }
603        for component in &wnames {
604            prefix.push(component.clone());
605            if !self.authorize_path(session.as_ref(), &prefix, Action::Walk) {
606                return Ok(Response::Error {
607                    ecode: libc_eperm(),
608                });
609            }
610        }
611
612        // Mirror of RemoteModelMount::walk: call backend.walk with the source
613        // fid, the new fid, and the path components.
614        let result = self.backend.walk(fid, newfid, &wnames).await?;
615
616        // The backend is authoritative for the exact request prefix it bound
617        // to `newfid`. Enforce the Backend contract before caching it.
618        if !wnames.is_empty()
619            && (result.qids.len() != result.reached.len()
620                || result.reached.len() > wnames.len()
621                || result.reached != wnames[..result.reached.len()])
622        {
623            return Err(anyhow::anyhow!(
624                "backend walk result does not describe its reached prefix"
625            ));
626        }
627        let nwqid = result.qids.len();
628        let mut reached = base;
629        reached.extend(result.reached);
630
631        if wnames.is_empty() {
632            // nwname=0 is a fid *clone*: newfid aliases fid (same file), and
633            // the backend returns no qids. newfid must still inherit the source
634            // fid's qtype, session, and path — otherwise the clone has no
635            // cached session and a live monitor wrongly denies it for an
636            // already-authenticated client (#568).
637            let qtype = self.fids.qtype(fid).unwrap_or(0);
638            self.fids.insert(newfid, qtype, session, reached);
639        } else if nwqid > 0 {
640            let qtype = result.qids.last().map(|q| q.qtype).unwrap_or(0);
641            self.fids.insert(newfid, qtype, session, reached);
642        }
643        Ok(Response::Walk { qids: result.qids })
644    }
645
646    async fn handle_lopen(&self, fid: u32, flags: u32) -> Result<Response> {
647        if let Some(err) = self.deny(fid, Action::Open) {
648            return Ok(err);
649        }
650        let open = self.backend.open(fid, flags).await?;
651        self.fids.set_opened(fid);
652        Ok(Response::Lopen {
653            qid: open.qid,
654            iounit: open.iounit,
655        })
656    }
657
658    async fn handle_read(&self, fid: u32, offset: u64, count: u32) -> Result<Response> {
659        if let Some(err) = self.deny(fid, Action::Read) {
660            return Ok(err);
661        }
662        let data = self.backend.read(fid, offset, count).await?;
663        Ok(Response::Read { data })
664    }
665
666    async fn handle_write(&self, fid: u32, offset: u64, data: &[u8]) -> Result<Response> {
667        if let Some(err) = self.deny(fid, Action::Write) {
668            return Ok(err);
669        }
670        let count = self.backend.write(fid, offset, data).await?;
671        Ok(Response::Write { count })
672    }
673
674    async fn handle_clunk(&self, fid: u32) -> Response {
675        // Best-effort clunk on the backend; the local fid is dropped either way.
676        if let Err(e) = self.backend.clunk(fid).await {
677            debug!(fid, error = %e, "backend clunk failed (ignored)");
678        }
679        self.fids.remove(fid);
680        Response::Clunk
681    }
682
683    async fn handle_getattr(&self, fid: u32) -> Result<Response> {
684        // getattr leaks object metadata (qid/mode/size/mtime), so it is gated
685        // like every other fid op — it is not a metadata-only exemption.
686        if let Some(err) = self.deny(fid, Action::Getattr) {
687            return Ok(err);
688        }
689        let st = self.backend.stat(fid).await?;
690        Ok(Response::Getattr {
691            qid: st.qid,
692            mode: st.mode,
693            size: st.size,
694            mtime_sec: st.mtime_sec,
695        })
696    }
697
698    async fn handle_readdir(&self, fid: u32, offset: u64, count: u32) -> Result<Response> {
699        if let Some(err) = self.deny(fid, Action::Readdir) {
700            return Ok(err);
701        }
702        let data = self.backend.readdir(fid, offset, count).await?;
703        Ok(Response::Readdir { data })
704    }
705
706    /// Mediate one op through the optional full S2 monitor or, when it is not
707    /// installed, directly through the mandatory audited decider.
708    fn deny(&self, fid: u32, action: Action) -> Option<Response> {
709        let Some(path) = self.fids.path(fid) else {
710            return Some(Response::Error {
711                ecode: libc_eperm(),
712            });
713        };
714        let session = self.fids.session(fid);
715        if self.authorize_path(session.as_ref(), &path, action) {
716            None
717        } else {
718            Some(Response::Error {
719                ecode: libc_eperm(),
720            })
721        }
722    }
723
724    fn authorize_path(
725        &self,
726        session: Option<&SessionContext>,
727        path: &[String],
728        action: Action,
729    ) -> bool {
730        if self.identity_aware() {
731            return self.monitor.as_ref().is_some_and(|monitor| {
732                session.is_some_and(|session| monitor.authorize(session, path, action))
733            });
734        }
735        let components: Vec<&str> = path.iter().map(String::as_str).collect();
736        self.decider
737            .check(&anonymous_floor(), ObjectRef::Path(&components), action)
738    }
739}
740
741/// Bind a Unix domain socket at `path` and serve `mount` (scoped to `subject`)
742/// as its 9P2000.L root until the socket errors or is closed.
743///
744/// Convenience wrapper over [`Translator::from_mount`] + [`Translator::serve_uds`]
745/// — the #506 one-call entry point a supervisor uses to expose a tenant's
746/// Subject-scoped export to a native Wanix `p9kit.ClientFS` client.
747pub async fn serve_mount_uds(
748    mount: Arc<dyn Mount>,
749    subject: Subject,
750    decider: Arc<dyn AccessDecider>,
751    monitor: Option<Arc<crate::mac_seam::ReferenceMonitor>>,
752    path: impl AsRef<Path>,
753) -> Result<()> {
754    let listener = UnixListener::bind(path.as_ref())
755        .with_context(|| format!("bind 9P UDS listener at {:?}", path.as_ref()))?;
756    let mut t = Translator::from_mount(mount, subject, decider);
757    if let Some(monitor) = monitor {
758        t = t.with_reference_monitor(monitor).with_activation_control();
759    }
760    t.serve_uds(listener).await
761}
762
763/// Bind a Cloud-Hypervisor **hybrid-vsock** host socket at `path` and serve
764/// `mount` (scoped to `subject`) as its 9P2000.L root until the socket errors
765/// or is closed.
766///
767/// The hybrid-vsock sibling of [`serve_mount_uds`] and the #730 one-call entry
768/// a supervisor uses to expose a tenant's Subject-scoped export to a **kata
769/// guest** dialing over vsock. Guest connections arrive on the host UDS `path`,
770/// each prefixed with a `connect <port>\n` handshake that
771/// [`Translator::serve_vsock`] strips before handing the stream to the shared
772/// 9P core.
773pub async fn serve_mount_vsock(
774    mount: Arc<dyn Mount>,
775    subject: Subject,
776    decider: Arc<dyn AccessDecider>,
777    monitor: Option<Arc<crate::mac_seam::ReferenceMonitor>>,
778    path: impl AsRef<Path>,
779) -> Result<()> {
780    let listener = UnixListener::bind(path.as_ref())
781        .with_context(|| format!("bind 9P hybrid-vsock listener at {:?}", path.as_ref()))?;
782    let mut t = Translator::from_mount(mount, subject, decider);
783    if let Some(monitor) = monitor {
784        t = t.with_reference_monitor(monitor).with_activation_control();
785    }
786    t.serve_vsock(listener).await
787}
788
789/// Bind a **raw** (no-handshake) hybrid-vsock **per-port** host socket at `path`
790/// and serve `mount` (scoped to `subject`) as its 9P2000.L root until the socket
791/// errors or is closed.
792///
793/// The raw sibling of [`serve_mount_vsock`], for the **guest-initiated**
794/// direction (#741). `path` is a per-port host UDS (`<vsock-base>_<port>`) the
795/// **guest dials**; per the Firecracker/CH hybrid-vsock spec such connections
796/// arrive **raw** (no `connect <port>\n` preamble — the port is encoded in the
797/// socket path). Accepted streams go straight to the shared 9P core via
798/// [`Translator::serve_vsock_raw`] with no preamble strip, so the guest's first
799/// `Tversion` bytes are treated as 9P and not consumed. This is the entry a kata
800/// supervisor uses to expose a tenant's Subject-scoped export on
801/// `VFS_9P_VSOCK_PORT`.
802pub async fn serve_mount_vsock_raw(
803    mount: Arc<dyn Mount>,
804    subject: Subject,
805    decider: Arc<dyn AccessDecider>,
806    monitor: Option<Arc<crate::mac_seam::ReferenceMonitor>>,
807    path: impl AsRef<Path>,
808) -> Result<()> {
809    let listener = UnixListener::bind(path.as_ref()).with_context(|| {
810        format!(
811            "bind 9P raw hybrid-vsock per-port listener at {:?}",
812            path.as_ref()
813        )
814    })?;
815    let mut t = Translator::from_mount(mount, subject, decider);
816    if let Some(monitor) = monitor {
817        t = t.with_reference_monitor(monitor).with_activation_control();
818    }
819    t.serve_vsock_raw(listener).await
820}
821
822/// Transport-agnostic accept surface, implemented for [`TcpListener`] and
823/// [`UnixListener`] so both share one accept loop (`serve_listener`).
824///
825/// Keeping this private and trait-bounded (rather than duplicating the loop)
826/// means TCP and UDS run byte-identical connection handling; a new transport
827/// only implements `accept_conn` + `describe`.
828#[async_trait]
829trait Listen: Send + Sync + 'static {
830    /// The per-connection byte stream this listener produces.
831    type Conn: AsyncRead + AsyncWrite + Send + 'static;
832
833    /// Accept one connection, returning the stream and a display string for the
834    /// peer (used only for tracing).
835    async fn accept_conn(&self) -> std::io::Result<(Self::Conn, String)>;
836
837    /// Human-readable endpoint description for the "listening" log line.
838    fn describe(&self) -> String;
839}
840
841#[async_trait]
842impl Listen for TcpListener {
843    type Conn = TcpStream;
844
845    async fn accept_conn(&self) -> std::io::Result<(TcpStream, String)> {
846        let (stream, peer) = self.accept().await?;
847        Ok((stream, peer.to_string()))
848    }
849
850    fn describe(&self) -> String {
851        self.local_addr()
852            .map(|a| a.to_string())
853            .unwrap_or_else(|_| "tcp:?".to_owned())
854    }
855}
856
857#[async_trait]
858impl Listen for UnixListener {
859    type Conn = UnixStream;
860
861    async fn accept_conn(&self) -> std::io::Result<(UnixStream, String)> {
862        let (stream, peer) = self.accept().await?;
863        Ok((stream, format!("unix:{peer:?}")))
864    }
865
866    fn describe(&self) -> String {
867        self.local_addr()
868            .map(|a| format!("unix:{a:?}"))
869            .unwrap_or_else(|_| "unix:?".to_owned())
870    }
871}
872
873/// Maximum length (excluding the terminating newline) of the hybrid-vsock
874/// `connect <port>` preamble line. The real handshake is well under 32 bytes;
875/// the cap bounds a peer that never sends a newline.
876const HYBRID_VSOCK_PREAMBLE_MAX: usize = 64;
877
878/// A Cloud-Hypervisor **hybrid-vsock** host listener: a [`UnixListener`] whose
879/// accepted connections each begin with a `connect <port>\n` text preamble (the
880/// firecracker/CH multiplexer handshake). [`accept_conn`](Listen::accept_conn)
881/// strips and acknowledges that preamble, then yields the bare [`UnixStream`]
882/// to the shared 9P serve path — so hybrid-vsock reuses byte-identical
883/// connection handling with TCP and UDS (`serve_listener` /
884/// [`serve_connection`](Translator::serve_connection)) and adds no new
885/// dependency.
886struct HybridVsockListener {
887    inner: UnixListener,
888}
889
890#[async_trait]
891impl Listen for HybridVsockListener {
892    type Conn = UnixStream;
893
894    async fn accept_conn(&self) -> std::io::Result<(UnixStream, String)> {
895        // A malformed/aborted handshake affects only that one peer: retry the
896        // accept rather than propagating (which `serve_listener` treats as a
897        // fatal listener error that tears down every sibling connection).
898        loop {
899            let (mut stream, _peer) = self.inner.accept().await?;
900            match hybrid_vsock_handshake(&mut stream).await {
901                Ok(port) => return Ok((stream, format!("hvsock:port{port}"))),
902                Err(e) => {
903                    warn!(error = %e, "hybrid-vsock handshake failed; dropping connection");
904                    continue;
905                }
906            }
907        }
908    }
909
910    fn describe(&self) -> String {
911        self.inner
912            .local_addr()
913            .map(|a| format!("hvsock:{a:?}"))
914            .unwrap_or_else(|_| "hvsock:?".to_owned())
915    }
916}
917
918/// A **raw** (no-handshake) hybrid-vsock **per-port** host listener: a
919/// [`UnixListener`] bound at a per-port host UDS (`<vsock-base>_<port>`) that the
920/// **guest dials**. Unlike [`HybridVsockListener`], accepted connections carry
921/// **no** `connect <port>\n` preamble — per the Firecracker/CH hybrid-vsock spec
922/// the port is encoded in the socket path, and guest-initiated connections to a
923/// per-port host UDS arrive raw (#741). So [`accept_conn`](Listen::accept_conn)
924/// yields the accepted [`UnixStream`] verbatim to the shared 9P serve path; the
925/// guest's first bytes are the 9P `Tversion`, never a preamble.
926///
927/// This is a thin, self-documenting wrapper (rather than serving the bare
928/// [`UnixListener`]) so the "listening" log line and peer strings identify the
929/// channel as raw hybrid-vsock; the byte handling is identical to the plain UDS
930/// impl.
931struct RawVsockListener {
932    inner: UnixListener,
933}
934
935#[async_trait]
936impl Listen for RawVsockListener {
937    type Conn = UnixStream;
938
939    async fn accept_conn(&self) -> std::io::Result<(UnixStream, String)> {
940        // No preamble: hand the stream straight through. The first bytes the
941        // guest sends are the 9P Tversion.
942        let (stream, peer) = self.inner.accept().await?;
943        Ok((stream, format!("rawvsock:{peer:?}")))
944    }
945
946    fn describe(&self) -> String {
947        self.inner
948            .local_addr()
949            .map(|a| format!("rawvsock:{a:?}"))
950            .unwrap_or_else(|_| "rawvsock:?".to_owned())
951    }
952}
953
954/// Read, validate, and acknowledge the hybrid-vsock `connect <port>\n` preamble
955/// on a freshly accepted host-UDS stream, returning the requested vsock port.
956///
957/// The preamble is read one byte at a time up to the terminating newline so no
958/// following 9P payload is swallowed into a throwaway buffer. The acknowledgement
959/// line contains `OK`, matching the firecracker/CH multiplexer and the reader in
960/// `kata_agent::hybrid_vsock_connect` (which only requires the response to
961/// contain `"OK"`).
962async fn hybrid_vsock_handshake(stream: &mut UnixStream) -> Result<u32> {
963    let mut line = Vec::with_capacity(HYBRID_VSOCK_PREAMBLE_MAX);
964    let mut byte = [0u8; 1];
965    loop {
966        let n = stream
967            .read(&mut byte)
968            .await
969            .context("read hybrid-vsock preamble")?;
970        if n == 0 {
971            anyhow::bail!("hybrid-vsock peer closed before sending `connect <port>` preamble");
972        }
973        if byte[0] == b'\n' {
974            break;
975        }
976        line.push(byte[0]);
977        if line.len() > HYBRID_VSOCK_PREAMBLE_MAX {
978            anyhow::bail!(
979                "hybrid-vsock preamble exceeds {HYBRID_VSOCK_PREAMBLE_MAX} bytes without a newline"
980            );
981        }
982    }
983
984    let text = String::from_utf8_lossy(&line);
985    let mut parts = text.split_whitespace();
986    let verb = parts.next().unwrap_or_default();
987    if !verb.eq_ignore_ascii_case("connect") {
988        anyhow::bail!("hybrid-vsock preamble: expected `connect <port>`, got {text:?}");
989    }
990    let port: u32 = parts
991        .next()
992        .and_then(|p| p.parse().ok())
993        .with_context(|| format!("hybrid-vsock preamble: missing/invalid port in {text:?}"))?;
994
995    stream
996        .write_all(format!("OK {port}\n").as_bytes())
997        .await
998        .context("write hybrid-vsock OK acknowledgement")?;
999    Ok(port)
1000}
1001
1002/// Extract the tag from a raw message for error-path Rlerror encoding.
1003fn tag_or_notag(buf: &[u8]) -> u16 {
1004    if buf.len() >= 6 {
1005        u16::from_le_bytes([buf[5], buf[6]])
1006    } else {
1007        0xFFFF // NOTAG
1008    }
1009}
1010
1011// errno-style codes the translator emits. We hardcode the integer values
1012// (Linux asm-generic errno numbers) rather than depend on libc so the crate
1013// stays wasm-friendly and the Rlerror wire codes are stable across platforms.
1014const ENOENT: u32 = 2; // No such file or directory
1015const EIO: u32 = 5; // I/O error
1016const EACCES: u32 = 13; // Permission denied
1017const EEXIST: u32 = 17; // File exists
1018const ENOTDIR: u32 = 20; // Not a directory
1019const EISDIR: u32 = 21; // Is a directory
1020const EINVAL: u32 = 22; // Invalid argument
1021const ENOSYS: u32 = 38; // Function not implemented
1022
1023const fn libc_einval() -> u32 {
1024    EINVAL
1025}
1026
1027/// Map a backend handler error to a 9P2000.L `Rlerror` errno (H1a / #764).
1028///
1029/// The backend seam is stringly-typed at the `anyhow::Error` boundary, but the
1030/// VFS [`MountBackend`] preserves the underlying [`hyprstream_vfs::MountError`]
1031/// as an anyhow *source* (via `.context(...)`, not string interpolation), so
1032/// the concrete error survives in the cause chain. This walks that chain and
1033/// maps the first [`MountError`] it finds to its POSIX errno; an untyped error
1034/// (e.g. a fid-table bookkeeping failure) falls back to [`EIO`].
1035///
1036/// Mapping (min ENOENT/EACCES/ENOTDIR per the spike, plus the rest of the
1037/// [`MountError`] surface):
1038/// `NotFound→ENOENT`, `PermissionDenied→EACCES`, `NotDirectory→ENOTDIR`,
1039/// `IsDirectory→EISDIR`, `InvalidArgument→EINVAL`, `AlreadyExists→EEXIST`,
1040/// `NotSupported→ENOSYS`, `Io→EIO`.
1041pub(crate) fn errno_from_error(err: &anyhow::Error) -> u32 {
1042    for cause in err.chain() {
1043        if let Some(me) = cause.downcast_ref::<hyprstream_vfs::MountError>() {
1044            return errno_from_mount_error(me);
1045        }
1046    }
1047    EIO
1048}
1049
1050/// Map a [`hyprstream_vfs::MountError`] variant to its POSIX errno.
1051fn errno_from_mount_error(e: &hyprstream_vfs::MountError) -> u32 {
1052    use hyprstream_vfs::MountError as M;
1053    match e {
1054        M::NotFound(_) => ENOENT,
1055        M::PermissionDenied(_) => EACCES,
1056        M::NotDirectory(_) => ENOTDIR,
1057        M::IsDirectory(_) => EISDIR,
1058        M::InvalidArgument(_) => EINVAL,
1059        M::AlreadyExists(_) => EEXIST,
1060        M::NotSupported(_) => ENOSYS,
1061        M::Io(_) => EIO,
1062    }
1063}
1064const fn libc_eperm() -> u32 {
1065    1 // EPERM
1066}
1067
1068#[cfg(test)]
1069#[allow(clippy::unwrap_used, clippy::expect_used)]
1070mod tests {
1071    use super::*;
1072    use crate::memory::MemoryBackend;
1073    use crate::msg::Qid;
1074
1075    // ── Typed errno mapping (H1a / #764) ────────────────────────────────
1076
1077    /// Every [`hyprstream_vfs::MountError`] variant must map to its POSIX
1078    /// errno when wrapped exactly as [`MountBackend`] wraps it (via
1079    /// `.context(...)`, which preserves the concrete error as an anyhow
1080    /// source). An untyped error falls back to EIO. Regression guard for the
1081    /// blanket-EIO behaviour the spike flagged at `translator.rs:211`.
1082    #[test]
1083    fn mount_errors_map_to_errnos() {
1084        use hyprstream_vfs::MountError as M;
1085        let cases = [
1086            (M::NotFound("x".into()), ENOENT),
1087            (M::PermissionDenied("x".into()), EACCES),
1088            (M::NotDirectory("x".into()), ENOTDIR),
1089            (M::IsDirectory("x".into()), EISDIR),
1090            (M::InvalidArgument("x".into()), EINVAL),
1091            (M::AlreadyExists("x".into()), EEXIST),
1092            (M::NotSupported("x".into()), ENOSYS),
1093            (M::Io("x".into()), EIO),
1094        ];
1095        for (err, expected) in cases {
1096            // Mimic the MountBackend error path: attach context so the
1097            // MountError is an anyhow *source*, not string-flattened.
1098            let wrapped = anyhow::Error::new(err).context("mount op failed");
1099            assert_eq!(errno_from_error(&wrapped), expected);
1100        }
1101        // Untyped bookkeeping errors fall back to EIO.
1102        assert_eq!(errno_from_error(&anyhow::anyhow!("fid 3 not walked")), EIO);
1103    }
1104
1105    /// End-to-end through [`MountBackend`]: a `Mount` that returns
1106    /// `NotFound` on a bad walk must surface as an anyhow chain the
1107    /// translator maps to `ENOENT` (not EIO). Proves the `.context(...)`
1108    /// wrapping in `MountBackend` keeps the `MountError` downcastable.
1109    #[tokio::test]
1110    async fn mount_backend_preserves_typed_errno_end_to_end() {
1111        use crate::mount_backend::MountBackend;
1112        use async_trait::async_trait;
1113        use hyprstream_rpc::Subject;
1114        use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Stat};
1115
1116        struct StubMount;
1117        #[async_trait]
1118        impl Mount for StubMount {
1119            async fn walk(&self, components: &[&str], _c: &Subject) -> Result<Fid, MountError> {
1120                if components.is_empty() {
1121                    // Attach walks the empty root path — resolve it.
1122                    Ok(Fid::new(()))
1123                } else {
1124                    Err(MountError::NotFound(components.join("/")))
1125                }
1126            }
1127            async fn open(&self, _f: &mut Fid, _m: u8, _c: &Subject) -> Result<(), MountError> {
1128                Err(MountError::PermissionDenied("open".into()))
1129            }
1130            async fn read(
1131                &self,
1132                _f: &Fid,
1133                _o: u64,
1134                _n: u32,
1135                _c: &Subject,
1136            ) -> Result<Vec<u8>, MountError> {
1137                Err(MountError::Io("read".into()))
1138            }
1139            async fn write(
1140                &self,
1141                _f: &Fid,
1142                _o: u64,
1143                _d: &[u8],
1144                _c: &Subject,
1145            ) -> Result<u32, MountError> {
1146                Err(MountError::NotSupported("write".into()))
1147            }
1148            async fn readdir(&self, _f: &Fid, _c: &Subject) -> Result<Vec<DirEntry>, MountError> {
1149                Err(MountError::NotDirectory("readdir".into()))
1150            }
1151            async fn stat(&self, _f: &Fid, _c: &Subject) -> Result<Stat, MountError> {
1152                Ok(Stat::unknown_qid(0x80, 0, "/".into(), 0))
1153            }
1154            async fn clunk(&self, _f: Fid, _c: &Subject) {}
1155        }
1156
1157        let backend = MountBackend::new(Arc::new(StubMount), Subject::new("tenant"));
1158        let t = Arc::new(Translator::new(Arc::new(backend), test_decider()));
1159
1160        // Attach fid 0 as root (empty walk succeeds).
1161        t.handle_message(&msg::tattach(1, 0, u32::MAX, "u", ""))
1162            .await
1163            .unwrap();
1164
1165        // Walk to a missing child → Err whose errno must be ENOENT.
1166        let err = t
1167            .handle_message(&msg::twalk(2, 0, 1, &["nope"]))
1168            .await
1169            .unwrap_err();
1170        assert_eq!(
1171            errno_from_error(&err),
1172            ENOENT,
1173            "missing path must be ENOENT, not EIO"
1174        );
1175    }
1176
1177    fn sample_qid(qtype: u8, path: u64) -> Qid {
1178        Qid {
1179            qtype,
1180            version: 1,
1181            path,
1182        }
1183    }
1184
1185    #[tokio::test]
1186    async fn version_round_trips() {
1187        let t = Translator::new(Arc::new(MemoryBackend::default()), test_decider());
1188        // Build a Tversion by hand via the codec and decode the response.
1189        let req = msg::tversion(1, 4096, "9P2000.L");
1190        let (tag, resp) = t.handle_message(&req).await.unwrap();
1191        assert_eq!(tag, 1);
1192        match resp {
1193            Response::Version { msize, version } => {
1194                assert_eq!(version, "9P2000.L");
1195                assert!(msize <= 4096);
1196            }
1197            other => panic!("expected Version, got {other:?}"),
1198        }
1199    }
1200
1201    #[tokio::test]
1202    async fn attach_then_walk_open_read_clunk() {
1203        let backend = MemoryBackend::default();
1204        backend.add_file("/hello.txt", b"hello world");
1205        let t = Translator::new(Arc::new(backend), test_decider());
1206
1207        // Attach: fid 0 becomes the root.
1208        let req = msg::tattach(1, 0, u32::MAX, "user", "/");
1209        let (_, resp) = t.handle_message(&req).await.unwrap();
1210        assert!(matches!(resp, Response::Attach { .. }));
1211
1212        // Walk from root (fid 0) to a new fid (1) for the file.
1213        let req = msg::twalk(2, 0, 1, &["hello.txt"]);
1214        let (_, resp) = t.handle_message(&req).await.unwrap();
1215        match resp {
1216            Response::Walk { qids } => assert_eq!(qids.len(), 1),
1217            other => panic!("expected Walk, got {other:?}"),
1218        }
1219
1220        // Open fid 1 for reading.
1221        let req = msg::tlopen(3, 1, 0); // OREAD
1222        let (_, resp) = t.handle_message(&req).await.unwrap();
1223        assert!(matches!(resp, Response::Lopen { .. }));
1224
1225        // Read.
1226        let req = msg::tread(4, 1, 0, 64);
1227        let (_, resp) = t.handle_message(&req).await.unwrap();
1228        match resp {
1229            Response::Read { data } => assert_eq!(&data, b"hello world"),
1230            other => panic!("expected Read, got {other:?}"),
1231        }
1232
1233        // Clunk fid 1.
1234        let req = msg::tclunk(5, 1);
1235        let (_, resp) = t.handle_message(&req).await.unwrap();
1236        assert!(matches!(resp, Response::Clunk));
1237    }
1238
1239    // ── #568 reference-monitor test doubles ───────────────────────────
1240    //
1241    // The monitor seams are exercised with fakes that stand in for the
1242    // application's verified-token authenticator, genesis/manifest label
1243    // resolver, and AVC/PDP decider. No production path installs a monitor
1244    // yet (activation is blocked on #698); the unmonitored tests in this
1245    // module double as the dormant-default regression guard.
1246
1247    use crate::mac_seam::{
1248        AccessDecider, AttachAuthenticator, ObjectLabelResolver, ObjectRef,
1249        ReferenceMonitorDenyReason, VerifiedAttach, VerifiedAttachIdentity, VerifiedTokenScope,
1250    };
1251    use hyprstream_rpc::auth::mac::{
1252        Assurance, CompartmentSet, Level, SecurityContext, SecurityLabel, VerifiedKeyMaterial,
1253    };
1254    use std::time::{Duration, Instant};
1255
1256    fn label(level: Level) -> SecurityLabel {
1257        SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY)
1258    }
1259
1260    fn ctx(level: Level) -> SecurityContext {
1261        // Classical key material so the derived assurance dominates the
1262        // Classical-assurance object labels used across these tests.
1263        SecurityContext::new(level, CompartmentSet::EMPTY, VerifiedKeyMaterial::Classical)
1264    }
1265
1266    /// A session at `level` whose verified token permits exactly `ops` (with
1267    /// a Secret ceiling) for the next hour.
1268    fn permit_session(level: Level, ops: &[Action]) -> SessionContext {
1269        permit_session_as("test-subject", level, ops)
1270    }
1271
1272    fn permit_session_as(identity: &str, level: Level, ops: &[Action]) -> SessionContext {
1273        SessionContext::from_verified_token(
1274            VerifiedAttachIdentity::from_verified_credential(identity, "test-tenant"),
1275            ctx(level),
1276            VerifiedTokenScope::from_verified_token(
1277                label(Level::Secret),
1278                Arc::from(ops),
1279                Instant::now() + Duration::from_secs(3600),
1280            ),
1281        )
1282    }
1283
1284    fn verified_attach(session: SessionContext) -> VerifiedAttach {
1285        let identity = session
1286            .verified_attach_identity()
1287            .expect("fixture session has verified identity")
1288            .clone();
1289        VerifiedAttach::try_new(
1290            identity.clone(),
1291            hyprstream_rpc::Subject::new(identity.subject()),
1292            session,
1293        )
1294        .expect("fixture bundle is internally bound")
1295    }
1296
1297    const ALL_OPS: &[Action] = &[
1298        Action::Attach,
1299        Action::Walk,
1300        Action::Open,
1301        Action::Read,
1302        Action::Write,
1303        Action::Getattr,
1304        Action::Readdir,
1305    ];
1306
1307    /// Authenticator returning a fixed session (the token is treated as
1308    /// already verified, as a real authenticator would after checking it).
1309    struct StaticAuth(SessionContext);
1310    #[async_trait]
1311    impl AttachAuthenticator for StaticAuth {
1312        async fn authenticate(
1313            &self,
1314            _u: &str,
1315            _a: &str,
1316        ) -> std::result::Result<VerifiedAttach, hyprstream_vfs::MountError> {
1317            if self.0.verified_attach_identity().is_none() {
1318                return Err(hyprstream_vfs::MountError::PermissionDenied(
1319                    "credential did not produce a verified attach identity".to_owned(),
1320                ));
1321            }
1322            Ok(verified_attach(self.0.clone()))
1323        }
1324    }
1325
1326    /// Resolver returning a fixed label for every path (`None` = unlabeled).
1327    struct StaticLabels(Option<SecurityLabel>);
1328    impl ObjectLabelResolver for StaticLabels {
1329        fn resolve(&self, _object: ObjectRef<'_>) -> Option<SecurityLabel> {
1330            self.0
1331        }
1332    }
1333
1334    struct AllowAll;
1335    impl AccessDecider for AllowAll {
1336        fn check(&self, _ctx: &SecurityContext, _object: ObjectRef<'_>, _action: Action) -> bool {
1337            true
1338        }
1339
1340        fn audit_denial(
1341            &self,
1342            _ctx: &SecurityContext,
1343            _object: ObjectRef<'_>,
1344            _object_label: Option<SecurityLabel>,
1345            _action: Action,
1346            _reason: ReferenceMonitorDenyReason,
1347        ) {
1348        }
1349    }
1350
1351    fn test_decider() -> Arc<dyn AccessDecider> {
1352        Arc::new(AllowAll)
1353    }
1354
1355    #[tokio::test]
1356    async fn connection_close_runs_backend_cleanup_on_eof_and_framing_error() {
1357        use crate::backend::{OpenResult, StatResult, WalkResult};
1358        use std::sync::atomic::{AtomicUsize, Ordering};
1359
1360        struct CloseBackend(AtomicUsize);
1361        #[async_trait]
1362        impl Backend for CloseBackend {
1363            async fn walk(&self, _: u32, _: u32, _: &[String]) -> Result<WalkResult> {
1364                anyhow::bail!("unreached")
1365            }
1366            async fn open(&self, _: u32, _: u32) -> Result<OpenResult> {
1367                anyhow::bail!("unreached")
1368            }
1369            async fn read(&self, _: u32, _: u64, _: u32) -> Result<Vec<u8>> {
1370                anyhow::bail!("unreached")
1371            }
1372            async fn write(&self, _: u32, _: u64, _: &[u8]) -> Result<u32> {
1373                anyhow::bail!("unreached")
1374            }
1375            async fn stat(&self, _: u32) -> Result<StatResult> {
1376                anyhow::bail!("unreached")
1377            }
1378            async fn readdir(&self, _: u32, _: u64, _: u32) -> Result<Vec<u8>> {
1379                anyhow::bail!("unreached")
1380            }
1381            async fn clunk(&self, _: u32) -> Result<()> {
1382                Ok(())
1383            }
1384            async fn close_connection(&self) {
1385                self.0.fetch_add(1, Ordering::SeqCst);
1386            }
1387        }
1388
1389        let backend = Arc::new(CloseBackend(AtomicUsize::new(0)));
1390        let translator = Arc::new(Translator::new(backend.clone(), test_decider()));
1391        let (peer, server) = tokio::io::duplex(32);
1392        drop(peer);
1393        translator.serve_connection(server).await.unwrap();
1394        assert_eq!(backend.0.load(Ordering::SeqCst), 1);
1395
1396        let (mut peer, server) = tokio::io::duplex(32);
1397        peer.write_all(&3u32.to_le_bytes()).await.unwrap();
1398        drop(peer);
1399        assert!(translator.serve_connection(server).await.is_err());
1400        assert_eq!(backend.0.load(Ordering::SeqCst), 2);
1401    }
1402
1403    fn monitor(
1404        auth: SessionContext,
1405        resolved: Option<SecurityLabel>,
1406        decider: Arc<dyn AccessDecider>,
1407    ) -> Arc<ReferenceMonitor> {
1408        Arc::new(ReferenceMonitor::new(
1409            Arc::new(StaticAuth(auth)),
1410            Arc::new(StaticLabels(resolved)),
1411            decider,
1412        ))
1413    }
1414
1415    /// With a monitor installed, an unlabeled root denies the attach itself:
1416    /// the root fid is a mediated object with no synthetic exemption.
1417    #[tokio::test]
1418    async fn monitor_denies_unlabeled_root_at_attach() {
1419        let t = Translator::new(Arc::new(MemoryBackend::default()), test_decider())
1420            .with_reference_monitor(monitor(
1421                permit_session(Level::Secret, ALL_OPS),
1422                None,
1423                Arc::new(AllowAll),
1424            ));
1425        let (_, resp) = t
1426            .handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1427            .await
1428            .unwrap();
1429        match resp {
1430            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
1431            other => panic!("expected Rlerror EPERM for unlabeled root, got {other:?}"),
1432        }
1433    }
1434
1435    /// A session without a verified token denies at attach, before any
1436    /// backend object handle exists.
1437    #[tokio::test]
1438    async fn monitor_denies_missing_token_at_attach() {
1439        let t = Translator::new(Arc::new(MemoryBackend::default()), test_decider())
1440            .with_reference_monitor(monitor(
1441                SessionContext::deny(),
1442                Some(label(Level::Public)),
1443                Arc::new(AllowAll),
1444            ));
1445        let (_, resp) = t
1446            .handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1447            .await
1448            .unwrap();
1449        match resp {
1450            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
1451            other => panic!("expected Rlerror EPERM for missing token, got {other:?}"),
1452        }
1453    }
1454
1455    #[tokio::test]
1456    async fn monitor_denies_expired_token_at_attach() {
1457        let expired = SessionContext::from_verified_token(
1458            VerifiedAttachIdentity::from_verified_credential("test-subject", "test-tenant"),
1459            ctx(Level::Secret),
1460            VerifiedTokenScope::from_verified_token(
1461                label(Level::Secret),
1462                Arc::from(ALL_OPS),
1463                Instant::now() - Duration::from_secs(1),
1464            ),
1465        );
1466        let t = Translator::new(Arc::new(MemoryBackend::default()), test_decider())
1467            .with_reference_monitor(monitor(
1468                expired,
1469                Some(label(Level::Public)),
1470                Arc::new(AllowAll),
1471            ));
1472        let (_, resp) = t
1473            .handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1474            .await
1475            .unwrap();
1476        match resp {
1477            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
1478            other => panic!("expected Rlerror EPERM for expired token, got {other:?}"),
1479        }
1480    }
1481
1482    /// When every gate passes — labeled object, unexpired token covering the
1483    /// op, dominating subject, permitting decider — the mediated session is
1484    /// served end to end.
1485    #[tokio::test]
1486    async fn monitor_allows_when_all_gates_pass() {
1487        let backend = MemoryBackend::default();
1488        backend.add_file("/hello.txt", b"hello world");
1489        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(monitor(
1490            permit_session(Level::Secret, ALL_OPS),
1491            Some(label(Level::Public)),
1492            Arc::new(AllowAll),
1493        ));
1494
1495        let (_, resp) = t
1496            .handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1497            .await
1498            .unwrap();
1499        assert!(matches!(resp, Response::Attach { .. }), "got {resp:?}");
1500        let (_, resp) = t
1501            .handle_message(&msg::twalk(2, 0, 1, &["hello.txt"]))
1502            .await
1503            .unwrap();
1504        assert!(matches!(resp, Response::Walk { .. }), "got {resp:?}");
1505        let (_, resp) = t.handle_message(&msg::tlopen(3, 1, 0)).await.unwrap();
1506        assert!(matches!(resp, Response::Lopen { .. }), "got {resp:?}");
1507        let (_, resp) = t.handle_message(&msg::tread(4, 1, 0, 64)).await.unwrap();
1508        match resp {
1509            Response::Read { data } => assert_eq!(&data, b"hello world"),
1510            other => panic!("expected Read, got {other:?}"),
1511        }
1512    }
1513
1514    /// #568: a translator with a live monitor actually blocks ops the decider
1515    /// rejects, proving the `deny` wiring is live — not just present but
1516    /// inert. Walk/open (permitted) still succeed; read is rejected with
1517    /// `Rlerror EPERM` rather than reaching the backend.
1518    #[tokio::test]
1519    async fn injected_decider_blocks_denied_action() {
1520        struct DenyReads;
1521        impl AccessDecider for DenyReads {
1522            fn check(
1523                &self,
1524                _ctx: &SecurityContext,
1525                _object: ObjectRef<'_>,
1526                action: Action,
1527            ) -> bool {
1528                !matches!(action, Action::Read)
1529            }
1530
1531            fn audit_denial(
1532                &self,
1533                _ctx: &SecurityContext,
1534                _object: ObjectRef<'_>,
1535                _object_label: Option<SecurityLabel>,
1536                _action: Action,
1537                _reason: ReferenceMonitorDenyReason,
1538            ) {
1539            }
1540        }
1541
1542        let backend = MemoryBackend::default();
1543        backend.add_file("/hello.txt", b"hello world");
1544        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(monitor(
1545            permit_session(Level::Secret, ALL_OPS),
1546            Some(label(Level::Public)),
1547            Arc::new(DenyReads),
1548        ));
1549
1550        t.handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1551            .await
1552            .unwrap();
1553        let (_, resp) = t
1554            .handle_message(&msg::twalk(2, 0, 1, &["hello.txt"]))
1555            .await
1556            .unwrap();
1557        assert!(
1558            matches!(resp, Response::Walk { .. }),
1559            "walk must still succeed"
1560        );
1561
1562        let (_, resp) = t.handle_message(&msg::tlopen(3, 1, 0)).await.unwrap();
1563        assert!(
1564            matches!(resp, Response::Lopen { .. }),
1565            "open must still succeed"
1566        );
1567
1568        let (_, resp) = t.handle_message(&msg::tread(4, 1, 0, 64)).await.unwrap();
1569        match resp {
1570            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
1571            other => panic!("expected Rlerror EPERM, got {other:?}"),
1572        }
1573    }
1574
1575    /// An op outside the verified token's operation set denies even when the
1576    /// decider would permit it — the token gate runs before policy.
1577    #[tokio::test]
1578    async fn monitor_denies_op_outside_token_scope() {
1579        let backend = MemoryBackend::default();
1580        backend.add_file("/hello.txt", b"hello world");
1581        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(monitor(
1582            permit_session(
1583                Level::Secret,
1584                &[Action::Attach, Action::Walk, Action::Open, Action::Read],
1585            ),
1586            Some(label(Level::Public)),
1587            Arc::new(AllowAll),
1588        ));
1589
1590        t.handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1591            .await
1592            .unwrap();
1593        t.handle_message(&msg::twalk(2, 0, 1, &["hello.txt"]))
1594            .await
1595            .unwrap();
1596        t.handle_message(&msg::tlopen(3, 1, 1 /* OWRITE */))
1597            .await
1598            .unwrap();
1599        let (_, resp) = t
1600            .handle_message(&msg::twrite(4, 1, 0, b"nope"))
1601            .await
1602            .unwrap();
1603        match resp {
1604            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
1605            other => panic!("expected Rlerror EPERM for out-of-scope write, got {other:?}"),
1606        }
1607        let (_, resp) = t.handle_message(&msg::tread(5, 1, 0, 64)).await.unwrap();
1608        assert!(
1609            matches!(resp, Response::Read { .. }),
1610            "in-scope read must pass: {resp:?}"
1611        );
1612    }
1613
1614    /// A walk is mediated against its destination label: the token ceiling
1615    /// (Confidential) covers the public file but not the Secret one, so the
1616    /// second walk denies even though the source fid was authorized.
1617    #[tokio::test]
1618    async fn monitor_walk_checked_against_destination_label() {
1619        struct ByName;
1620        impl ObjectLabelResolver for ByName {
1621            fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
1622                match object {
1623                    ObjectRef::Path(parts) => Some(match parts.last().copied() {
1624                        Some("secret.txt") => label(Level::Secret),
1625                        _ => label(Level::Public),
1626                    }),
1627                    ObjectRef::Cid(_) => None,
1628                }
1629            }
1630        }
1631        let session = SessionContext::from_verified_token(
1632            VerifiedAttachIdentity::from_verified_credential("test-subject", "test-tenant"),
1633            ctx(Level::Secret),
1634            VerifiedTokenScope::from_verified_token(
1635                label(Level::Confidential),
1636                Arc::from(ALL_OPS),
1637                Instant::now() + Duration::from_secs(3600),
1638            ),
1639        );
1640        let backend = MemoryBackend::default();
1641        backend.add_file("/hello.txt", b"hi");
1642        backend.add_file("/secret.txt", b"classified");
1643        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(
1644            Arc::new(ReferenceMonitor::new(
1645                Arc::new(StaticAuth(session)),
1646                Arc::new(ByName),
1647                Arc::new(AllowAll),
1648            )),
1649        );
1650
1651        t.handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1652            .await
1653            .unwrap();
1654        let (_, resp) = t
1655            .handle_message(&msg::twalk(2, 0, 1, &["hello.txt"]))
1656            .await
1657            .unwrap();
1658        assert!(
1659            matches!(resp, Response::Walk { .. }),
1660            "public walk must pass: {resp:?}"
1661        );
1662        let (_, resp) = t
1663            .handle_message(&msg::twalk(3, 0, 2, &["secret.txt"]))
1664            .await
1665            .unwrap();
1666        match resp {
1667            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
1668            other => panic!("expected Rlerror EPERM above the token ceiling, got {other:?}"),
1669        }
1670    }
1671
1672    /// The IFC floor is independent of the token and the policy matrix: a
1673    /// Public subject holding a Secret-ceiling token with an allow-all
1674    /// decider still cannot walk into a Secret-labeled object.
1675    #[tokio::test]
1676    async fn monitor_ifc_floor_not_bypassed_by_permissive_decider() {
1677        struct AllSecret;
1678        impl ObjectLabelResolver for AllSecret {
1679            fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
1680                match object {
1681                    ObjectRef::Path([]) => Some(label(Level::Public)),
1682                    ObjectRef::Path(_) => Some(label(Level::Secret)),
1683                    ObjectRef::Cid(_) => None,
1684                }
1685            }
1686        }
1687        let backend = MemoryBackend::default();
1688        backend.add_file("/secret.txt", b"classified");
1689        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(
1690            Arc::new(ReferenceMonitor::new(
1691                Arc::new(StaticAuth(permit_session(Level::Public, ALL_OPS))),
1692                Arc::new(AllSecret),
1693                Arc::new(AllowAll),
1694            )),
1695        );
1696
1697        let (_, resp) = t
1698            .handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1699            .await
1700            .unwrap();
1701        assert!(
1702            matches!(resp, Response::Attach { .. }),
1703            "public root must attach: {resp:?}"
1704        );
1705        let (_, resp) = t
1706            .handle_message(&msg::twalk(2, 0, 1, &["secret.txt"]))
1707            .await
1708            .unwrap();
1709        match resp {
1710            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
1711            other => panic!("expected Rlerror EPERM for IFC non-dominance, got {other:?}"),
1712        }
1713    }
1714
1715    /// Clunk is fid disposal, not an object operation: it is never mediated,
1716    /// so a denied op can never wedge connection teardown.
1717    #[tokio::test]
1718    async fn clunk_is_not_mediated() {
1719        let backend = MemoryBackend::default();
1720        backend.add_file("/hello.txt", b"hi");
1721        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(monitor(
1722            permit_session(Level::Secret, &[Action::Attach, Action::Walk]),
1723            Some(label(Level::Public)),
1724            Arc::new(AllowAll),
1725        ));
1726        t.handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1727            .await
1728            .unwrap();
1729        t.handle_message(&msg::twalk(2, 0, 1, &["hello.txt"]))
1730            .await
1731            .unwrap();
1732        let (_, resp) = t.handle_message(&msg::tclunk(3, 1)).await.unwrap();
1733        assert!(
1734            matches!(resp, Response::Clunk),
1735            "clunk must not be mediated: {resp:?}"
1736        );
1737    }
1738
1739    /// #767 review: `getattr` leaks object metadata (qid/mode/size/mtime) and
1740    /// must be gated by the monitor like every other fid op — it was the one
1741    /// ungated op. A decider that denies `Action::Getattr` must produce EPERM.
1742    #[tokio::test]
1743    async fn injected_decider_blocks_getattr() {
1744        struct DenyGetattr;
1745        impl AccessDecider for DenyGetattr {
1746            fn check(
1747                &self,
1748                _ctx: &SecurityContext,
1749                _object: ObjectRef<'_>,
1750                action: Action,
1751            ) -> bool {
1752                !matches!(action, Action::Getattr)
1753            }
1754
1755            fn audit_denial(
1756                &self,
1757                _ctx: &SecurityContext,
1758                _object: ObjectRef<'_>,
1759                _object_label: Option<SecurityLabel>,
1760                _action: Action,
1761                _reason: ReferenceMonitorDenyReason,
1762            ) {
1763            }
1764        }
1765
1766        let backend = MemoryBackend::default();
1767        backend.add_file("/hello.txt", b"hi");
1768        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(monitor(
1769            permit_session(Level::Secret, ALL_OPS),
1770            Some(label(Level::Public)),
1771            Arc::new(DenyGetattr),
1772        ));
1773
1774        t.handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1775            .await
1776            .unwrap();
1777        let (_, resp) = t
1778            .handle_message(&msg::twalk(2, 0, 1, &["hello.txt"]))
1779            .await
1780            .unwrap();
1781        assert!(
1782            matches!(resp, Response::Walk { .. }),
1783            "walk must still succeed"
1784        );
1785
1786        let (_, resp) = t
1787            .handle_message(&msg::tgetattr(3, 1, u64::MAX))
1788            .await
1789            .unwrap();
1790        match resp {
1791            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
1792            other => panic!("expected Rlerror EPERM for gated getattr, got {other:?}"),
1793        }
1794    }
1795
1796    /// #767 review: a zero-element walk (nwname=0) is a fid *clone*; the new
1797    /// fid must inherit the source fid's cached session rather than being left
1798    /// untracked (which would fail closed under a live monitor and wrongly
1799    /// deny an already-authenticated client).
1800    #[tokio::test]
1801    async fn walk_clone_inherits_source_context() {
1802        let t = Translator::new(Arc::new(MemoryBackend::default()), test_decider())
1803            .with_reference_monitor(monitor(
1804                permit_session(Level::Secret, ALL_OPS),
1805                Some(label(Level::Public)),
1806                Arc::new(AllowAll),
1807            ));
1808
1809        // Attach root fid 0 with the elevated (non-anonymous) session.
1810        t.handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
1811            .await
1812            .unwrap();
1813        // Clone fid 0 -> fid 1 via a zero-element walk.
1814        let (_, resp) = t.handle_message(&msg::twalk(2, 0, 1, &[])).await.unwrap();
1815        assert!(
1816            matches!(resp, Response::Walk { .. }),
1817            "clone walk must succeed"
1818        );
1819
1820        // The clone must carry the source's elevated session, not floor out.
1821        let session = t
1822            .fids
1823            .session(1)
1824            .expect("cloned fid must be tracked in the fid table");
1825        assert_eq!(
1826            session.security_context().level(),
1827            Level::Secret,
1828            "cloned fid must inherit the source's elevated session",
1829        );
1830    }
1831
1832    #[tokio::test]
1833    async fn review_empty_walk_clone_must_not_rebind_memory_fid_to_root() {
1834        struct ByPath;
1835        impl ObjectLabelResolver for ByPath {
1836            fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
1837                match object {
1838                    ObjectRef::Path([]) => Some(label(Level::Secret)),
1839                    ObjectRef::Path(["public.txt"]) => Some(label(Level::Public)),
1840                    ObjectRef::Path(_) | ObjectRef::Cid(_) => None,
1841                }
1842            }
1843        }
1844        struct DenySecretReads;
1845        impl AccessDecider for DenySecretReads {
1846            fn check(&self, _ctx: &SecurityContext, object: ObjectRef<'_>, action: Action) -> bool {
1847                !(action == Action::Read && matches!(object, ObjectRef::Path([])))
1848            }
1849
1850            fn audit_denial(
1851                &self,
1852                _ctx: &SecurityContext,
1853                _object: ObjectRef<'_>,
1854                _object_label: Option<SecurityLabel>,
1855                _action: Action,
1856                _reason: ReferenceMonitorDenyReason,
1857            ) {
1858            }
1859        }
1860
1861        let backend = MemoryBackend::default();
1862        backend.add_file("/public.txt", b"public");
1863        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(
1864            Arc::new(ReferenceMonitor::new(
1865                Arc::new(StaticAuth(permit_session(Level::Secret, ALL_OPS))),
1866                Arc::new(ByPath),
1867                Arc::new(DenySecretReads),
1868            )),
1869        );
1870
1871        t.handle_message(&msg::tattach(1, 0, u32::MAX, "ticket", "/"))
1872            .await
1873            .unwrap();
1874        t.handle_message(&msg::twalk(2, 0, 1, &["public.txt"]))
1875            .await
1876            .unwrap();
1877        t.handle_message(&msg::twalk(3, 1, 2, &[])).await.unwrap();
1878        let (_, read) = t.handle_message(&msg::tread(4, 2, 0, 4096)).await.unwrap();
1879        match read {
1880            Response::Read { data } => assert_eq!(&data, b"public"),
1881            other => panic!(
1882                "clone must still point at public.txt; MemoryBackend rebound it to the Secret root: {other:?}"
1883            ),
1884        }
1885    }
1886
1887    #[tokio::test]
1888    async fn connection_scoped_translators_do_not_share_fid_context() {
1889        let root = Translator::new(Arc::new(MemoryBackend::default()), test_decider())
1890            .with_reference_monitor(monitor(
1891                permit_session(Level::Secret, ALL_OPS),
1892                Some(label(Level::Public)),
1893                Arc::new(AllowAll),
1894            ));
1895        let conn_a = Arc::new(root.connection_scoped());
1896        let conn_b = Arc::new(root.connection_scoped());
1897
1898        conn_a
1899            .handle_message(&msg::tattach(1, 1, u32::MAX, "alice", "/"))
1900            .await
1901            .unwrap();
1902
1903        // conn_b never attached: fid 1 is unknown to its table, and a fid
1904        // outside a verified session fails closed under a live monitor.
1905        let (_, resp) = conn_b
1906            .handle_message(&msg::twalk(2, 1, 2, &[]))
1907            .await
1908            .unwrap();
1909        match resp {
1910            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
1911            other => panic!("expected EPERM for unauthenticated fid reuse, got {other:?}"),
1912        }
1913    }
1914
1915    #[tokio::test]
1916    async fn translator_rejects_conflicting_attach_security_context() {
1917        struct TicketAuth;
1918        #[async_trait]
1919        impl AttachAuthenticator for TicketAuth {
1920            async fn authenticate(
1921                &self,
1922                uname: &str,
1923                _aname: &str,
1924            ) -> std::result::Result<VerifiedAttach, hyprstream_vfs::MountError> {
1925                let identity = if uname == "alice-ticket" {
1926                    "verified-alice"
1927                } else {
1928                    "verified-bob"
1929                };
1930                // Both principals have identical authorization attributes;
1931                // only the verifier-produced identity differs.
1932                Ok(verified_attach(permit_session_as(
1933                    identity,
1934                    Level::Secret,
1935                    ALL_OPS,
1936                )))
1937            }
1938        }
1939
1940        let t = Translator::new(Arc::new(MemoryBackend::default()), test_decider())
1941            .with_reference_monitor(Arc::new(ReferenceMonitor::new(
1942                Arc::new(TicketAuth),
1943                Arc::new(StaticLabels(Some(label(Level::Public)))),
1944                Arc::new(AllowAll),
1945            )));
1946        let (_, resp) = t
1947            .handle_message(&msg::tattach(1, 1, u32::MAX, "alice-ticket", "/"))
1948            .await
1949            .unwrap();
1950        assert!(matches!(resp, Response::Attach { .. }), "got {resp:?}");
1951
1952        let err = t
1953            .handle_message(&msg::tattach(2, 2, u32::MAX, "bob-ticket", "/"))
1954            .await
1955            .unwrap_err();
1956        assert_eq!(
1957            errno_from_error(&err),
1958            EACCES,
1959            "conflicting attach session must be EACCES",
1960        );
1961    }
1962
1963    /// F2: a real `AttachAuthenticator` re-stamps `Instant::now() + ttl` on
1964    /// every verification of the *same* ticket. Re-attaching that identical,
1965    /// still-valid ticket on a second fid of the same connection must be
1966    /// accepted — not rejected as a "conflicting" session. Equality for re-attach
1967    /// detection is over identity (subject + token scope), never the timestamp.
1968    #[tokio::test]
1969    async fn same_valid_ticket_reattach_is_accepted() {
1970        struct FreshDeadlineAuth;
1971        #[async_trait]
1972        impl AttachAuthenticator for FreshDeadlineAuth {
1973            async fn authenticate(
1974                &self,
1975                _uname: &str,
1976                _aname: &str,
1977            ) -> std::result::Result<VerifiedAttach, hyprstream_vfs::MountError> {
1978                // `permit_session` stamps `Instant::now()` into the token, so
1979                // each call yields a distinct deadline — exactly what a real
1980                // verifier does when re-checking the same ticket.
1981                Ok(verified_attach(permit_session(Level::Secret, ALL_OPS)))
1982            }
1983        }
1984
1985        let t = Translator::new(Arc::new(MemoryBackend::default()), test_decider())
1986            .with_reference_monitor(Arc::new(ReferenceMonitor::new(
1987                Arc::new(FreshDeadlineAuth),
1988                Arc::new(StaticLabels(Some(label(Level::Public)))),
1989                Arc::new(AllowAll),
1990            )));
1991
1992        let (_, resp) = t
1993            .handle_message(&msg::tattach(1, 1, u32::MAX, "alice-ticket", "/"))
1994            .await
1995            .unwrap();
1996        assert!(
1997            matches!(resp, Response::Attach { .. }),
1998            "first attach: {resp:?}"
1999        );
2000
2001        // Same ticket, freshly-stamped deadline, new fid on the same connection.
2002        let (_, resp) = t
2003            .handle_message(&msg::tattach(2, 2, u32::MAX, "alice-ticket", "/"))
2004            .await
2005            .unwrap();
2006        assert!(
2007            matches!(resp, Response::Attach { .. }),
2008            "same valid ticket re-attach must be accepted, got {resp:?}",
2009        );
2010    }
2011
2012    #[tokio::test]
2013    async fn denied_monitored_attach_does_not_poison_valid_retry() {
2014        struct TicketAuth;
2015        #[async_trait]
2016        impl AttachAuthenticator for TicketAuth {
2017            async fn authenticate(
2018                &self,
2019                uname: &str,
2020                _aname: &str,
2021            ) -> std::result::Result<VerifiedAttach, hyprstream_vfs::MountError> {
2022                if uname == "valid-ticket" {
2023                    Ok(verified_attach(permit_session_as(
2024                        "verified-alice",
2025                        Level::Secret,
2026                        ALL_OPS,
2027                    )))
2028                } else {
2029                    Err(hyprstream_vfs::MountError::PermissionDenied(
2030                        "invalid ticket".to_owned(),
2031                    ))
2032                }
2033            }
2034        }
2035        let t = Translator::new(Arc::new(MemoryBackend::default()), test_decider())
2036            .with_reference_monitor(Arc::new(ReferenceMonitor::new(
2037                Arc::new(TicketAuth),
2038                Arc::new(StaticLabels(Some(label(Level::Public)))),
2039                Arc::new(AllowAll),
2040            )));
2041        let (_, denied) = t
2042            .handle_message(&msg::tattach(1, 1, u32::MAX, "forged-ticket", "/"))
2043            .await
2044            .unwrap();
2045        assert!(matches!(denied, Response::Error { ecode } if ecode == libc_eperm()));
2046        let (_, accepted) = t
2047            .handle_message(&msg::tattach(2, 2, u32::MAX, "valid-ticket", "/"))
2048            .await
2049            .unwrap();
2050        assert!(
2051            matches!(accepted, Response::Attach { .. }),
2052            "valid retry: {accepted:?}"
2053        );
2054    }
2055
2056    #[tokio::test]
2057    async fn mount_backend_multiname_walk_mediates_the_bound_leaf() {
2058        use hyprstream_vfs::{SyntheticMount, SyntheticNode};
2059
2060        struct ByPath;
2061        impl ObjectLabelResolver for ByPath {
2062            fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
2063                match object {
2064                    ObjectRef::Path([] | ["a"]) => Some(label(Level::Public)),
2065                    ObjectRef::Path(["a", "b"]) => Some(label(Level::Secret)),
2066                    ObjectRef::Path(_) | ObjectRef::Cid(_) => None,
2067                }
2068            }
2069        }
2070        struct DenySecretReads;
2071        impl AccessDecider for DenySecretReads {
2072            fn check(&self, _ctx: &SecurityContext, object: ObjectRef<'_>, action: Action) -> bool {
2073                !(action == Action::Read && matches!(object, ObjectRef::Path(["a", "b"])))
2074            }
2075
2076            fn audit_denial(
2077                &self,
2078                _ctx: &SecurityContext,
2079                _object: ObjectRef<'_>,
2080                _object_label: Option<SecurityLabel>,
2081                _action: Action,
2082                _reason: ReferenceMonitorDenyReason,
2083            ) {
2084            }
2085        }
2086        let root = SyntheticNode::dir().with_child(
2087            "a",
2088            SyntheticNode::dir().with_child("b", SyntheticNode::file(b"secret-at-a-b".to_vec())),
2089        );
2090        let backend = MountBackend::new(
2091            Arc::new(SyntheticMount::new(root)),
2092            hyprstream_rpc::Subject::new("test-subject"),
2093        );
2094        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(
2095            Arc::new(ReferenceMonitor::new(
2096                Arc::new(StaticAuth(permit_session(Level::Secret, ALL_OPS))),
2097                Arc::new(ByPath),
2098                Arc::new(DenySecretReads),
2099            )),
2100        );
2101        t.handle_message(&msg::tattach(1, 0, u32::MAX, "ticket", "/"))
2102            .await
2103            .unwrap();
2104        let (_, walk) = t
2105            .handle_message(&msg::twalk(2, 0, 1, &["a", "b"]))
2106            .await
2107            .unwrap();
2108        match walk {
2109            Response::Walk { qids } => assert_eq!(qids.len(), 2, "one QID per bound component"),
2110            other => panic!("expected successful two-name walk, got {other:?}"),
2111        }
2112        assert_eq!(t.fids.path(1), Some(vec!["a".into(), "b".into()]));
2113        let (_, read) = t.handle_message(&msg::tread(3, 1, 0, 64)).await.unwrap();
2114        assert!(matches!(read, Response::Error { ecode } if ecode == libc_eperm()));
2115    }
2116
2117    /// F1 (defect 1 — intermediate-hop mediation): content-truth labels need
2118    /// not be monotone with depth. Here the `secret` directory hop is
2119    /// Secret-labeled while its `public` leaf is Public. The walk must mediate
2120    /// *every* hop, so a Public subject traversing through the Secret directory
2121    /// is refused at the first hop — not cleared against only the (Public)
2122    /// final destination.
2123    #[tokio::test]
2124    async fn walk_mediates_every_hop_not_just_destination() {
2125        struct ByDepth;
2126        impl ObjectLabelResolver for ByDepth {
2127            fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
2128                match object {
2129                    // The single directory hop is Secret; anything deeper is Public
2130                    // (a non-monotone lattice — the leaf is *less* classified than
2131                    // the directory that contains it).
2132                    ObjectRef::Path([]) => Some(label(Level::Public)),
2133                    ObjectRef::Path([_]) => Some(label(Level::Secret)),
2134                    ObjectRef::Path([_, ..]) => Some(label(Level::Public)),
2135                    ObjectRef::Cid(_) => None,
2136                }
2137            }
2138        }
2139        let backend = MemoryBackend::default();
2140        backend.add_file("/secret", b"classified");
2141        let t = Translator::new(Arc::new(backend), test_decider()).with_reference_monitor(
2142            Arc::new(ReferenceMonitor::new(
2143                Arc::new(StaticAuth(permit_session(Level::Public, ALL_OPS))),
2144                Arc::new(ByDepth),
2145                Arc::new(AllowAll),
2146            )),
2147        );
2148
2149        t.handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
2150            .await
2151            .unwrap();
2152        // Walk through the Secret directory toward the Public leaf. The Public
2153        // subject cannot clear the Secret hop, so the walk must deny — even
2154        // though the *destination* label is Public.
2155        let (_, resp) = t
2156            .handle_message(&msg::twalk(2, 0, 1, &["secret", "public"]))
2157            .await
2158            .unwrap();
2159        match resp {
2160            Response::Error { ecode } => assert_eq!(ecode, libc_eperm()),
2161            other => panic!("expected EPERM at the Secret intermediate hop, got {other:?}"),
2162        }
2163    }
2164
2165    /// F1 (defect 2 — partial-walk path poisoning): 9P permits `nwqid < nwname`.
2166    /// The fid must be tagged with the path the backend *reached* (the
2167    /// returned-qid prefix), never the full requested suffix — otherwise later
2168    /// ops resolve the label of a name the backend never opened (a name↔object
2169    /// TOCTOU). `PartialWalkBackend` reaches only the first component no matter
2170    /// how many are requested.
2171    #[tokio::test]
2172    async fn partial_walk_caches_reached_path_not_requested_suffix() {
2173        use crate::backend::{Backend, OpenResult, StatResult, WalkResult};
2174        struct PartialWalkBackend;
2175        #[async_trait]
2176        impl Backend for PartialWalkBackend {
2177            async fn attach(
2178                &self,
2179                _uname: &str,
2180                _aname: &str,
2181                verified: Option<crate::VerifiedAttach>,
2182            ) -> anyhow::Result<Option<crate::VerifiedAttach>> {
2183                Ok(verified)
2184            }
2185            async fn walk(
2186                &self,
2187                _fid: u32,
2188                _newfid: u32,
2189                _components: &[String],
2190            ) -> anyhow::Result<WalkResult> {
2191                // Reaches exactly one component, regardless of how many walked.
2192                Ok(WalkResult {
2193                    qids: vec![sample_qid(0, 1)],
2194                    reached: vec!["a".to_owned()],
2195                })
2196            }
2197            async fn open(&self, _fid: u32, _flags: u32) -> anyhow::Result<OpenResult> {
2198                unimplemented!("not reached")
2199            }
2200            async fn read(&self, _fid: u32, _offset: u64, _count: u32) -> anyhow::Result<Vec<u8>> {
2201                unimplemented!("not reached")
2202            }
2203            async fn write(&self, _fid: u32, _offset: u64, _data: &[u8]) -> anyhow::Result<u32> {
2204                unimplemented!("not reached")
2205            }
2206            async fn stat(&self, _fid: u32) -> anyhow::Result<StatResult> {
2207                unimplemented!("not reached")
2208            }
2209            async fn readdir(
2210                &self,
2211                _fid: u32,
2212                _offset: u64,
2213                _count: u32,
2214            ) -> anyhow::Result<Vec<u8>> {
2215                unimplemented!("not reached")
2216            }
2217            async fn clunk(&self, _fid: u32) -> anyhow::Result<()> {
2218                Ok(())
2219            }
2220        }
2221
2222        // No monitor: this isolates the path-caching fix from mediation.
2223        let t = Translator::new(Arc::new(PartialWalkBackend), test_decider());
2224        t.handle_message(&msg::tattach(1, 0, u32::MAX, "user", "/"))
2225            .await
2226            .unwrap();
2227        t.handle_message(&msg::twalk(2, 0, 1, &["a", "b"]))
2228            .await
2229            .unwrap();
2230
2231        let cached = t.fids.path(1).expect("newfid must be tracked");
2232        assert_eq!(
2233            cached,
2234            vec!["a".to_string()],
2235            "cached path must be the reached prefix, not the unreached suffix",
2236        );
2237    }
2238
2239    #[tokio::test]
2240    async fn fid_table_tracks_open_and_clunk() {
2241        let table = FidTable::default();
2242        table.insert(7, 0x80, None, Vec::new());
2243        assert_eq!(table.qtype(7), Some(0x80));
2244        table.set_opened(7);
2245        table.remove(7);
2246        assert_eq!(table.qtype(7), None);
2247    }
2248
2249    #[test]
2250    fn qid_helpers() {
2251        let q = sample_qid(0x80, 42);
2252        assert!(q.is_dir());
2253    }
2254
2255    /// A Treaddir over the translator must produce a wire message typed RREADDIR
2256    /// (41), whose payload decodes as standard 9P2000.L dirent records — the
2257    /// exact contract a standard client (Wanix `p9kit`) enforces. Regression
2258    /// guard for the interop fix (previously framed as RREAD=117).
2259    #[tokio::test]
2260    async fn readdir_emits_standard_rreaddir_wire() {
2261        let backend = MemoryBackend::default();
2262        backend.add_file("/one.txt", b"111");
2263        backend.add_file("/two.txt", b"22");
2264        let t = Arc::new(Translator::new(Arc::new(backend), test_decider()));
2265
2266        // Attach fid 0 as the (directory) root, then open + readdir it.
2267        t.handle_message(&msg::tattach(1, 0, u32::MAX, "u", "/"))
2268            .await
2269            .unwrap();
2270        t.handle_message(&msg::tlopen(2, 0, 0)).await.unwrap();
2271        let (tag, resp) = t
2272            .handle_message(&msg::treaddir(3, 0, 0, 8192))
2273            .await
2274            .unwrap();
2275
2276        // Encode to the wire exactly as serve_connection does, and check the
2277        // message-type byte is RREADDIR, not RREAD.
2278        let wire = msg::encode_response(tag, &resp);
2279        assert_eq!(
2280            wire[4],
2281            msg::RREADDIR,
2282            "readdir must be framed as RREADDIR (41)"
2283        );
2284        assert_ne!(
2285            wire[4],
2286            msg::RREAD,
2287            "readdir must NOT be framed as RREAD (117)"
2288        );
2289
2290        // The payload must decode as standard dirent records.
2291        let data = match resp {
2292            Response::Readdir { data } => data,
2293            other => panic!("expected Readdir, got {other:?}"),
2294        };
2295        let entries = msg::parse_readdir_entries(&data).unwrap();
2296        let mut names: Vec<_> = entries.iter().map(|e| e.name.clone()).collect();
2297        names.sort();
2298        assert_eq!(names, vec!["one.txt".to_string(), "two.txt".to_string()]);
2299        // Cookies are 1-based and monotonic.
2300        assert!(entries.iter().all(|e| e.offset >= 1));
2301    }
2302
2303    /// End-to-end hybrid-vsock: a client that speaks the CH multiplexer
2304    /// handshake (`connect <port>\n` → line containing `OK`) over a temp host
2305    /// UDS must, after the preamble is stripped, drive a byte-identical 9P2000.L
2306    /// session (version → attach → walk → open → read) against the shared serve
2307    /// core. This exercises [`Translator::serve_vsock`] +
2308    /// [`hybrid_vsock_handshake`] without needing a real vsock device.
2309    #[tokio::test]
2310    async fn hybrid_vsock_handshake_then_9p_session() {
2311        use std::time::{SystemTime, UNIX_EPOCH};
2312        use tokio::net::UnixStream;
2313
2314        // Unique temp UDS path (no tempfile dep in this crate).
2315        let nanos = SystemTime::now()
2316            .duration_since(UNIX_EPOCH)
2317            .unwrap()
2318            .as_nanos();
2319        let sock =
2320            std::env::temp_dir().join(format!("hs9p-vsock-{}-{nanos}.sock", std::process::id()));
2321        let _ = std::fs::remove_file(&sock);
2322
2323        let backend = MemoryBackend::default();
2324        backend.add_file("/hello.txt", b"hello vsock");
2325        let listener = UnixListener::bind(&sock).expect("bind hybrid-vsock host UDS");
2326        let translator = Translator::new(Arc::new(backend), test_decider());
2327        let server = tokio::spawn(translator.serve_vsock(listener));
2328
2329        // ── Client side ─────────────────────────────────────────────────
2330        let mut client = UnixStream::connect(&sock).await.expect("dial host UDS");
2331
2332        // Hybrid-vsock preamble, exactly as `kata_agent::hybrid_vsock_connect`
2333        // writes it, then read the acknowledgement line and require "OK".
2334        client.write_all(b"connect 1024\n").await.unwrap();
2335        let mut ack = Vec::new();
2336        let mut b = [0u8; 1];
2337        loop {
2338            let n = client.read(&mut b).await.unwrap();
2339            if n == 0 || b[0] == b'\n' {
2340                break;
2341            }
2342            ack.push(b[0]);
2343        }
2344        assert!(
2345            String::from_utf8_lossy(&ack).contains("OK"),
2346            "handshake ack must contain OK, got {ack:?}"
2347        );
2348
2349        // Read one length-prefixed 9P frame off the wire.
2350        async fn read_frame(s: &mut UnixStream) -> Vec<u8> {
2351            let mut len = [0u8; 4];
2352            s.read_exact(&mut len).await.unwrap();
2353            let total = u32::from_le_bytes(len) as usize;
2354            let mut buf = vec![0u8; total];
2355            buf[..4].copy_from_slice(&len);
2356            s.read_exact(&mut buf[4..]).await.unwrap();
2357            buf
2358        }
2359
2360        // Tversion → Rversion.
2361        client
2362            .write_all(&msg::tversion(1, MSG_SIZE, "9P2000.L"))
2363            .await
2364            .unwrap();
2365        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2366        assert!(
2367            matches!(resp, Response::Version { .. }),
2368            "expected Rversion, got {resp:?}"
2369        );
2370
2371        // Tattach fid 0 as root.
2372        client
2373            .write_all(&msg::tattach(2, 0, u32::MAX, "u", "/"))
2374            .await
2375            .unwrap();
2376        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2377        assert!(
2378            matches!(resp, Response::Attach { .. }),
2379            "expected Rattach, got {resp:?}"
2380        );
2381
2382        // Twalk to the file, Tlopen, Tread.
2383        client
2384            .write_all(&msg::twalk(3, 0, 1, &["hello.txt"]))
2385            .await
2386            .unwrap();
2387        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2388        assert!(
2389            matches!(resp, Response::Walk { .. }),
2390            "expected Rwalk, got {resp:?}"
2391        );
2392
2393        client.write_all(&msg::tlopen(4, 1, 0)).await.unwrap();
2394        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2395        assert!(
2396            matches!(resp, Response::Lopen { .. }),
2397            "expected Rlopen, got {resp:?}"
2398        );
2399
2400        client.write_all(&msg::tread(5, 1, 0, 64)).await.unwrap();
2401        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2402        match resp {
2403            Response::Read { data } => assert_eq!(&data, b"hello vsock"),
2404            other => panic!("expected Rread with payload, got {other:?}"),
2405        }
2406
2407        drop(client);
2408        server.abort();
2409        let _ = std::fs::remove_file(&sock);
2410    }
2411
2412    /// RAW (no-handshake) vsock: a guest-initiated client that connects to a
2413    /// per-port host UDS and sends its 9P `Tversion` **immediately** — with NO
2414    /// `connect <port>\n` preamble — must drive a byte-identical 9P2000.L session.
2415    /// This is the #741 guest→host direction: the raw serve path must treat the
2416    /// very first bytes as 9P and never consume a preamble. Exercises
2417    /// [`Translator::serve_vsock_raw`] / [`RawVsockListener`].
2418    #[tokio::test]
2419    async fn raw_vsock_no_preamble_9p_session() {
2420        use std::time::{SystemTime, UNIX_EPOCH};
2421        use tokio::net::UnixStream;
2422
2423        let nanos = SystemTime::now()
2424            .duration_since(UNIX_EPOCH)
2425            .unwrap()
2426            .as_nanos();
2427        let sock =
2428            std::env::temp_dir().join(format!("hs9p-rawvsock-{}-{nanos}.sock", std::process::id()));
2429        let _ = std::fs::remove_file(&sock);
2430
2431        let backend = MemoryBackend::default();
2432        backend.add_file("/hello.txt", b"hello raw");
2433        let listener = UnixListener::bind(&sock).expect("bind raw vsock per-port host UDS");
2434        let translator = Translator::new(Arc::new(backend), test_decider());
2435        let server = tokio::spawn(translator.serve_vsock_raw(listener));
2436
2437        // ── Client (guest) side ─────────────────────────────────────────
2438        let mut client = UnixStream::connect(&sock)
2439            .await
2440            .expect("dial per-port host UDS");
2441
2442        async fn read_frame(s: &mut UnixStream) -> Vec<u8> {
2443            let mut len = [0u8; 4];
2444            s.read_exact(&mut len).await.unwrap();
2445            let total = u32::from_le_bytes(len) as usize;
2446            let mut buf = vec![0u8; total];
2447            buf[..4].copy_from_slice(&len);
2448            s.read_exact(&mut buf[4..]).await.unwrap();
2449            buf
2450        }
2451
2452        // FIRST bytes on the wire are 9P Tversion — NO `connect <port>\n`
2453        // preamble. If the raw path erroneously stripped a preamble it would
2454        // swallow these bytes and the session would hang / fail here.
2455        client
2456            .write_all(&msg::tversion(1, MSG_SIZE, "9P2000.L"))
2457            .await
2458            .unwrap();
2459        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2460        assert!(
2461            matches!(resp, Response::Version { .. }),
2462            "raw path must treat the first bytes as 9P Tversion, got {resp:?}"
2463        );
2464
2465        // Rest of the session proves the stream was never desynchronized.
2466        client
2467            .write_all(&msg::tattach(2, 0, u32::MAX, "u", "/"))
2468            .await
2469            .unwrap();
2470        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2471        assert!(
2472            matches!(resp, Response::Attach { .. }),
2473            "expected Rattach, got {resp:?}"
2474        );
2475
2476        client
2477            .write_all(&msg::twalk(3, 0, 1, &["hello.txt"]))
2478            .await
2479            .unwrap();
2480        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2481        assert!(
2482            matches!(resp, Response::Walk { .. }),
2483            "expected Rwalk, got {resp:?}"
2484        );
2485
2486        client.write_all(&msg::tlopen(4, 1, 0)).await.unwrap();
2487        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2488        assert!(
2489            matches!(resp, Response::Lopen { .. }),
2490            "expected Rlopen, got {resp:?}"
2491        );
2492
2493        client.write_all(&msg::tread(5, 1, 0, 64)).await.unwrap();
2494        let (_, resp) = msg::parse_response(&read_frame(&mut client).await).unwrap();
2495        match resp {
2496            Response::Read { data } => assert_eq!(&data, b"hello raw"),
2497            other => panic!("expected Rread with payload, got {other:?}"),
2498        }
2499
2500        drop(client);
2501        server.abort();
2502        let _ = std::fs::remove_file(&sock);
2503    }
2504
2505    /// A malformed preamble must drop only that connection: the accept loop
2506    /// stays live and a well-behaved client that connects afterward still gets
2507    /// served. Guards the "retry, don't propagate" contract in
2508    /// [`HybridVsockListener::accept_conn`].
2509    #[tokio::test]
2510    async fn hybrid_vsock_bad_preamble_does_not_kill_listener() {
2511        use std::time::{SystemTime, UNIX_EPOCH};
2512        use tokio::net::UnixStream;
2513
2514        let nanos = SystemTime::now()
2515            .duration_since(UNIX_EPOCH)
2516            .unwrap()
2517            .as_nanos();
2518        let sock = std::env::temp_dir().join(format!(
2519            "hs9p-vsock-bad-{}-{nanos}.sock",
2520            std::process::id()
2521        ));
2522        let _ = std::fs::remove_file(&sock);
2523
2524        let listener = UnixListener::bind(&sock).unwrap();
2525        let translator = Translator::new(Arc::new(MemoryBackend::default()), test_decider());
2526        let server = tokio::spawn(translator.serve_vsock(listener));
2527
2528        // First client sends garbage; server should drop it and keep listening.
2529        let mut bad = UnixStream::connect(&sock).await.unwrap();
2530        bad.write_all(b"garbage not a preamble\n").await.unwrap();
2531        // Server closes this connection without acknowledging; read returns EOF.
2532        let mut b = [0u8; 1];
2533        let _ = bad.read(&mut b).await; // 0 (EOF) or Err — either is fine.
2534        drop(bad);
2535
2536        // Second client completes a valid handshake — proving the loop survived.
2537        let mut good = UnixStream::connect(&sock).await.unwrap();
2538        good.write_all(b"connect 1024\n").await.unwrap();
2539        let mut ack = Vec::new();
2540        let mut byte = [0u8; 1];
2541        loop {
2542            let n = good.read(&mut byte).await.unwrap();
2543            if n == 0 || byte[0] == b'\n' {
2544                break;
2545            }
2546            ack.push(byte[0]);
2547        }
2548        assert!(
2549            String::from_utf8_lossy(&ack).contains("OK"),
2550            "listener must survive a bad handshake and serve the next client"
2551        );
2552
2553        drop(good);
2554        server.abort();
2555        let _ = std::fs::remove_file(&sock);
2556    }
2557
2558    // ── Attach-time mount ticket (H1b / #765) ───────────────────────────
2559
2560    /// A fake [`AttachAuthorizer`] mirroring the H1b `Tattach.uname` ticket
2561    /// check PLUS the `aname` export-selection gate: one fixed ticket string
2562    /// maps to a narrowed Subject, and only the default export (empty `aname`)
2563    /// is granted; anything else is denied with `PermissionDenied` (→ `EACCES`).
2564    struct FakeTicketAuth;
2565    #[async_trait::async_trait]
2566    impl crate::mount_backend::AttachAuthorizer for FakeTicketAuth {
2567        async fn authenticate(
2568            &self,
2569            uname: &str,
2570            aname: &str,
2571        ) -> std::result::Result<VerifiedAttach, hyprstream_vfs::MountError> {
2572            let identity = match uname {
2573                "good-ticket" => "alice",
2574                "other-ticket" => "bob",
2575                _ => {
2576                    return Err(hyprstream_vfs::MountError::PermissionDenied(
2577                        "bad ticket".into(),
2578                    ))
2579                }
2580            };
2581            // Export-selection gate (#877 fail-closed contract): only the
2582            // default export is granted today; an explicit `aname` selecting any
2583            // other export denies — there is NO fallback to the default.
2584            if aname.is_empty() {
2585                Ok(verified_attach(permit_session_as(
2586                    identity,
2587                    Level::Secret,
2588                    ALL_OPS,
2589                )))
2590            } else {
2591                Err(hyprstream_vfs::MountError::PermissionDenied(format!(
2592                    "export {aname:?} not granted by ticket"
2593                )))
2594            }
2595        }
2596    }
2597
2598    fn authorized_translator() -> Arc<Translator> {
2599        use hyprstream_vfs::{SyntheticMount, SyntheticNode};
2600        let root =
2601            SyntheticNode::dir().with_child("hello.txt", SyntheticNode::file(b"hi alice".to_vec()));
2602        let mount: Arc<dyn hyprstream_vfs::Mount> = Arc::new(SyntheticMount::new(root));
2603        Arc::new(Translator::from_mount_authorized(
2604            mount,
2605            Arc::new(FakeTicketAuth),
2606            test_decider(),
2607        ))
2608    }
2609
2610    /// A valid ticket in `Tattach.uname` binds the session Subject and the
2611    /// attach + subsequent ops succeed (the H1b happy path over the shared
2612    /// `handle_message` core).
2613    #[tokio::test]
2614    async fn attach_ticket_valid_binds_subject_and_serves() {
2615        let t = authorized_translator();
2616        let (_, resp) = t
2617            .handle_message(&msg::tattach(1, 0, u32::MAX, "good-ticket", ""))
2618            .await
2619            .unwrap();
2620        assert!(
2621            matches!(resp, Response::Attach { .. }),
2622            "valid ticket must attach: {resp:?}"
2623        );
2624
2625        // The bound Subject now threads through walk/open/read.
2626        let (_, resp) = t
2627            .handle_message(&msg::twalk(2, 0, 1, &["hello.txt"]))
2628            .await
2629            .unwrap();
2630        assert!(matches!(resp, Response::Walk { .. }), "got {resp:?}");
2631        let (_, resp) = t.handle_message(&msg::tlopen(3, 1, 0)).await.unwrap();
2632        assert!(matches!(resp, Response::Lopen { .. }), "got {resp:?}");
2633        let (_, resp) = t.handle_message(&msg::tread(4, 1, 0, 64)).await.unwrap();
2634        match resp {
2635            Response::Read { data } => assert_eq!(&data, b"hi alice"),
2636            other => panic!("expected Rread, got {other:?}"),
2637        }
2638    }
2639
2640    /// An invalid ticket in `Tattach.uname` fails the attach; the translator
2641    /// maps the authorizer's `PermissionDenied` to an `Rlerror` `EACCES` — no
2642    /// fid or mount handle is ever created.
2643    #[tokio::test]
2644    async fn attach_ticket_denied_returns_eacces() {
2645        let t = authorized_translator();
2646        let err = t
2647            .handle_message(&msg::tattach(1, 0, u32::MAX, "forged", ""))
2648            .await
2649            .unwrap_err();
2650        assert_eq!(
2651            errno_from_error(&err),
2652            EACCES,
2653            "denied ticket must be EACCES"
2654        );
2655    }
2656
2657    /// An empty `uname` (no ticket presented) is likewise denied — the ticket is
2658    /// mandatory on the WebTransport plane.
2659    #[tokio::test]
2660    async fn attach_empty_ticket_denied() {
2661        let t = authorized_translator();
2662        let err = t
2663            .handle_message(&msg::tattach(1, 0, u32::MAX, "", ""))
2664            .await
2665            .unwrap_err();
2666        assert_eq!(
2667            errno_from_error(&err),
2668            EACCES,
2669            "missing ticket must be EACCES"
2670        );
2671    }
2672
2673    /// A second attach may repeat the same ticket, but it must not re-scope the
2674    /// session to a different valid Subject.
2675    #[tokio::test]
2676    async fn second_attach_conflicting_ticket_denied() {
2677        let t = authorized_translator();
2678        let (_, resp) = t
2679            .handle_message(&msg::tattach(1, 0, u32::MAX, "good-ticket", ""))
2680            .await
2681            .unwrap();
2682        assert!(matches!(resp, Response::Attach { .. }), "got {resp:?}");
2683
2684        let err = t
2685            .handle_message(&msg::tattach(2, 0, u32::MAX, "other-ticket", ""))
2686            .await
2687            .unwrap_err();
2688        assert_eq!(
2689            errno_from_error(&err),
2690            EACCES,
2691            "conflicting attach must be EACCES"
2692        );
2693    }
2694
2695    /// A valid ticket presenting an `aname` for an export it did not grant fails
2696    /// the attach; the authorizer's `PermissionDenied` maps to an `Rlerror`
2697    /// `EACCES` before any fid or mount handle is ever created. Fail-closed:
2698    /// there is NO fallback to a default export after an explicit selector
2699    /// (#877/#1071 contract).
2700    #[tokio::test]
2701    async fn attach_aname_denied_returns_eacces() {
2702        let t = authorized_translator();
2703        let err = t
2704            .handle_message(&msg::tattach(
2705                1,
2706                0,
2707                u32::MAX,
2708                "good-ticket",
2709                "forbidden-export",
2710            ))
2711            .await
2712            .unwrap_err();
2713        assert_eq!(
2714            errno_from_error(&err),
2715            EACCES,
2716            "denied aname must be EACCES"
2717        );
2718        // The root fid (fid 0, the attach target) must not exist after a denied
2719        // attach — the deny happened in `backend.attach` before the translator
2720        // bound any fid (the fail-closed contract: no fid leak on a denied
2721        // export).
2722        assert!(
2723            t.fids.qtype(0).is_none(),
2724            "no fid may be created for a denied aname"
2725        );
2726    }
2727
2728    /// Fail-closed: an op arriving before a successful attach binds the Subject
2729    /// must not reach the mount (the `OnceCell` is unset).
2730    #[tokio::test]
2731    async fn op_before_attach_fails_closed() {
2732        let t = authorized_translator();
2733        // No Tattach: a walk cannot resolve a caller and must error, not serve.
2734        let err = t
2735            .handle_message(&msg::twalk(1, 0, 1, &["hello.txt"]))
2736            .await
2737            .unwrap_err();
2738        // Untyped bookkeeping error (no MountError) → EIO, never a success.
2739        assert_eq!(errno_from_error(&err), EIO);
2740    }
2741}