Skip to main content

hyprstream_core/server/routes/
ninep.rs

1//! 9P-over-WebSocket export (H1a / #764).
2//!
3//! Serves hyprstream's Subject-scoped VFS as **9P2000.L over WebSocket** on the
4//! existing axum HTTP server, wire-compatible with `wanix serve`, so stock
5//! wanix 0.4 / apptron mount a hyprstream host with zero client glue.
6//!
7//! Two routes (registered in [`crate::server`]):
8//!
9//! - `GET /.well-known/export9p` — discovery. Advertises the `/9p` WebSocket
10//!   endpoint, the mount-ticket query parameter, and the wire so a mounting
11//!   client (S4 `WanixSessionContext`) can construct the `wss://…/9p?ticket=…`
12//!   URL. (Upstream's `/.well-known/export9p` is a `mux`-session endpoint for
13//!   the *reverse* direction — a browser exporting **its** namespace outward;
14//!   H1a's interop path is the raw-frame `/9p` endpoint that stock wanix
15//!   `import` binds connect to directly, so we serve a JSON discovery document
16//!   here instead of the mux protocol. See the PR "WIRE CONTRACT" section.)
17//! - `GET /9p` — WebSocket upgrade → a ws↔9p byte pump feeding the
18//!   transport-agnostic [`Translator::serve_connection`] core over a
19//!   [`MountBackend`] (the SAME core the UDS/vsock transports use — not a
20//!   fork). Binary frames carry framed 9P2000.L messages; the pump tolerates
21//!   arbitrary chunking (`P9PortReadWriter` on the wanix side buffers).
22//!
23//! ## Auth (reuses the existing chain)
24//!
25//! The mount ticket rides the URL query (`?ticket=<at+jwt>`) because a browser
26//! `WebSocket` cannot set request headers. It is validated at the WS upgrade
27//! via [`crate::server::middleware::verify_resource_token_claims`] — the exact same
28//! chain `auth_middleware` uses (issuer routing, Ed25519/ML-DSA signature +
29//! audience validation, JTI revocation). The validated `sub` becomes the
30//! session [`Subject`], threaded onto every 9P op by [`MountBackend`] (the
31//! single MAC policy-enforcement point). Denials surface as `Rlerror` errnos.
32//!
33//! ## Server-owned liveness (H1a hard requirement)
34//!
35//! A dead browser peer is NOT observable to the far side (a closed port yields
36//! no EOF), so a naive server would leak the 9P session forever. The pump
37//! therefore OWNS liveness via **server-driven WS ping/pong keepalive**: it
38//! sends a WS `Ping` every [`PING_INTERVAL`] (30s) and closes the session after
39//! [`MAX_MISSED_PONGS`] consecutive unanswered pings (~90s). Closing drops the
40//! pump's write half, which surfaces as EOF to `serve_connection` and tears the
41//! 9P session down cleanly. A dead peer stops ponging and is reaped in ~90s; a
42//! HEALTHY-but-idle mount survives **indefinitely** because pongs keep flowing
43//! with zero 9P traffic (and any inbound frame — pong or data — counts as
44//! liveness). The client's WS `close` event is the browser's unmount trigger,
45//! so teardown stays 100% server-driven with no client keepalive. The server
46//! never relies on the client noticing.
47
48use std::collections::BTreeMap;
49use std::sync::{Arc, OnceLock};
50use std::time::{Duration, Instant};
51
52use async_trait::async_trait;
53use axum::{
54    extract::{
55        ws::{Message, WebSocket, WebSocketUpgrade},
56        Query, State,
57    },
58    http::{HeaderMap, StatusCode},
59    response::{IntoResponse, Response},
60    Json,
61};
62use futures::{SinkExt, StreamExt};
63use hyprstream_9p::{
64    Action as NinePAction, AttachAuthorizer, SessionContext, Translator, VerifiedAttach,
65    VerifiedAttachIdentity, VerifiedTokenScope,
66};
67use hyprstream_rpc::auth::mac::{SubjectContextClaims as _, VerifiedKeyMaterial};
68use hyprstream_rpc::transport::quinn_transport::{NinePWtHandler, NinePWtStream};
69use hyprstream_rpc::Subject;
70use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Stat, SyntheticMount, SyntheticNode};
71use serde::{Deserialize, Serialize};
72use tokio::io::{split, AsyncReadExt, AsyncWriteExt};
73use tracing::{debug, info, warn};
74
75use super::ninep_canonical_read::CanonicalReadMount;
76use crate::server::state::{ResourceAuthState, ServerState};
77
78const PLANE_WS: &str = "ws";
79const PLANE_WEBTRANSPORT: &str = "webtransport";
80const ROOT_NAMESPACE_PATH: &str = "/";
81
82/// Query-param name carrying the short-lived mount ticket. Kept in sync with
83/// the discovery document and the design doc's `wss://…/9p?ticket=…` example.
84const TICKET_PARAM: &str = "ticket";
85
86/// URL path the 9P plane is served on. The single authoritative source for the
87/// `/9p` selector on the SERVE side: both [`Export9pDiscovery`] and the
88/// [`WirePlaneTable`] read it, and the route in [`crate::server`] registers it,
89/// so the plane advertises its own path rather than the value being duplicated
90/// as a constant on both the dial and serve sides (the retire of the dial-side
91/// `crate::dial::*_PATH` constants against this table is #820's job).
92pub const NINEP_PATH: &str = "/9p";
93
94/// Interval between server-sent WS keepalive `Ping`s. A HEALTHY-but-idle mount
95/// stays alive indefinitely as long as the peer keeps ponging (see module docs).
96const PING_INTERVAL: Duration = Duration::from_secs(30);
97
98/// Consecutive unanswered pings tolerated before the server reaps the session.
99/// With [`PING_INTERVAL`] = 30s this is ~90s of silence → dead-peer detection.
100const MAX_MISSED_PONGS: u32 = 3;
101
102/// Duplex buffer bridging the WS pump to the 9P serve core. Sized to comfortably
103/// hold a full negotiated 9P msize plus headroom.
104const DUPLEX_BUF: usize = 64 * 1024;
105
106// ─────────────────────────────────────────────────────────────────────────────
107// Discovery: GET /.well-known/export9p
108// ─────────────────────────────────────────────────────────────────────────────
109
110/// Discovery document for the 9P-over-WebSocket export.
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct Export9pDiscovery {
113    /// 9P dialect served (`9P2000.L`).
114    pub protocol: String,
115    /// Transport (`websocket`).
116    pub transport: String,
117    /// WebSocket upgrade path (`/9p`).
118    pub endpoint: String,
119    /// Query-param name for the mount ticket (`ticket`).
120    pub ticket_param: String,
121    /// Required `Sec-WebSocket-Protocol` subprotocol, or `null` for none.
122    /// H1a requires none — stock wanix opens `new WebSocket(src)` with no
123    /// subprotocol.
124    pub subprotocol: Option<String>,
125    /// Wire framing: raw length-prefixed 9P2000.L messages, one per binary
126    /// frame from the server (arbitrary chunking tolerated inbound).
127    pub wire: String,
128    /// The upstream tool this endpoint is wire-compatible with.
129    pub compatible_with: String,
130}
131
132impl Default for Export9pDiscovery {
133    fn default() -> Self {
134        Self {
135            protocol: "9P2000.L".to_owned(),
136            transport: "websocket".to_owned(),
137            endpoint: NINEP_PATH.to_owned(),
138            ticket_param: TICKET_PARAM.to_owned(),
139            subprotocol: None,
140            wire: "raw-9p-binary-frames".to_owned(),
141            compatible_with: "wanix serve".to_owned(),
142        }
143    }
144}
145
146/// `GET /.well-known/export9p` — advertise the 9P-over-WS export.
147pub async fn export9p_metadata() -> impl IntoResponse {
148    Json(Export9pDiscovery::default())
149}
150
151// ─────────────────────────────────────────────────────────────────────────────
152// Discovery: GET /.well-known/planes (wire-plane table, #821 / epic #809)
153// ─────────────────────────────────────────────────────────────────────────────
154
155/// One wire plane's advertisement in the [`WirePlaneTable`].
156///
157/// A "plane" is a non-file wire endpoint the daemon serves (9P, moq, …). This
158/// is the cs/ndb analog: a client resolves a plane NAME → its current path +
159/// carriers here, then dials/mounts wherever it wants. The server advertises;
160/// it never dictates that the client hardcode the path.
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
162pub struct WirePlane {
163    /// URL path the plane is currently served on (e.g. `/9p`, `/moq`). This is
164    /// the value a client resolves against instead of a hardcoded constant.
165    pub path: String,
166    /// Carriers the plane is reachable over, most-preferred first. `ws` =
167    /// WebSocket (browser-native), `webtransport` = WebTransport over QUIC/H3.
168    pub transports: Vec<String>,
169    /// Query-param carrying the plane's auth/mount ticket, if it needs one.
170    /// Omitted from JSON when the plane is unauthenticated at the transport.
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub ticket_param: Option<String>,
173    /// Protocol/dialect tag for the plane (e.g. `9P2000.L`), if meaningful.
174    /// Omitted when the plane has no single dialect to name.
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub protocol: Option<String>,
177}
178
179/// Wire-plane discovery table served at `GET /.well-known/planes` (#821).
180///
181/// Enumerates every non-file wire plane the daemon serves, keyed by a stable
182/// plane NAME (`9p`, `moq`, …) → its current [`WirePlane`] advertisement. This
183/// is the source of truth a client resolves the `/9p` (and any future) selector
184/// against; the serve side ADVERTISES the path here rather than the value being
185/// duplicated as a hardcoded constant on both the dial and serve sides.
186///
187/// Companions — does not replace — [`Export9pDiscovery`] at
188/// `/.well-known/export9p`: the `9p` entry here is derived from the SAME
189/// [`Export9pDiscovery::default`] values (`endpoint`/`ticket_param`/`protocol`),
190/// so the two documents can never drift and the existing export9p contract
191/// (which 1:3.0's `WsMountTransport` reads today) is untouched.
192///
193/// `BTreeMap` gives a deterministic, stably-ordered JSON object.
194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195pub struct WirePlaneTable {
196    /// Plane name → advertisement. Stably ordered.
197    pub planes: BTreeMap<String, WirePlane>,
198}
199
200impl WirePlaneTable {
201    /// Build the table from the daemon's actually-registered planes.
202    ///
203    /// The `9p` entry is derived from [`Export9pDiscovery::default`] so it stays
204    /// byte-for-byte consistent with the companion export9p document. The `moq`
205    /// streaming plane advertises [`hyprstream_rpc::dial::MOQ_PATH`] (its
206    /// existing WebTransport selector) so this table is authoritative for it
207    /// too. Both planes list the carriers they are actually reachable over: the
208    /// 9P plane over WebSocket (H1a, `/9p`) and WebTransport (H1b, #765), the
209    /// moq plane over WebTransport.
210    pub fn current() -> Self {
211        let export9p = Export9pDiscovery::default();
212
213        let mut planes = BTreeMap::new();
214        planes.insert(
215            "9p".to_owned(),
216            WirePlane {
217                path: export9p.endpoint.clone(),
218                transports: vec!["ws".to_owned(), "webtransport".to_owned()],
219                ticket_param: Some(export9p.ticket_param.clone()),
220                protocol: Some(export9p.protocol.clone()),
221            },
222        );
223        planes.insert(
224            "moq".to_owned(),
225            WirePlane {
226                path: hyprstream_rpc::dial::MOQ_PATH.to_owned(),
227                transports: vec!["webtransport".to_owned()],
228                ticket_param: None,
229                protocol: None,
230            },
231        );
232
233        Self { planes }
234    }
235}
236
237impl Default for WirePlaneTable {
238    fn default() -> Self {
239        Self::current()
240    }
241}
242
243/// `GET /.well-known/planes` — advertise the wire-plane discovery table (#821).
244pub async fn wire_planes_metadata() -> impl IntoResponse {
245    Json(WirePlaneTable::current())
246}
247
248// ─────────────────────────────────────────────────────────────────────────────
249// Mount: GET /9p (WebSocket upgrade)
250// ─────────────────────────────────────────────────────────────────────────────
251
252/// Query params on the `/9p` WebSocket upgrade.
253#[derive(Debug, Deserialize)]
254pub struct NinePQuery {
255    /// Short-lived mount ticket, minted by `POST /oauth/mount-ticket`.
256    /// Required — a missing/invalid ticket is rejected pre-upgrade.
257    #[serde(default)]
258    pub ticket: Option<String>,
259}
260
261/// `GET /9p` — validate the mount ticket, then upgrade to a 9P-over-WS session.
262///
263/// The ticket is validated BEFORE the upgrade so an unauthenticated client gets
264/// a clean HTTP `401` rather than a dangling WebSocket. On success the session's
265/// [`Subject`] is bound for the whole connection and enforced per-op by
266/// [`MountBackend`].
267pub async fn ninep_ws(
268    State(state): State<ServerState>,
269    Query(q): Query<NinePQuery>,
270    headers: HeaderMap,
271    ws: WebSocketUpgrade,
272) -> Response {
273    let ticket = match q.ticket.as_deref() {
274        Some(t) if !t.is_empty() => t,
275        _ => {
276            debug!("9P WS upgrade rejected: missing mount ticket");
277            return (StatusCode::UNAUTHORIZED, "missing mount ticket").into_response();
278        }
279    };
280
281    let verified =
282        match validate_ticket(&state, ticket, &headers, PLANE_WS, ROOT_NAMESPACE_PATH).await {
283            Ok(s) => s,
284            Err(reason) => {
285                warn!(reason, "9P WS upgrade rejected: invalid mount ticket");
286                return (StatusCode::UNAUTHORIZED, "invalid mount ticket").into_response();
287            }
288        };
289
290    let mount: Arc<dyn Mount> = if state.config.ninep_canonical_read.is_some() {
291        match CanonicalReadMount::new(&state, verified.subject().clone(), ticket.to_owned()) {
292            Ok(mount) => Arc::new(mount),
293            Err(_) => {
294                return (
295                    StatusCode::SERVICE_UNAVAILABLE,
296                    "canonical export unavailable",
297                )
298                    .into_response()
299            }
300        }
301    } else {
302        build_export_mount(&state, verified.subject())
303    };
304    // Install the full monitor with the same VerifiedAttach bundle already
305    // derived from the mount ticket. The operator control starts floor-only.
306    let monitor = crate::mac::production_ninep_reference_monitor(
307        Arc::clone(&state.ninep_decider),
308        Arc::new(PreverifiedAttachAuthorizer(verified.clone())),
309    );
310    // `from_mount` wraps the Subject-scoped mount in a `MountBackend` and threads
311    // `subject` onto every backend op — the same seam UDS/vsock use.
312    let translator = Arc::new(
313        Translator::from_mount(
314            mount,
315            verified.subject().clone(),
316            Arc::clone(&state.ninep_decider),
317        )
318        .with_reference_monitor(monitor)
319        .with_activation_control(),
320    );
321
322    // No subprotocol negotiation: stock wanix connects with none.
323    ws.on_upgrade(move |socket| serve_9p_websocket(socket, translator, PING_INTERVAL))
324}
325
326/// Validate a mount ticket to a session [`Subject`], reusing the server auth
327/// chain ([`verify_resource_token_claims`](crate::server::middleware::verify_resource_token_claims)).
328///
329/// Real controls enforced here: Ed25519/ML-DSA signature, audience binding to
330/// this resource, expiry, and JTI revocation (all inside `verify_resource_token_claims`),
331/// plus subject-name validation. The `sub` becomes the session Subject.
332///
333/// One-shot replay prevention is enforced for mount tickets. Explicit browser
334/// `Origin` binding beyond the JWT `aud` remains a separate design concern.
335async fn validate_ticket(
336    state: &ServerState,
337    ticket: &str,
338    _headers: &HeaderMap,
339    plane: &str,
340    namespace_path: &str,
341) -> Result<VerifiedAttach, &'static str> {
342    let resource_state = state.resource_auth_state();
343    verify_mount_ticket(&resource_state, ticket, plane, namespace_path).await
344}
345
346/// Transport-agnostic core of mount-ticket validation, shared by H1a's
347/// URL-query path ([`validate_ticket`]) and H1b's `Tattach.uname` path
348/// ([`TicketAttachAuthorizer`]). Both present the same mount-ticket JWT;
349/// only *where* it rides differs (WS query vs 9P attach), so the verification —
350/// signature, expiry, revocation (in `verify_resource_token_claims`), explicit
351/// mount-capability marker, then subject-name validation — is identical.
352async fn verify_mount_ticket(
353    state: &ResourceAuthState,
354    ticket: &str,
355    plane: &str,
356    namespace_path: &str,
357) -> Result<VerifiedAttach, &'static str> {
358    let claims = crate::server::middleware::verify_resource_token_claims(state, ticket).await?;
359    // Mount tickets are local, MAC-bound credentials. Federation can attest an
360    // identity for ordinary resource access, but cannot consume this shared
361    // replay barrier or choose a local tenant/clearance.
362    if claims.iss != state.oauth_issuer_url {
363        return Err("mount ticket issuer is not local");
364    }
365    if !crate::services::oauth::mount_ticket::is_mount_ticket_for(&claims, plane, namespace_path) {
366        return Err("token is not valid for this 9P plane/path");
367    }
368    let atproto_issuer =
369        crate::services::oauth::state::canonical_issuer_origin(&state.oauth_issuer_url)
370            .unwrap_or_else(|| state.oauth_issuer_url.clone());
371    let local_issuers = [&*state.oauth_issuer_url, atproto_issuer.as_str()];
372    let subject = claims.subject(&local_issuers);
373    subject
374        .validate()
375        .map_err(|_| "subject validation failed")?;
376    match subject.name() {
377        Some(n) if !n.is_empty() => {}
378        _ => return Err("empty subject"),
379    }
380    // Validate all authority and time admission before consuming one-use
381    // replay state. The bounded duration also makes subsequent Instant
382    // arithmetic safe from attacker-controlled overflow.
383    claims
384        .tenant
385        .as_deref()
386        .filter(|tenant| !tenant.is_empty() && *tenant != "*")
387        .ok_or("mount ticket missing authority-bound tenant")?;
388    claims
389        .security_context(VerifiedKeyMaterial::Classical)
390        .ok_or("mount ticket missing verified Claims clearance")?;
391    let Some(jti) = claims.jti.as_ref() else {
392        return Err("mount ticket missing jti");
393    };
394    let now = chrono::Utc::now().timestamp();
395    let max_lifetime = crate::services::oauth::mount_ticket::MOUNT_TICKET_TTL;
396    let lifetime = claims
397        .exp
398        .checked_sub(claims.iat)
399        .filter(|lifetime| *lifetime > 0 && *lifetime <= max_lifetime)
400        .ok_or("mount ticket lifetime is invalid")?;
401    let remaining = claims
402        .exp
403        .checked_sub(now)
404        .filter(|remaining| *remaining > 0 && *remaining <= max_lifetime)
405        .ok_or("mount ticket expired")?;
406    if claims.iat > now || lifetime > max_lifetime {
407        return Err("mount ticket issued in the future");
408    }
409    let ttl = u64::try_from(remaining).map_err(|_| "mount ticket lifetime is invalid")?;
410    let result = state.dpop_jti_seen.insert_if_absent_no_evict(
411        crate::services::oauth::replay_key::mount_ticket_jti(jti),
412        (),
413        Duration::from_secs(ttl),
414    );
415    if result != hyprstream_util::InsertIfAbsentNoEvictResult::Inserted {
416        crate::services::oauth::replay_metrics::record_rejection(
417            crate::services::oauth::replay_metrics::DPOP,
418            result,
419        );
420        if crate::services::oauth::replay_metrics::should_warn_full(
421            crate::services::oauth::replay_metrics::DPOP,
422            result,
423        ) {
424            warn!("DPoP replay barrier is full; refusing fresh mount ticket");
425        }
426        return Err("mount ticket already used");
427    }
428    verified_attach_from_claims(claims, subject)
429}
430
431const NINEP_ALL_ACTIONS: &[NinePAction] = &[
432    NinePAction::Attach,
433    NinePAction::Walk,
434    NinePAction::Open,
435    NinePAction::Read,
436    NinePAction::Write,
437    NinePAction::Getattr,
438    NinePAction::Readdir,
439];
440
441fn verified_attach_from_claims(
442    claims: hyprstream_rpc::auth::Claims,
443    subject: Subject,
444) -> Result<VerifiedAttach, &'static str> {
445    let tenant = claims
446        .tenant
447        .as_deref()
448        .filter(|tenant| !tenant.is_empty() && *tenant != "*")
449        .ok_or("mount ticket missing authority-bound tenant")?;
450    // The ticket signature has just been verified by the local authority.
451    // Assurance is Classical unless an attach-specific subject key proof is
452    // added; the clearance claim cannot upgrade it.
453    let security_context = claims
454        .security_context(VerifiedKeyMaterial::Classical)
455        .ok_or("mount ticket missing verified Claims clearance")?;
456    let valid_for = claims
457        .exp
458        .checked_sub(chrono::Utc::now().timestamp())
459        .filter(|remaining| {
460            *remaining > 0 && *remaining <= crate::services::oauth::mount_ticket::MOUNT_TICKET_TTL
461        })
462        .and_then(|remaining| u64::try_from(remaining).ok())
463        .ok_or("mount ticket expired")?;
464    let identity =
465        VerifiedAttachIdentity::from_verified_credential(claims.sub.clone(), tenant.to_owned());
466    let scope = VerifiedTokenScope::from_verified_token(
467        *security_context.clearance(),
468        Arc::from(NINEP_ALL_ACTIONS),
469        Instant::now()
470            .checked_add(Duration::from_secs(valid_for))
471            .ok_or("mount ticket expiry is invalid")?,
472    );
473    let session = SessionContext::from_verified_token(identity.clone(), security_context, scope);
474    let verified = VerifiedAttach::try_new(identity, subject, session)
475        .map_err(|_| "verified attach binding failed")?;
476    // Seed the direct VFS PEP from the same verified Claims that produced the
477    // unified bundle. The VFS Subject can never acquire authority from uname.
478    hyprstream_rpc::auth::mac::remember_verified_claims(
479        verified.subject(),
480        &claims,
481        VerifiedKeyMaterial::Classical,
482        Some(tenant),
483    );
484    Ok(verified)
485}
486
487#[derive(Clone)]
488struct PreverifiedAttachAuthorizer(VerifiedAttach);
489
490#[async_trait]
491impl AttachAuthorizer for PreverifiedAttachAuthorizer {
492    async fn authenticate(&self, _uname: &str, aname: &str) -> Result<VerifiedAttach, MountError> {
493        if aname_to_namespace_path(aname)? != ROOT_NAMESPACE_PATH {
494            return Err(MountError::PermissionDenied(
495                "preverified ticket is not valid for requested export".to_owned(),
496            ));
497        }
498        Ok(self.0.clone())
499    }
500}
501
502/// Preserve the preexisting synthetic root when the exact canonical worktree
503/// export is disabled. The opt-in path constructs a holder-bound namespace
504/// after ticket verification and never exposes the rest of the host VFS.
505fn build_export_mount(_state: &ServerState, _subject: &Subject) -> Arc<dyn Mount> {
506    let root = SyntheticNode::dir()
507        .with_child("srv", SyntheticNode::dir())
508        .with_child("worktree", SyntheticNode::dir())
509        .with_child("stream", SyntheticNode::dir())
510        .with_child(
511            "README",
512            SyntheticNode::file(
513                b"hyprstream 9P-over-WebSocket export (H1a placeholder root).\n\
514                  Real Subject-scoped host VFS lands with #730.\n"
515                    .to_vec(),
516            ),
517        );
518    Arc::new(SyntheticMount::new(root))
519}
520
521/// Drive one 9P-over-WebSocket session to completion.
522///
523/// Bridges the WebSocket message stream to the transport-agnostic
524/// [`Translator::serve_connection`] core via an in-process duplex (mirroring
525/// `wanix serve`'s ws↔9p pump), and OWNS session liveness via server-driven
526/// ping/pong keepalive (see module docs): a `Ping` every `ping_interval`, close
527/// after [`MAX_MISSED_PONGS`] consecutive unanswered pings; any inbound frame
528/// resets the miss counter, so a healthy-idle mount lives indefinitely.
529pub(crate) async fn serve_9p_websocket(
530    socket: WebSocket,
531    translator: Arc<Translator>,
532    ping_interval: Duration,
533) {
534    // `core_side` feeds the 9P serve core; `pump_side` is driven by the WS pump.
535    let (core_side, pump_side) = tokio::io::duplex(DUPLEX_BUF);
536    let (mut pump_rd, mut pump_wr) = split(pump_side);
537    let (mut ws_tx, mut ws_rx) = socket.split();
538
539    // Outbound framing is not cancel-safe (a full 9P message is two `read_exact`
540    // reads: length prefix then payload), so it runs in its own task and feeds
541    // whole frames to the select loop over a channel. Mirrors `serve.go`'s
542    // 9p→ws goroutine.
543    let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(32);
544    let frame_reader = tokio::spawn(async move {
545        loop {
546            let mut len = [0u8; 4];
547            if pump_rd.read_exact(&mut len).await.is_err() {
548                break; // core closed
549            }
550            let total = u32::from_le_bytes(len) as usize;
551            if total < 4 {
552                break;
553            }
554            let mut frame = vec![0u8; total];
555            frame[..4].copy_from_slice(&len);
556            if pump_rd.read_exact(&mut frame[4..]).await.is_err() {
557                break;
558            }
559            if frame_tx.send(frame).await.is_err() {
560                break; // select loop gone
561            }
562        }
563        // `frame_tx` drops → `frame_rx` closes → select loop learns the core ended.
564    });
565    // `frame_reader` (a JoinHandle) owns `pump_rd`; aborted after the session.
566
567    // The pump select loop owns the WS sink+stream, `pump_wr`, the keepalive
568    // ping interval, and the missed-pong counter — the single point that both
569    // forwards bytes and decides liveness.
570    let pump = async move {
571        let mut ping = tokio::time::interval(ping_interval);
572        ping.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
573        let mut missed_pongs: u32 = 0;
574        loop {
575            tokio::select! {
576                // Outbound 9P frame → one WS binary frame.
577                maybe = frame_rx.recv() => match maybe {
578                    Some(frame) => {
579                        if ws_tx.send(Message::Binary(frame)).await.is_err() {
580                            break; // peer gone
581                        }
582                    }
583                    None => break, // core closed (serve_connection ended)
584                },
585                // Inbound WS frame → core (binary), or liveness signal.
586                msg = ws_rx.next() => match msg {
587                    None => break, // stream ended
588                    Some(Err(e)) => {
589                        debug!(error = %e, "9P WS read error; closing");
590                        break;
591                    }
592                    Some(Ok(m)) => {
593                        // ANY inbound frame (pong OR data) proves the peer is alive.
594                        missed_pongs = 0;
595                        match m {
596                            Message::Binary(bytes) => {
597                                if pump_wr.write_all(&bytes).await.is_err() {
598                                    break; // core gone
599                                }
600                            }
601                            Message::Close(_) => break,
602                            // Pong/Ping/Text carry no 9P payload; tungstenite
603                            // auto-replies to inbound Pings at the protocol layer.
604                            Message::Ping(_) | Message::Pong(_) | Message::Text(_) => {}
605                        }
606                    }
607                },
608                // Keepalive tick: send a Ping; reap the session after too many
609                // consecutive unanswered pings (dead peer).
610                _ = ping.tick() => {
611                    missed_pongs += 1;
612                    if missed_pongs >= MAX_MISSED_PONGS {
613                        info!(missed_pongs, "9P WS keepalive: peer missed pongs; closing");
614                        break;
615                    }
616                    if ws_tx.send(Message::Ping(Vec::new())).await.is_err() {
617                        break; // peer gone
618                    }
619                }
620            }
621        }
622        let _ = ws_tx.close().await;
623        // `pump_wr` drops here → core read half sees EOF → serve_connection ends.
624    };
625
626    // Both sides must finish so serve_connection can clunk retained remote
627    // fids after an abrupt WebSocket close. Dropping its future here would
628    // cancel the connection cleanup.
629    let (result, ()) = tokio::join!(translator.serve_connection(core_side), pump);
630    if let Err(e) = result {
631        debug!(error = %e, "9P WS serve loop ended with error");
632    }
633    frame_reader.abort();
634}
635
636// ─────────────────────────────────────────────────────────────────────────────
637// H1b: /9p over WebTransport (QUIC path-mux plane)
638// ─────────────────────────────────────────────────────────────────────────────
639
640/// Resolves the mount ticket a client presents in `Tattach.uname` to a narrowed
641/// session [`Subject`], reusing H1a's [`verify_mount_ticket`].
642///
643/// This is the attach-time credential seam for the H1b `/9p` WebTransport plane:
644/// the cert-pinned mesh session carries no URL query (and a browser `WebSocket`
645/// can't set headers), so the ticket rides `Tattach.uname` and is validated once
646/// at attach — the per-session analogue of H1a's pre-upgrade check. On denial we
647/// return [`MountError::PermissionDenied`], which the 9P translator maps to an
648/// `Rlerror` (`EACCES`).
649struct TicketAttachAuthorizer {
650    state: ServerState,
651    canonical_mount: Option<Arc<OnceLock<Arc<dyn Mount>>>>,
652}
653
654#[async_trait]
655impl AttachAuthorizer for TicketAttachAuthorizer {
656    async fn authenticate(&self, uname: &str, aname: &str) -> Result<VerifiedAttach, MountError> {
657        if uname.is_empty() {
658            return Err(MountError::PermissionDenied(
659                "missing mount ticket".to_owned(),
660            ));
661        }
662        // Resolve the requested export (`aname`) to the namespace path the
663        // ticket must grant, then let the ticket capability check decide. An
664        // empty `aname` selects the default (root) export; an explicit selector
665        // is normalized as an absolute, `..`-free path so the accept-side
666        // canonical form agrees with the capability a ticket encodes. A
667        // malformed `aname` denies here; an otherwise well-formed but ungranted
668        // one denies inside `verify_mount_ticket` (the ticket capability won't
669        // match). Either way this is EACCES before any fid exists, and there is
670        // NO fallback to a default export after an explicit selector
671        // (#877/#1071 fail-closed contract).
672        let requested_ns = aname_to_namespace_path(aname)?;
673        let resource_state = self.state.resource_auth_state();
674        match verify_mount_ticket(&resource_state, uname, PLANE_WEBTRANSPORT, &requested_ns).await {
675            Ok(verified) => {
676                if let Some(slot) = &self.canonical_mount {
677                    let mount = CanonicalReadMount::new(
678                        &self.state,
679                        verified.subject().clone(),
680                        uname.to_owned(),
681                    )?;
682                    slot.set(Arc::new(mount)).map_err(|_| {
683                        MountError::PermissionDenied("canonical export already bound".into())
684                    })?;
685                }
686                Ok(verified)
687            }
688            Err(reason) => {
689                warn!(reason, aname = %aname, "9P WT attach rejected: invalid mount ticket or export");
690                Err(MountError::PermissionDenied(reason.to_owned()))
691            }
692        }
693    }
694}
695
696/// WT obtains the holder only at `Tattach`; all pre-attach mount operations
697/// deny and the first verified attach installs exactly one connection-local view.
698struct AttachedMount(Arc<OnceLock<Arc<dyn Mount>>>);
699
700impl AttachedMount {
701    fn bound(&self) -> Result<&Arc<dyn Mount>, MountError> {
702        self.0
703            .get()
704            .ok_or_else(|| MountError::PermissionDenied("9P op before verified attach".into()))
705    }
706}
707
708#[async_trait]
709impl Mount for AttachedMount {
710    async fn walk(&self, components: &[&str], caller: &Subject) -> Result<Fid, MountError> {
711        self.bound()?.walk(components, caller).await
712    }
713    async fn open(&self, fid: &mut Fid, mode: u8, caller: &Subject) -> Result<(), MountError> {
714        self.bound()?.open(fid, mode, caller).await
715    }
716    async fn read(
717        &self,
718        fid: &Fid,
719        offset: u64,
720        count: u32,
721        caller: &Subject,
722    ) -> Result<Vec<u8>, MountError> {
723        self.bound()?.read(fid, offset, count, caller).await
724    }
725    async fn write(
726        &self,
727        _fid: &Fid,
728        _offset: u64,
729        _data: &[u8],
730        _caller: &Subject,
731    ) -> Result<u32, MountError> {
732        Err(MountError::PermissionDenied(
733            "canonical export is read-only".into(),
734        ))
735    }
736    async fn readdir(&self, fid: &Fid, caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
737        self.bound()?.readdir(fid, caller).await
738    }
739    async fn stat(&self, fid: &Fid, caller: &Subject) -> Result<Stat, MountError> {
740        self.bound()?.stat(fid, caller).await
741    }
742    async fn clunk(&self, fid: Fid, caller: &Subject) {
743        if let Ok(mount) = self.bound() {
744            mount.clunk(fid, caller).await;
745        }
746    }
747}
748
749/// Normalize the 9P `aname` (export selector) a client presents at `Tattach`
750/// into the namespace path the mount ticket must grant.
751///
752/// An empty `aname` selects the default (root) export → [`ROOT_NAMESPACE_PATH`].
753/// An explicit selector is normalized as an absolute, `..`-free path (a bare
754/// name is anchored at the root) by reusing the mint-side normalizer so the
755/// accept-side canonical form agrees byte-for-byte with the capability a ticket
756/// encodes. A malformed selector (`..`, non-normalizable) denies — it is never
757/// silently coerced to the default.
758///
759/// Today mount tickets are minted only for `/` (`mount_ticket.rs`), so the only
760/// `aname` that can match a grant is one normalizing to `/` (empty or `/`
761/// itself); any other selector denies with `EACCES`. Widening this to real
762/// per-export grants is the `ExportResolver` (#877/#1071) — out of scope here,
763/// where the seam is made `aname`-aware and fail-closed.
764fn aname_to_namespace_path(aname: &str) -> Result<String, MountError> {
765    if aname.is_empty() {
766        return Ok(ROOT_NAMESPACE_PATH.to_owned());
767    }
768    let anchored = if aname.starts_with('/') {
769        aname.to_owned()
770    } else {
771        format!("/{aname}")
772    };
773    crate::services::oauth::mount_ticket::normalize_namespace_path(&anchored).ok_or_else(|| {
774        MountError::PermissionDenied(format!("malformed aname (export selector): {aname:?}"))
775    })
776}
777
778/// The injected 9P-over-WebTransport handler (H1b / #765).
779///
780/// Registered process-globally via [`register_ninep_wt_handler`] so the QUIC
781/// path-mux `/9p` arm (`hyprstream-rpc`) can drive hyprstream's 9P core without
782/// that transport crate depending on `hyprstream`. Each WT bidi stream on the
783/// `/9p` path lands in [`NinePWtHandler::serve`], where it is served by the SAME
784/// [`Translator::serve_connection`] core + mount contract as H1a —
785/// only the ticket now rides `Tattach.uname` (validated by
786/// [`TicketAttachAuthorizer`]) and the transport is a QUIC bidi stream.
787pub struct NinePWtExport {
788    state: ServerState,
789}
790
791impl NinePWtExport {
792    /// Build the handler over the server's [`ServerState`] (the ticket-validation
793    /// chain + export mount source).
794    pub fn new(state: ServerState) -> Self {
795        Self { state }
796    }
797}
798
799#[async_trait]
800impl NinePWtHandler for NinePWtExport {
801    async fn serve(&self, stream: Box<dyn NinePWtStream>) {
802        // WT receives the holder only at Tattach. The opt-in mount is installed
803        // into a connection-local slot by successful ticket verification; the
804        // default synthetic root retains its existing behavior.
805        let canonical_mount = self
806            .state
807            .config
808            .ninep_canonical_read
809            .as_ref()
810            .map(|_| Arc::new(OnceLock::new()));
811        let mount: Arc<dyn Mount> = match &canonical_mount {
812            Some(slot) => Arc::new(AttachedMount(Arc::clone(slot))),
813            None => build_export_mount(&self.state, &Subject::anonymous()),
814        };
815        let authorizer: Arc<dyn AttachAuthorizer> = Arc::new(TicketAttachAuthorizer {
816            state: self.state.clone(),
817            canonical_mount,
818        });
819        // Install the full monitor. `from_mount_authorized` and the MAC path
820        // consume the exact same VerifiedAttach result from one ticket check.
821        let monitor = crate::mac::production_ninep_reference_monitor(
822            Arc::clone(&self.state.ninep_decider),
823            Arc::clone(&authorizer) as Arc<dyn hyprstream_9p::AttachAuthenticator>,
824        );
825        let translator = Arc::new(
826            Translator::from_mount_authorized(
827                mount,
828                authorizer,
829                Arc::clone(&self.state.ninep_decider),
830            )
831            .with_reference_monitor(monitor)
832            .with_activation_control(),
833        );
834        if let Err(e) = translator.serve_connection(stream).await {
835            debug!(error = %e, "9P WT serve loop ended with error");
836        }
837    }
838}
839
840/// Register the process-global 9P-over-WebTransport handler so the QUIC
841/// path-mux `/9p` arm serves this node's export. Idempotent (first-wins);
842/// call once at server startup where [`ServerState`] exists (see
843/// [`crate::server::create_app`]).
844pub fn register_ninep_wt_handler(state: ServerState) {
845    let installed = hyprstream_rpc::transport::quinn_transport::set_global_ninep_handler(Arc::new(
846        NinePWtExport::new(state),
847    ));
848    if installed {
849        info!("registered 9P-over-WebTransport handler (/9p QUIC path-mux, H1b)");
850    }
851}
852
853#[cfg(test)]
854#[allow(clippy::unwrap_used, clippy::expect_used)]
855mod tests {
856    use super::*;
857    use axum::{routing::get, Router};
858    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
859    use ed25519_dalek::Signer as _;
860    use hyprstream_9p::msg::{self, Response as P9Response};
861    use tokio_tungstenite::tungstenite::Message as WsMessage;
862
863    fn mount_claims(now: i64) -> hyprstream_rpc::auth::Claims {
864        hyprstream_rpc::auth::Claims::new("alice".to_owned(), now, now + 60)
865            .with_issuer("https://issuer.test".to_owned())
866            .with_audience(Some("https://resource.test".to_owned()))
867            .with_cap(crate::services::oauth::mount_ticket::ticket_capability(
868                "ws", "/",
869            ))
870            .with_tenant("tenant.test".to_owned())
871            .with_clearance(hyprstream_rpc::auth::mac::SecurityLabel::new(
872                hyprstream_rpc::auth::mac::Level::Secret,
873                hyprstream_rpc::auth::mac::Assurance::Classical,
874                hyprstream_rpc::auth::mac::CompartmentSet::EMPTY,
875            ))
876            .with_client_id("hyprstream-oauth-client-1")
877            .with_jti()
878    }
879
880    fn mount_ticket_state() -> (
881        ResourceAuthState,
882        ed25519_dalek::SigningKey,
883        hyprstream_rpc::crypto::pq::MlDsaSigningKey,
884        ed25519_dalek::SigningKey,
885    ) {
886        let ed25519 = ed25519_dalek::SigningKey::from_bytes(&[0x5a; 32]);
887        let federation_ed25519 = ed25519_dalek::SigningKey::from_bytes(&[0x5b; 32]);
888        let (ml_dsa, ml_dsa_verifying) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
889        let composite_keys = Arc::new(hyprstream_rpc::auth::CompositeKeySet::default());
890        let pair = hyprstream_rpc::auth::CompositeKeyPair::verifying(
891            crate::auth::jwt::composite_kid(&ml_dsa_verifying, &ed25519.verifying_key()),
892            ml_dsa_verifying,
893            ed25519.verifying_key(),
894            hyprstream_rpc::auth::CompositePairRole::OAuth,
895            hyprstream_rpc::auth::CompositePairState::Active,
896            0,
897            i64::MAX,
898        );
899        composite_keys
900            .publish(1, "ninep-test".to_owned(), vec![pair])
901            .expect("test composite pair must publish");
902
903        let federation_issuer = "https://federation.test";
904        let federation_kid = hyprstream_rpc::auth::jwt::kid_for_key(&federation_ed25519);
905        let federation_jwks = serde_json::json!({
906            "keys": [{
907                "kty": "OKP",
908                "crv": "Ed25519",
909                "x": URL_SAFE_NO_PAD.encode(federation_ed25519.verifying_key().as_bytes()),
910                "use": "sig",
911                "alg": "EdDSA",
912                "kid": federation_kid,
913            }]
914        });
915        let mut trusted = std::collections::HashMap::new();
916        trusted.insert(
917            federation_issuer.to_owned(),
918            crate::config::TrustedIssuerConfig {
919                jwks_uri: Some(format!("{federation_issuer}/jwks")),
920                jwks_cache_ttl_secs: 300,
921                allow_http: false,
922                federate_tui_client: None,
923            },
924        );
925        let federation_fetcher = Arc::new(
926            move |_url: &str| -> std::pin::Pin<
927                Box<dyn std::future::Future<Output = anyhow::Result<serde_json::Value>> + Send>,
928            > {
929                let federation_jwks = federation_jwks.clone();
930                Box::pin(async move { Ok(federation_jwks) })
931            },
932        );
933        let mut state = ResourceAuthState::new(
934            ed25519.verifying_key(),
935            "https://resource.test".to_owned(),
936            "https://issuer.test".to_owned(),
937            Arc::new(
938                crate::auth::FederationKeyResolver::new(&trusted)
939                    .with_jwks_fetcher(federation_fetcher),
940            ),
941        );
942        state.composite_key_set = composite_keys;
943        state.dpop_jti_seen = Arc::new(hyprstream_util::TtlCache::new(8, 16));
944        // Mount-ticket verification fails closed without the process-global
945        // revocation store (one canonical store; no per-service plumbing).
946        // Install an in-memory authority when no other test in this binary
947        // got there first.
948        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
949            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
950                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
951            ));
952        }
953        (state, ed25519, ml_dsa, federation_ed25519)
954    }
955
956    /// Test-only composite encoder that intentionally preserves an absent JTI.
957    /// Production encoders correctly add one, but this consumer must reject a
958    /// signed legacy/malformed ticket before it touches replay state.
959    fn encode_mount_ticket(
960        claims: &hyprstream_rpc::auth::Claims,
961        ml_dsa: &hyprstream_rpc::crypto::pq::MlDsaSigningKey,
962        ed25519: &ed25519_dalek::SigningKey,
963    ) -> String {
964        let ml_dsa_verifying = ml_dsa::Keypair::verifying_key(ml_dsa);
965        let kid = crate::auth::jwt::composite_kid(&ml_dsa_verifying, &ed25519.verifying_key());
966        let header = serde_json::json!({
967            "alg": "ML-DSA-65-Ed25519",
968            "typ": "at+jwt",
969            "kid": kid,
970        });
971        let signing_input = format!(
972            "{}.{}",
973            URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("test header serializes")),
974            URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).expect("test claims serialize")),
975        );
976        let mut signature =
977            hyprstream_rpc::crypto::pq::ml_dsa_sign(ml_dsa, signing_input.as_bytes());
978        signature.extend_from_slice(&ed25519.sign(signing_input.as_bytes()).to_bytes());
979        format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(signature))
980    }
981
982    #[tokio::test]
983    async fn mount_ticket_consumer_admits_once_without_pre_admission_consumption() {
984        let (state, ed25519, ml_dsa, federation_ed25519) = mount_ticket_state();
985        let now = chrono::Utc::now().timestamp();
986        let local_claims = mount_claims(now);
987        let local = encode_mount_ticket(&local_claims, &ml_dsa, &ed25519);
988        let first = verify_mount_ticket(&state, &local, "ws", "/").await;
989        assert!(first.is_ok(), "local ticket rejected: {first:?}");
990        assert!(verify_mount_ticket(&state, &local, "ws", "/")
991            .await
992            .is_err());
993        let occupied = state.dpop_jti_seen.len();
994        assert_eq!(occupied, 1);
995
996        let mut federated = mount_claims(now);
997        federated.iss = "https://federation.test".to_owned();
998        let federated = crate::auth::jwt::encode(&federated, &federation_ed25519);
999        assert_eq!(
1000            verify_mount_ticket(&state, &federated, "ws", "/").await,
1001            Err("mount ticket issuer is not local"),
1002            "a trusted federated ticket must reach the mount-only issuer guard"
1003        );
1004        assert_eq!(
1005            state.dpop_jti_seen.len(),
1006            occupied,
1007            "a federated mount ticket consumed replay capacity"
1008        );
1009
1010        let mut missing_tenant = mount_claims(now);
1011        missing_tenant.tenant = None;
1012        let mut missing_clearance = mount_claims(now);
1013        missing_clearance.clearance = None;
1014        let mut missing_jti = mount_claims(now);
1015        missing_jti.jti = None;
1016        let mut future_iat = mount_claims(now);
1017        future_iat.iat = now + 120;
1018        future_iat.exp = now + 180;
1019        let mut extreme_i64 = mount_claims(now);
1020        extreme_i64.iat = i64::MIN;
1021        extreme_i64.exp = i64::MAX;
1022        let mut overlong = mount_claims(now);
1023        overlong.exp = now + crate::services::oauth::mount_ticket::MOUNT_TICKET_TTL + 1;
1024        let mut expired = mount_claims(now);
1025        expired.iat = now - 61;
1026        expired.exp = now - 1;
1027
1028        for (case, claims) in [
1029            ("missing tenant", missing_tenant),
1030            ("missing clearance", missing_clearance),
1031            ("missing JTI", missing_jti),
1032            ("future iat", future_iat),
1033            ("extreme i64", extreme_i64),
1034            ("overlong lifetime", overlong),
1035            ("expired", expired),
1036        ] {
1037            let token = encode_mount_ticket(&claims, &ml_dsa, &ed25519);
1038            assert!(
1039                verify_mount_ticket(&state, &token, "ws", "/")
1040                    .await
1041                    .is_err(),
1042                "{case} ticket was accepted"
1043            );
1044            assert_eq!(
1045                state.dpop_jti_seen.len(),
1046                occupied,
1047                "{case} ticket consumed replay capacity"
1048            );
1049        }
1050    }
1051
1052    struct TransportTestDecider;
1053
1054    impl hyprstream_9p::AccessDecider for TransportTestDecider {
1055        fn check(
1056            &self,
1057            _ctx: &hyprstream_rpc::auth::mac::SecurityContext,
1058            _object: hyprstream_rpc::auth::mac::ObjectRef<'_>,
1059            _action: hyprstream_9p::Action,
1060        ) -> bool {
1061            true
1062        }
1063
1064        fn audit_denial(
1065            &self,
1066            _ctx: &hyprstream_rpc::auth::mac::SecurityContext,
1067            _object: hyprstream_rpc::auth::mac::ObjectRef<'_>,
1068            _object_label: Option<hyprstream_rpc::auth::mac::SecurityLabel>,
1069            _action: hyprstream_9p::Action,
1070            _reason: hyprstream_9p::ReferenceMonitorDenyReason,
1071        ) {
1072        }
1073    }
1074
1075    /// Discovery doc round-trips and advertises the H1a contract.
1076    #[test]
1077    fn discovery_defaults_match_wire_contract() {
1078        let d = Export9pDiscovery::default();
1079        assert_eq!(d.protocol, "9P2000.L");
1080        assert_eq!(d.endpoint, "/9p");
1081        assert_eq!(d.ticket_param, "ticket");
1082        assert_eq!(d.subprotocol, None); // stock wanix uses no subprotocol
1083    }
1084
1085    /// The wire-plane discovery table (#821) lists the 9p plane, serializes to
1086    /// valid JSON, and stays byte-for-byte back-compatible with the existing
1087    /// `/.well-known/export9p` document — the 9p entry is DERIVED from
1088    /// `Export9pDiscovery::default()`, so the two can never drift.
1089    #[test]
1090    fn wire_plane_table_lists_9p_and_is_back_compat() {
1091        let table = WirePlaneTable::current();
1092
1093        // The 9p plane is advertised, over both carriers, resolving to /9p.
1094        let ninep = table.planes.get("9p").expect("9p plane must be advertised");
1095        assert_eq!(ninep.path, "/9p");
1096        assert_eq!(ninep.path, NINEP_PATH);
1097        assert_eq!(ninep.transports, vec!["ws", "webtransport"]);
1098        assert_eq!(ninep.ticket_param.as_deref(), Some("ticket"));
1099        assert_eq!(ninep.protocol.as_deref(), Some("9P2000.L"));
1100
1101        // The moq plane is advertised at its existing selector.
1102        let moq = table
1103            .planes
1104            .get("moq")
1105            .expect("moq plane must be advertised");
1106        assert_eq!(moq.path, hyprstream_rpc::dial::MOQ_PATH);
1107        assert_eq!(moq.transports, vec!["webtransport"]);
1108
1109        // The document is valid JSON with the expected `planes` shape and
1110        // round-trips losslessly.
1111        let json = serde_json::to_value(&table).expect("table serializes to JSON");
1112        assert!(
1113            json.get("planes").is_some(),
1114            "top-level `planes` key present"
1115        );
1116        assert_eq!(json["planes"]["9p"]["path"], "/9p");
1117        assert_eq!(json["planes"]["9p"]["transports"][0], "ws");
1118        let round: WirePlaneTable =
1119            serde_json::from_value(json).expect("table round-trips from JSON");
1120        assert_eq!(round, table);
1121
1122        // Back-compat: the fields the 9p entry is built from are exactly the
1123        // export9p document's fields — deriving the entry guarantees no drift.
1124        let export9p = Export9pDiscovery::default();
1125        assert_eq!(ninep.path, export9p.endpoint);
1126        assert_eq!(
1127            ninep.ticket_param.as_deref(),
1128            Some(export9p.ticket_param.as_str())
1129        );
1130        assert_eq!(ninep.protocol.as_deref(), Some(export9p.protocol.as_str()));
1131
1132        // The export9p contract itself is unchanged (still serializes with its
1133        // original field set + values — the 1:3.0 WsMountTransport reads this).
1134        let ex_json = serde_json::to_value(&export9p).expect("export9p serializes");
1135        assert_eq!(ex_json["protocol"], "9P2000.L");
1136        assert_eq!(ex_json["transport"], "websocket");
1137        assert_eq!(ex_json["endpoint"], "/9p");
1138        assert_eq!(ex_json["ticket_param"], "ticket");
1139        assert_eq!(ex_json["subprotocol"], serde_json::Value::Null);
1140        assert_eq!(ex_json["wire"], "raw-9p-binary-frames");
1141        assert_eq!(ex_json["compatible_with"], "wanix serve");
1142    }
1143
1144    /// End-to-end 9P-over-WebSocket attach: spin the `/9p` transport over a
1145    /// `MemoryBackend`, connect a real WebSocket client, and drive
1146    /// version → attach → walk → open → read. Exercises the full ws↔9p pump +
1147    /// the shared `serve_connection` core over genuine WS binary frames.
1148    #[tokio::test]
1149    async fn websocket_9p_attach_walk_read_roundtrip() {
1150        // A test route that serves a Subject-scoped SyntheticMount over WS via
1151        // `from_mount` — the SAME MountBackend path `/9p` uses in production, so
1152        // typed MountError→errno mapping is exercised end to end. No
1153        // ServerState/ticket, isolating the transport under test.
1154        async fn test_ws(ws: WebSocketUpgrade) -> Response {
1155            let root = SyntheticNode::dir()
1156                .with_child("hello.txt", SyntheticNode::file(b"hello ws".to_vec()));
1157            let mount: Arc<dyn Mount> = Arc::new(SyntheticMount::new(root));
1158            let translator = Arc::new(Translator::from_mount(
1159                mount,
1160                Subject::new("test"),
1161                Arc::new(TransportTestDecider),
1162            ));
1163            ws.on_upgrade(move |s| serve_9p_websocket(s, translator, Duration::from_secs(10)))
1164        }
1165
1166        let app = Router::new().route("/9p", get(test_ws));
1167        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1168        let addr = listener.local_addr().unwrap();
1169        let server = tokio::spawn(async move {
1170            axum::serve(listener, app).await.unwrap();
1171        });
1172
1173        let url = format!("ws://{addr}/9p");
1174        let (mut ws, _resp) = tokio_tungstenite::connect_async(&url).await.unwrap();
1175
1176        // Helper: send a framed 9P T-message, await the next binary frame,
1177        // decode the R-message.
1178        async fn rpc(
1179            ws: &mut tokio_tungstenite::WebSocketStream<
1180                tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
1181            >,
1182            tmsg: Vec<u8>,
1183        ) -> P9Response {
1184            ws.send(WsMessage::Binary(tmsg)).await.unwrap();
1185            loop {
1186                match ws.next().await.unwrap().unwrap() {
1187                    WsMessage::Binary(buf) => {
1188                        let (_tag, resp) = msg::parse_response(&buf).unwrap();
1189                        return resp;
1190                    }
1191                    _ => continue,
1192                }
1193            }
1194        }
1195
1196        // Tversion → Rversion.
1197        let resp = rpc(&mut ws, msg::tversion(1, 8192, "9P2000.L")).await;
1198        assert!(matches!(resp, P9Response::Version { .. }), "got {resp:?}");
1199
1200        // Tattach fid 0 as root.
1201        let resp = rpc(&mut ws, msg::tattach(2, 0, u32::MAX, "u", "")).await;
1202        assert!(matches!(resp, P9Response::Attach { .. }), "got {resp:?}");
1203
1204        // Twalk to the file, Tlopen, Tread.
1205        let resp = rpc(&mut ws, msg::twalk(3, 0, 1, &["hello.txt"])).await;
1206        assert!(matches!(resp, P9Response::Walk { .. }), "got {resp:?}");
1207
1208        let resp = rpc(&mut ws, msg::tlopen(4, 1, 0)).await;
1209        assert!(matches!(resp, P9Response::Lopen { .. }), "got {resp:?}");
1210
1211        let resp = rpc(&mut ws, msg::tread(5, 1, 0, 64)).await;
1212        match resp {
1213            P9Response::Read { data } => assert_eq!(&data, b"hello ws"),
1214            other => panic!("expected Rread, got {other:?}"),
1215        }
1216
1217        // A walk to a missing path returns a typed ENOENT Rlerror (H1a errnos).
1218        let resp = rpc(&mut ws, msg::twalk(6, 0, 2, &["nope"])).await;
1219        match resp {
1220            P9Response::Error { ecode } => assert_eq!(ecode, 2, "missing path must be ENOENT"),
1221            other => panic!("expected Rlerror ENOENT, got {other:?}"),
1222        }
1223
1224        ws.close(None).await.unwrap();
1225        server.abort();
1226    }
1227
1228    /// Two real 9P wire sessions may reuse fid numbers, but each export keeps
1229    /// its selected worktree and read handles within its own connection.
1230    #[tokio::test]
1231    async fn canonical_read_wire_sessions_isolate_fids_and_deny_other_paths_and_write() {
1232        fn served(ws: WebSocketUpgrade, body: &'static [u8]) -> Response {
1233            let tree = SyntheticNode::dir().with_child(
1234                "selected",
1235                SyntheticNode::dir().with_child(
1236                    "main",
1237                    SyntheticNode::dir()
1238                        .with_child("proof.txt", SyntheticNode::file(body.to_vec())),
1239                ),
1240            );
1241            let backing: Arc<dyn Mount> = Arc::new(SyntheticMount::new(tree));
1242            let mount: Arc<dyn Mount> = Arc::new(CanonicalReadMount::test_new(
1243                Subject::new("alice"),
1244                "selected",
1245                "main",
1246                backing,
1247            ));
1248            let translator = Arc::new(Translator::from_mount(
1249                mount,
1250                Subject::new("alice"),
1251                Arc::new(TransportTestDecider),
1252            ));
1253            ws.on_upgrade(move |socket| {
1254                serve_9p_websocket(socket, translator, Duration::from_secs(10))
1255            })
1256        }
1257        async fn a(ws: WebSocketUpgrade) -> Response {
1258            served(ws, b"connection A")
1259        }
1260        async fn b(ws: WebSocketUpgrade) -> Response {
1261            served(ws, b"connection B")
1262        }
1263        async fn rpc(
1264            ws: &mut tokio_tungstenite::WebSocketStream<
1265                tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
1266            >,
1267            request: Vec<u8>,
1268        ) -> P9Response {
1269            ws.send(WsMessage::Binary(request)).await.unwrap();
1270            loop {
1271                if let WsMessage::Binary(frame) = ws.next().await.unwrap().unwrap() {
1272                    return msg::parse_response(&frame).unwrap().1;
1273                }
1274            }
1275        }
1276
1277        let app = Router::new().route("/a", get(a)).route("/b", get(b));
1278        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1279        let addr = listener.local_addr().unwrap();
1280        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1281        let (mut ws_a, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/a"))
1282            .await
1283            .unwrap();
1284        let (mut ws_b, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/b"))
1285            .await
1286            .unwrap();
1287        for ws in [&mut ws_a, &mut ws_b] {
1288            assert!(matches!(
1289                rpc(ws, msg::tversion(1, 8192, "9P2000.L")).await,
1290                P9Response::Version { .. }
1291            ));
1292            assert!(matches!(
1293                rpc(ws, msg::tattach(2, 0, u32::MAX, "u", "")).await,
1294                P9Response::Attach { .. }
1295            ));
1296            assert!(matches!(
1297                rpc(ws, msg::twalk(3, 0, 1, &["worktree", "proof.txt"])).await,
1298                P9Response::Walk { .. }
1299            ));
1300            assert!(matches!(
1301                rpc(ws, msg::tlopen(4, 1, 0)).await,
1302                P9Response::Lopen { .. }
1303            ));
1304        }
1305        assert!(
1306            matches!(rpc(&mut ws_a, msg::tread(5, 1, 0, 64)).await, P9Response::Read { data } if data == b"connection A")
1307        );
1308        assert!(
1309            matches!(rpc(&mut ws_b, msg::tread(5, 1, 0, 64)).await, P9Response::Read { data } if data == b"connection B")
1310        );
1311        assert!(matches!(
1312            rpc(&mut ws_a, msg::twrite(6, 1, 0, b"overwrite")).await,
1313            P9Response::Error { ecode: 13 }
1314        ));
1315        assert!(matches!(
1316            rpc(&mut ws_a, msg::twalk(7, 0, 2, &["private"])).await,
1317            P9Response::Error { ecode: 13 }
1318        ));
1319        ws_a.close(None).await.unwrap();
1320        ws_b.close(None).await.unwrap();
1321        server.abort();
1322    }
1323}