Skip to main content

capsule_runtime/
resource_plane.rs

1//! The resource plane: the read-only file surface a capsule declares under `exports.files`.
2//!
3//! Two verbs, `list` and `read`, served host-side off the ordinary host path the runtime already
4//! holds for the workdir. No wasm is instantiated, no store is locked and no running turn is
5//! consulted, so the plane answers whether the capsule is idle or mid-task — and a read never
6//! costs an inference turn.
7//!
8//! Three responsibilities are kept apart:
9//!
10//! * The **agent** owns what a file contains. Nothing here asks it anything.
11//! * The **runtime** owns who may read it. Path resolution lives entirely in this module: a
12//!   caller never sanitises a path, because a gateway that normalises `..` into something
13//!   servable has taken over the containment boundary, and the component holding that boundary
14//!   must not think. Every escaping request is refused, never repaired.
15//! * The **trace** owns the record. Every read and every refusal lands in `trace.jsonl` at the
16//!   moment of the request, because the agent has been removed from the loop and the trace is
17//!   the only account of what left the capsule and when.
18//!
19//! Declaring an export does not change the achieved containment class — see
20//! [`crate::containment`]. Containment describes the guest's reach outward; an export widens the
21//! operator's reach inward and hands the guest nothing.
22//!
23//! The filesystem work is synchronous `std::fs` run on [`tokio::task::spawn_blocking`], and the
24//! resolve-then-verify-prefix path is the only one: `openat2(RESOLVE_BENEATH)` is Linux-only and
25//! could never be more than an extra layer over a portable path that has to be correct by
26//! itself, so this module keeps the portable path alone rather than two that can disagree.
27
28use std::{
29    io::Read,
30    path::{Component, Path, PathBuf},
31    sync::{
32        atomic::{AtomicU64, Ordering},
33        Arc,
34    },
35    time::UNIX_EPOCH,
36};
37
38use murmur_artifact::{ContainmentClass, ExportMode, FileExport, PeerFilesExport};
39use serde::Serialize;
40
41use crate::{errors::RuntimeError, trace::ResourceTraceAppender};
42
43/// Path prefix the plane answers under. Everything below it is `GET`-only.
44pub const RESOURCE_PATH_PREFIX: &str = "/resources/";
45
46/// The one file-surface route, relative to [`RESOURCE_PATH_PREFIX`].
47const FILES_ROUTE: &str = "files";
48
49// ── Declared export ───────────────────────────────────────────────────────────
50
51/// One `exports.files` block, with its root already resolved against the session's accessible
52/// workdir.
53///
54/// The root is *joined*, not canonicalised, at construction: `exports.files.root` is not required
55/// to exist when the capsule launches, because the agent may create it during a task. Every
56/// request canonicalises it afresh, which is also what lets a `list` answer `200` with no entries
57/// before the agent has written anything.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct DeclaredExport {
60    /// `exports.files.root` verbatim, as the operator wrote it (`out/`). Echoed in every
61    /// response and every trace line; never used to touch the filesystem.
62    pub declared_root: String,
63    /// `accessible_workdir.join(declared_root)`.
64    pub root: PathBuf,
65    pub mode: ExportMode,
66    /// Per-file read ceiling. A file above it is still *listed*, with its real size — discovery
67    /// must not lie about what is there — and refused on read.
68    pub max_bytes: u64,
69}
70
71impl DeclaredExport {
72    /// Resolves a manifest's `exports.files` block against the session's work folder — the
73    /// directory the agent's own tools see at `.`, and therefore the one a relative export root
74    /// names.
75    pub fn resolve(accessible_workdir: &Path, export: &FileExport) -> Self {
76        Self {
77            declared_root: export.root.clone(),
78            root: accessible_workdir.join(&export.root),
79            mode: export.mode,
80            max_bytes: export.max_bytes,
81        }
82    }
83
84    /// [`Self::resolve`] for the peer plane's separate subtree.
85    ///
86    /// The same type because it is the same resolution: `exports.peer_files` opens a different
87    /// root under a different authoriser, but a path beneath it is decided by exactly the rules
88    /// that decide one beneath `exports.files`. `mode` is [`ExportMode::ReadOnly`] because there
89    /// is no other kind of peer export and none is declarable — a redeem serves bytes and
90    /// nothing else.
91    pub fn for_peer_files(accessible_workdir: &Path, export: &PeerFilesExport) -> Self {
92        Self {
93            declared_root: export.root.clone(),
94            root: accessible_workdir.join(&export.root),
95            mode: ExportMode::ReadOnly,
96            max_bytes: export.max_bytes,
97        }
98    }
99}
100
101/// Refuses a launch whose declared `exports.peer_files.root` already resolves outside the
102/// accessible workdir — [`check_export_root`] for the peer plane's root, and the same refusal.
103pub fn check_peer_files_root(
104    accessible_workdir: &Path,
105    export: &PeerFilesExport,
106) -> Result<(), RuntimeError> {
107    check_root_within_workdir(accessible_workdir, "exports.peer_files.root", &export.root)
108}
109
110/// Refuses a launch whose declared export root already resolves outside the accessible workdir.
111///
112/// Called from `stage_session` before the workdir is created, so a capsule whose `out/` is a
113/// symlink into someone else's directory never runs at all — the alternative is discovering it
114/// one served file at a time, by which point the first file has left. A root that does not yet
115/// exist is accepted: the agent may create it during a task, and every request resolves the root
116/// afresh.
117pub fn check_export_root(
118    accessible_workdir: &Path,
119    export: &FileExport,
120) -> Result<(), RuntimeError> {
121    check_root_within_workdir(accessible_workdir, "exports.files.root", &export.root)
122}
123
124fn check_root_within_workdir(
125    accessible_workdir: &Path,
126    field: &str,
127    root: &str,
128) -> Result<(), RuntimeError> {
129    let Ok(workdir_canon) = std::fs::canonicalize(accessible_workdir) else {
130        // No `--workdir`: the session directory does not exist yet, so nothing under it can
131        // already point elsewhere.
132        return Ok(());
133    };
134    let Ok(resolved) = std::fs::canonicalize(workdir_canon.join(root)) else {
135        return Ok(());
136    };
137    if !resolved.starts_with(&workdir_canon) {
138        return Err(RuntimeError::ExportRootOutsideWorkdir {
139            field: field.to_string(),
140            declared: root.to_string(),
141            resolved: resolved.display().to_string(),
142            workdir: workdir_canon.display().to_string(),
143        });
144    }
145    Ok(())
146}
147
148/// Everything the resource plane needs to answer a request, and nothing that a running task
149/// leaves behind.
150///
151/// Deliberately constructible from an export declaration, a workdir path and a containment class
152/// alone: a later reader-only launch mode must be able to build one over an existing workdir
153/// without starting the engine, and would be correct to report `generation: 0` there, since no
154/// task has completed *in that process*.
155pub struct ResourcePlane {
156    /// `None` means the capsule declared no `exports.files`, which is the deny case: every
157    /// request answers `no_resource_plane` and still lands in the trace.
158    export: Option<DeclaredExport>,
159    /// The class this session actually achieved — never the declared floor. Reported on every
160    /// response and used to key the symlink decision (see [`symlink_policy`]).
161    containment_achieved: ContainmentClass,
162    /// Incremented by the agent loop when a task reaches a terminal state. Provenance, never a
163    /// pin: see [`ResourcePlane::generation`].
164    generation: Arc<AtomicU64>,
165    /// `None` when there is nowhere to write a record — a plane built outside a session. A
166    /// session-backed plane always has one.
167    trace: Option<Arc<ResourceTraceAppender>>,
168}
169
170impl ResourcePlane {
171    /// The five inputs a plane needs, and the complete list of them: a host path, the declared
172    /// export (`None` = undeclared = deny), the achieved containment class, the generation
173    /// counter and somewhere to write the record. None of them is state a completed task left
174    /// behind, which is what lets a later reader-only launch mode build one over an existing
175    /// workdir without starting the engine.
176    pub fn new(
177        accessible_workdir: &Path,
178        export: Option<&FileExport>,
179        containment_achieved: ContainmentClass,
180        generation: Arc<AtomicU64>,
181        trace: Option<Arc<ResourceTraceAppender>>,
182    ) -> Self {
183        Self::with_export(
184            export.map(|export| DeclaredExport::resolve(accessible_workdir, export)),
185            containment_achieved,
186            generation,
187            trace,
188        )
189    }
190
191    /// [`Self::new`] with the root already resolved.
192    pub fn with_export(
193        export: Option<DeclaredExport>,
194        containment_achieved: ContainmentClass,
195        generation: Arc<AtomicU64>,
196        trace: Option<Arc<ResourceTraceAppender>>,
197    ) -> Self {
198        Self {
199            export,
200            containment_achieved,
201            generation,
202            trace,
203        }
204    }
205
206    /// Which turn the bytes belong to: `0` until the first task in this process reaches a
207    /// terminal state, then one more per completed task.
208    ///
209    /// It answers *these bytes are as of turn N* and nothing else. It is not an argument — no
210    /// request selects a generation, no response conflicts because the generation has moved on,
211    /// and superseded bytes are not retained. A capsule that is finished but alive and rewrites a
212    /// file two turns later simply serves the newer file; the `etag` is how a caller notices.
213    pub fn generation(&self) -> u64 {
214        self.generation.load(Ordering::SeqCst)
215    }
216
217    pub fn containment_achieved(&self) -> ContainmentClass {
218        self.containment_achieved
219    }
220}
221
222// ── Wire shapes ───────────────────────────────────────────────────────────────
223
224/// A status, headers and a body — everything a transport needs and nothing about the transport.
225///
226/// [`handle_resource_request`] returns this rather than writing to a socket, so the same logic
227/// can be bound on another listener behind its own authoriser without touching any of it.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct ResourceResponse {
230    pub status: u16,
231    pub headers: Vec<(String, String)>,
232    pub body: Vec<u8>,
233}
234
235impl ResourceResponse {
236    /// Builds a response with `content-length` taken from the body it carries.
237    ///
238    /// Framing is settled here rather than left to the transport so that a later listener binding
239    /// [`handle_resource_request`] gets a self-delimiting response without having to know it owed
240    /// one. A body delimited only by the connection closing is a body a caller cannot tell apart
241    /// from a truncated one, which would undo the point of serving a validator alongside it.
242    pub(crate) fn framed(status: u16, mut headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
243        headers.push(("content-length".to_string(), body.len().to_string()));
244        Self {
245            status,
246            headers,
247            body,
248        }
249    }
250}
251
252#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
253pub struct ListResponse {
254    pub root: String,
255    pub mode: ExportMode,
256    pub max_bytes: u64,
257    pub generation: u64,
258    pub containment_achieved: ContainmentClass,
259    pub entries: Vec<ListEntry>,
260}
261
262/// One regular file under the export root. `size_bytes`, `mtime_ms` and `sha256` all come from a
263/// single open of that file, so they describe one version of it and never a mixture of two.
264#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
265pub struct ListEntry {
266    /// Relative to the export root, `/`-separated.
267    pub path: String,
268    pub size_bytes: u64,
269    pub mtime_ms: u64,
270    pub sha256: String,
271}
272
273/// The bytes of one file together with the validator that describes *those* bytes.
274///
275/// The hash is computed from the buffer actually served, not from a second pass over the path, so
276/// the `etag` and the body are the same version by construction.
277#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct ReadResponse {
279    pub bytes: Vec<u8>,
280    pub sha256: String,
281    pub mtime_ms: u64,
282}
283
284// ── Errors ────────────────────────────────────────────────────────────────────
285
286#[derive(Debug, Clone, PartialEq, Eq)]
287pub enum ResourceError {
288    /// The manifest declares no `exports.files`. Absent means deny.
289    NoResourcePlane,
290    NotFound,
291    OutsideRoot,
292    /// A symlink was encountered and the achieved class is `scoped`.
293    SymlinkRefused,
294    NotARegularFile,
295    TooLarge {
296        max_bytes: u64,
297    },
298    MethodNotAllowed,
299    IoError(String),
300}
301
302impl ResourceError {
303    /// The stable `error` string in the JSON body and the `outcome` in the trace — one vocabulary
304    /// for both, so a refusal an auditor reads is spelled the way the caller saw it.
305    pub fn code(&self) -> &'static str {
306        match self {
307            ResourceError::NoResourcePlane => "no_resource_plane",
308            ResourceError::NotFound => "not_found",
309            ResourceError::OutsideRoot => "outside_root",
310            ResourceError::SymlinkRefused => "symlink_refused",
311            ResourceError::NotARegularFile => "not_a_regular_file",
312            ResourceError::TooLarge { .. } => "too_large",
313            ResourceError::MethodNotAllowed => "method_not_allowed",
314            ResourceError::IoError(_) => "io_error",
315        }
316    }
317
318    pub fn status(&self) -> u16 {
319        match self {
320            ResourceError::NoResourcePlane | ResourceError::NotFound => 404,
321            ResourceError::OutsideRoot
322            | ResourceError::SymlinkRefused
323            | ResourceError::NotARegularFile => 403,
324            ResourceError::TooLarge { .. } => 413,
325            ResourceError::MethodNotAllowed => 405,
326            ResourceError::IoError(_) => 500,
327        }
328    }
329
330    pub fn message(&self) -> String {
331        match self {
332            ResourceError::NoResourcePlane => {
333                "this capsule declares no exports.files block, so it has no resource plane"
334                    .to_string()
335            }
336            ResourceError::NotFound => "no such file under the export root".to_string(),
337            ResourceError::OutsideRoot => {
338                "the requested path resolves outside the export root".to_string()
339            }
340            ResourceError::SymlinkRefused => {
341                "a symlink was encountered and the achieved containment class is scoped".to_string()
342            }
343            ResourceError::NotARegularFile => {
344                "the requested path is not a regular file".to_string()
345            }
346            ResourceError::TooLarge { max_bytes } => {
347                format!("file exceeds the declared exports.files.max_bytes of {max_bytes} bytes")
348            }
349            ResourceError::MethodNotAllowed => {
350                "the resource plane serves GET only; it has no write path".to_string()
351            }
352            ResourceError::IoError(detail) => format!("read failed: {detail}"),
353        }
354    }
355}
356
357fn io_to_resource_error(error: &std::io::Error) -> ResourceError {
358    match error.kind() {
359        std::io::ErrorKind::NotFound => ResourceError::NotFound,
360        // A component of the path is not a directory, or O_NOFOLLOW hit a symlink on the final
361        // component: both mean the name does not designate a servable regular file here.
362        std::io::ErrorKind::NotADirectory => ResourceError::NotFound,
363        std::io::ErrorKind::PermissionDenied => ResourceError::IoError(error.to_string()),
364        _ if error.raw_os_error() == Some(libc::ELOOP) => ResourceError::SymlinkRefused,
365        _ => ResourceError::IoError(error.to_string()),
366    }
367}
368
369// ── The class-keyed symlink decision ──────────────────────────────────────────
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq)]
372pub enum SymlinkPolicy {
373    /// Refuse any symlink encountered on the resolved path, and omit symlinked entries from a
374    /// listing.
375    Refuse,
376    /// Follow symlinks, and serve only when the fully-resolved target is still beneath the export
377    /// root.
378    FollowWithinRoot,
379}
380
381/// What a symlink under the export root means at each achieved containment class.
382///
383/// Pure and class-keyed, mirroring the seam `containment::achieved_class_for_tier` uses, so the
384/// decision is testable across all three variants without a host probe — which matters because
385/// `scoped` is unreachable on darwin and on any Linux without a usable Landlock ABI.
386///
387/// * `scoped` — host-path grants are possible and the filesystem's shape stays visible, so a
388///   symlink under the export root could target a granted host path. Refuse it outright.
389/// * `sealed` — the workdir, `/tmp` and the home folder are the only writable paths and there is
390///   no outside to name, so everything under the export root is capsule-authored. Follow, and check the target.
391/// * `advisory` — a convention on top of a convention. Same rule as `sealed`, and every response
392///   says `advisory` so a caller knows what it is trusting.
393pub fn symlink_policy(class: ContainmentClass) -> SymlinkPolicy {
394    match class {
395        ContainmentClass::Scoped => SymlinkPolicy::Refuse,
396        ContainmentClass::Sealed | ContainmentClass::Advisory => SymlinkPolicy::FollowWithinRoot,
397    }
398}
399
400// ── Path resolution ───────────────────────────────────────────────────────────
401
402/// Percent-decoding, applied **before** any validation.
403///
404/// Order is the whole point: validating first is exactly what lets `%2e%2e%2f` through as an
405/// opaque-looking component that the filesystem then reads as `../`. An incomplete or non-hex
406/// escape is left as the literal bytes it was written with rather than rejected here — whatever
407/// it decodes to still has to survive [`export_relpath_components`].
408fn percent_decode(raw: &str) -> Vec<u8> {
409    let bytes = raw.as_bytes();
410    let mut out = Vec::with_capacity(bytes.len());
411    let mut index = 0;
412    while index < bytes.len() {
413        if bytes[index] == b'%' && index + 2 < bytes.len() {
414            let hex = std::str::from_utf8(&bytes[index + 1..index + 3])
415                .ok()
416                .and_then(|pair| u8::from_str_radix(pair, 16).ok());
417            if let Some(byte) = hex {
418                out.push(byte);
419                index += 3;
420                continue;
421            }
422        }
423        out.push(bytes[index]);
424        index += 1;
425    }
426    out
427}
428
429/// Decodes a request path and lowers it to the components that may be joined onto the export
430/// root, refusing everything else without touching the filesystem.
431///
432/// Refused: an empty path, an absolute path, a NUL byte, bytes that are not UTF-8, and any
433/// component equal to `""`, `"."` or `".."`. `.` is refused rather than skipped for the same
434/// reason `..` is: the runtime does not repair a request into something servable, and a caller
435/// that wanted `a/b` should ask for `a/b`.
436pub(crate) fn export_relpath_components(raw: &str) -> Result<Vec<String>, ResourceError> {
437    let decoded = percent_decode(raw);
438    if decoded.is_empty() || decoded.contains(&0) {
439        return Err(ResourceError::OutsideRoot);
440    }
441    let decoded = String::from_utf8(decoded).map_err(|_| ResourceError::OutsideRoot)?;
442    if decoded.starts_with('/') || Path::new(&decoded).is_absolute() {
443        return Err(ResourceError::OutsideRoot);
444    }
445    // One trailing slash names nothing new, so it is dropped before splitting. Every empty segment
446    // that survives is a `//` inside the path and is refused with the rest.
447    let mut components = Vec::new();
448    for part in decoded.strip_suffix('/').unwrap_or(&decoded).split('/') {
449        if part.is_empty() || part == "." || part == ".." {
450            return Err(ResourceError::OutsideRoot);
451        }
452        components.push(part.to_string());
453    }
454    if components.is_empty() {
455        return Err(ResourceError::OutsideRoot);
456    }
457    // Nothing above can produce a `..`, a root or a Windows prefix, but the join below is the
458    // step that would act on one, so the invariant is asserted where it is relied upon.
459    for component in &components {
460        if Path::new(component)
461            .components()
462            .any(|c| !matches!(c, Component::Normal(_)))
463        {
464            return Err(ResourceError::OutsideRoot);
465        }
466    }
467    Ok(components)
468}
469
470/// Canonicalises the export root and the target and requires the target to be the root or beneath
471/// it — the portable resolve-then-verify-prefix path, and the only one.
472///
473/// `Path::starts_with` compares whole components, so `/w/outside/x` is correctly *not* beneath
474/// `/w/out`.
475fn resolve_beneath(
476    root_canon: &Path,
477    components: &[String],
478    policy: SymlinkPolicy,
479) -> Result<PathBuf, ResourceError> {
480    let mut target = root_canon.to_path_buf();
481    if policy == SymlinkPolicy::Refuse {
482        // Walk component by component so a symlink is caught wherever it sits on the path, not
483        // only on the final element — an intermediate symlinked directory redirects everything
484        // below it just as effectively.
485        for component in components {
486            target.push(component);
487            let metadata =
488                std::fs::symlink_metadata(&target).map_err(|e| io_to_resource_error(&e))?;
489            if metadata.file_type().is_symlink() {
490                return Err(ResourceError::SymlinkRefused);
491            }
492        }
493    } else {
494        for component in components {
495            target.push(component);
496        }
497    }
498    let canonical = std::fs::canonicalize(&target).map_err(|e| io_to_resource_error(&e))?;
499    if !canonical.starts_with(root_canon) {
500        return Err(ResourceError::OutsideRoot);
501    }
502    Ok(canonical)
503}
504
505/// Opens `path` for reading without following a symlink on its final component and without
506/// blocking on a FIFO, and returns the descriptor with the metadata `fstat` reports for it.
507///
508/// `O_NONBLOCK` is what keeps a FIFO from parking the caller until a writer appears. Check the
509/// file type and owner on the returned metadata, never on a second lookup of `path`, which may by
510/// then name something else.
511pub(crate) fn open_no_follow(path: &Path) -> std::io::Result<(std::fs::File, std::fs::Metadata)> {
512    use std::os::unix::fs::OpenOptionsExt;
513
514    let file = std::fs::OpenOptions::new()
515        .read(true)
516        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
517        .open(path)?;
518    let metadata = file.metadata()?;
519    Ok((file, metadata))
520}
521
522/// [`open_no_follow`], then confirms from the open descriptor that it is a regular file, so a
523/// FIFO, socket or device node under the export root is `not_a_regular_file`.
524fn open_regular_file(path: &Path) -> Result<(std::fs::File, std::fs::Metadata), ResourceError> {
525    let (file, metadata) = open_no_follow(path).map_err(|e| io_to_resource_error(&e))?;
526    if !metadata.is_file() {
527        return Err(ResourceError::NotARegularFile);
528    }
529    Ok((file, metadata))
530}
531
532fn mtime_ms(metadata: &std::fs::Metadata) -> u64 {
533    metadata
534        .modified()
535        .ok()
536        .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
537        .map(|d| d.as_millis() as u64)
538        .unwrap_or(0)
539}
540
541// ── read ──────────────────────────────────────────────────────────────────────
542
543/// Resolves one root-relative request path to a canonical target beneath the export root,
544/// returning that target together with its canonical root-relative form.
545///
546/// The step the reader takes before it opens anything, exposed so the peer plane's *mint* can
547/// name a file without reading it. Sharing it is the point: a path that would be refused on a
548/// read is refused on a mint by the same code, so a handle can never authorise something the
549/// reader would then decline — or, worse, something it would not.
550pub(crate) fn resolve_relpath_beneath_root(
551    export: &DeclaredExport,
552    relpath: &str,
553    policy: SymlinkPolicy,
554) -> Result<(PathBuf, String), ResourceError> {
555    let components = export_relpath_components(relpath)?;
556    let root_canon = std::fs::canonicalize(&export.root).map_err(|e| io_to_resource_error(&e))?;
557    let target = resolve_beneath(&root_canon, &components, policy)?;
558    let relative = target
559        .strip_prefix(&root_canon)
560        .map_err(|_| ResourceError::OutsideRoot)?
561        .components()
562        .map(|component| component.as_os_str().to_string_lossy().into_owned())
563        .collect::<Vec<_>>()
564        .join("/");
565    if relative.is_empty() {
566        return Err(ResourceError::OutsideRoot);
567    }
568    Ok((target, relative))
569}
570
571/// Serves one file's current bytes.
572///
573/// Atomicity against a concurrent rewrite rests on two rules and no locking: the file is opened
574/// exactly once and its bytes, size and mtime all come from that one descriptor — a path can name
575/// a different inode by the time it is looked at twice — and the hash is taken over the buffer
576/// actually returned. An agent that rewrites by writing a temp file and renaming it into place
577/// therefore holds this reader on the old inode for the whole read; one that truncates and
578/// rewrites in place can still be read mid-write. That is an authoring convention, documented for
579/// capsule authors, not a mechanism enforced here.
580pub(crate) fn read_export_file_with_policy(
581    export: &DeclaredExport,
582    relpath: &str,
583    policy: SymlinkPolicy,
584) -> Result<ReadResponse, ResourceError> {
585    let (target, _) = resolve_relpath_beneath_root(export, relpath, policy)?;
586
587    let (file, metadata) = open_regular_file(&target)?;
588    if metadata.len() > export.max_bytes {
589        return Err(ResourceError::TooLarge {
590            max_bytes: export.max_bytes,
591        });
592    }
593    let mtime = mtime_ms(&metadata);
594
595    // Bounded by the declared ceiling plus one byte, so a file that grew between the fstat above
596    // and this read is refused rather than served past the ceiling.
597    let mut bytes = Vec::with_capacity(metadata.len() as usize);
598    let mut limited = file.take(export.max_bytes.saturating_add(1));
599    limited
600        .read_to_end(&mut bytes)
601        .map_err(|e| io_to_resource_error(&e))?;
602    if bytes.len() as u64 > export.max_bytes {
603        return Err(ResourceError::TooLarge {
604            max_bytes: export.max_bytes,
605        });
606    }
607
608    let sha256 = murmur_artifact::sha256_hex(&bytes);
609    Ok(ReadResponse {
610        bytes,
611        sha256,
612        mtime_ms: mtime,
613    })
614}
615
616/// Serves one file named by a relative path beneath `root`, with no manifest export behind it.
617///
618/// The entry point for a host-process read of a path some *other* party chose — the plan
619/// scheduler dereferencing a tool's `data_path`. The host holds ambient filesystem authority, so
620/// `root` is the whole of the caller's boundary: the path is lowered, canonicalised and required
621/// to land beneath `root` by [`resolve_relpath_beneath_root`], the same predicate the resource
622/// plane's reader and the peer plane's mint use, and refusals come back with the same
623/// [`ResourceError::code`] vocabulary.
624///
625/// `policy` is a parameter of the caller's boundary, not of a containment class: pass
626/// [`SymlinkPolicy::Refuse`] unless the reader is inside the sandbox that owns `root`.
627pub(crate) fn read_file_beneath_root(
628    root: &Path,
629    relpath: &str,
630    max_bytes: u64,
631    policy: SymlinkPolicy,
632) -> Result<ReadResponse, ResourceError> {
633    let export = DeclaredExport {
634        declared_root: ".".to_string(),
635        root: root.to_path_buf(),
636        mode: ExportMode::ReadOnly,
637        max_bytes,
638    };
639    read_export_file_with_policy(&export, relpath, policy)
640}
641
642// ── list ──────────────────────────────────────────────────────────────────────
643
644/// Every regular file under the export root, sorted by path.
645///
646/// A missing root is `Ok(vec![])`, never a `404`: `exports.files.root` is not required to exist at
647/// launch, and only an *undeclared* plane refuses a listing. A file above `max_bytes` is listed
648/// with its real size — discovery must not lie about what is there — and refused on read.
649fn list_export_files(
650    export: &DeclaredExport,
651    policy: SymlinkPolicy,
652) -> Result<Vec<ListEntry>, ResourceError> {
653    let root_canon = match std::fs::canonicalize(&export.root) {
654        Ok(path) => path,
655        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
656        Err(error) => return Err(io_to_resource_error(&error)),
657    };
658    if !root_canon.is_dir() {
659        return Ok(Vec::new());
660    }
661
662    let mut entries = Vec::new();
663    let mut pending = vec![(root_canon.clone(), String::new())];
664    while let Some((dir, prefix)) = pending.pop() {
665        let reader = match std::fs::read_dir(&dir) {
666            Ok(reader) => reader,
667            // A directory that vanished mid-walk (the agent is still working) drops out of the
668            // listing rather than failing the whole request.
669            Err(_) => continue,
670        };
671        for entry in reader.flatten() {
672            let name = entry.file_name().to_string_lossy().to_string();
673            let relative = if prefix.is_empty() {
674                name.clone()
675            } else {
676                format!("{prefix}/{name}")
677            };
678            let Ok(file_type) = entry.file_type() else {
679                continue;
680            };
681            let path = entry.path();
682
683            if file_type.is_symlink() {
684                if policy == SymlinkPolicy::Refuse {
685                    continue;
686                }
687                // Follow, but only onto a regular file still beneath the root. A symlinked
688                // *directory* is never descended into: it would list the same bytes twice under
689                // two names and, if it pointed at an ancestor, would not terminate.
690                let Ok(canonical) = std::fs::canonicalize(&path) else {
691                    continue;
692                };
693                if !canonical.starts_with(&root_canon) {
694                    continue;
695                }
696                if let Some(entry) = describe_entry(&canonical, relative) {
697                    entries.push(entry);
698                }
699                continue;
700            }
701
702            if file_type.is_dir() {
703                pending.push((path, relative));
704            } else if file_type.is_file() {
705                if let Some(entry) = describe_entry(&path, relative) {
706                    entries.push(entry);
707                }
708            }
709        }
710    }
711    entries.sort_by(|a, b| a.path.cmp(&b.path));
712    Ok(entries)
713}
714
715/// One listing entry, taken from one open of the file: the size is the number of bytes hashed,
716/// so `size_bytes` and `sha256` describe the same version of it. `None` when the file went away
717/// or turned out not to be a regular file between the walk and the open.
718fn describe_entry(path: &Path, relative: String) -> Option<ListEntry> {
719    let (mut file, metadata) = open_regular_file(path).ok()?;
720    let mtime = mtime_ms(&metadata);
721    // Streamed rather than buffered: a listing is not bounded by `max_bytes` — an oversized file
722    // is still listed — so it must not be bounded by memory either.
723    let (size_bytes, sha256) = murmur_artifact::sha256_hex_of_reader(&mut file).ok()?;
724    Some(ListEntry {
725        path: relative,
726        size_bytes,
727        mtime_ms: mtime,
728        sha256,
729    })
730}
731
732// ── The transport-agnostic handler ────────────────────────────────────────────
733
734/// Answers one resource-plane request: a method, a raw request path, and nothing else.
735///
736/// Knows no socket, no framing and no authoriser, so binding it on a second listener with its own
737/// authentication is a matter of calling exactly this function and writing out the reply.
738///
739/// `raw_path` is the request target verbatim, still percent-encoded and possibly carrying a query
740/// string. Decoding is this function's job, never the caller's.
741pub async fn handle_resource_request(
742    plane: &ResourcePlane,
743    method: &str,
744    raw_path: &str,
745) -> ResourceResponse {
746    let path = raw_path.split('?').next().unwrap_or("");
747    let Some(rest) = path.strip_prefix(RESOURCE_PATH_PREFIX) else {
748        return error_response(&ResourceError::NotFound, None);
749    };
750
751    if rest == FILES_ROUTE || rest == "files/" {
752        return handle_list(plane, method).await;
753    }
754    if let Some(relpath) = rest.strip_prefix("files/") {
755        return handle_read(plane, method, relpath).await;
756    }
757    // No route to name, so nothing is traced — but the method still answers first. A `PUT` at an
758    // unknown path under the prefix is an attempt to write, and `405` with an `allow: GET` says
759    // there is no write path anywhere here, where a `404` would only say "not that one".
760    if method != "GET" {
761        return error_response(&ResourceError::MethodNotAllowed, None);
762    }
763    error_response(&ResourceError::NotFound, None)
764}
765
766/// The declared export a request may be answered from, or the refusal that stands in its place.
767///
768/// The method check comes first because it is a property of the request alone: a `PUT` is refused
769/// identically whether or not the capsule exports anything.
770fn servable_export<'a>(
771    plane: &'a ResourcePlane,
772    method: &str,
773) -> Result<&'a DeclaredExport, ResourceError> {
774    if method != "GET" {
775        return Err(ResourceError::MethodNotAllowed);
776    }
777    plane.export.as_ref().ok_or(ResourceError::NoResourcePlane)
778}
779
780async fn handle_list(plane: &ResourcePlane, method: &str) -> ResourceResponse {
781    let generation = plane.generation();
782    let class = plane.containment_achieved;
783
784    let export = match servable_export(plane, method) {
785        Ok(export) => export.clone(),
786        // No declared root to name: the record still says what was asked for and why it was
787        // refused, which is the whole of what an auditor needs from a denied request.
788        Err(error) => return refuse_list(plane, "", &error, generation, class).await,
789    };
790
791    let listed = {
792        let export = export.clone();
793        let policy = symlink_policy(class);
794        tokio::task::spawn_blocking(move || list_export_files(&export, policy))
795            .await
796            .unwrap_or_else(|join| Err(ResourceError::IoError(join.to_string())))
797    };
798
799    let entries = match listed {
800        Ok(entries) => entries,
801        Err(error) => {
802            return refuse_list(plane, &export.declared_root, &error, generation, class).await
803        }
804    };
805
806    if let Some(trace) = &plane.trace {
807        trace
808            .write_resource_list(
809                &export.declared_root,
810                entries.len(),
811                entries.iter().map(|entry| entry.size_bytes).sum(),
812                generation,
813                class,
814                "ok",
815                None,
816            )
817            .await;
818    }
819
820    let body = ListResponse {
821        root: export.declared_root.clone(),
822        mode: export.mode,
823        max_bytes: export.max_bytes,
824        generation,
825        containment_achieved: class,
826        entries,
827    };
828    ResourceResponse::framed(
829        200,
830        vec![
831            ("content-type".to_string(), "application/json".to_string()),
832            ("x-murmur-generation".to_string(), generation.to_string()),
833            ("x-murmur-containment".to_string(), class.to_string()),
834            ("x-murmur-export-root".to_string(), export.declared_root),
835        ],
836        serde_json::to_vec(&body).unwrap_or_default(),
837    )
838}
839
840async fn handle_read(plane: &ResourcePlane, method: &str, relpath: &str) -> ResourceResponse {
841    let generation = plane.generation();
842    let class = plane.containment_achieved;
843    // Decoded, but never validated or normalised: `%2e%2e%2f` and `../` are one attempt and read
844    // as one finding, while a refused path appears in the record as what it asked for rather than
845    // as something this module made servable.
846    let traced_path = decoded_request_path(relpath);
847
848    let export = match servable_export(plane, method) {
849        Ok(export) => export.clone(),
850        Err(error) => return refuse_read(plane, &traced_path, &error, generation, class).await,
851    };
852
853    let read = {
854        let export = export.clone();
855        let policy = symlink_policy(class);
856        let relpath = relpath.to_string();
857        tokio::task::spawn_blocking(move || read_export_file_with_policy(&export, &relpath, policy))
858            .await
859            .unwrap_or_else(|join| Err(ResourceError::IoError(join.to_string())))
860    };
861
862    let response = match read {
863        Ok(response) => response,
864        Err(error) => return refuse_read(plane, &traced_path, &error, generation, class).await,
865    };
866
867    if let Some(trace) = &plane.trace {
868        trace
869            .write_resource_read(
870                &traced_path,
871                "ok",
872                Some(response.bytes.len() as u64),
873                Some(response.sha256.clone()),
874                generation,
875                class,
876                None,
877            )
878            .await;
879    }
880
881    ResourceResponse::framed(
882        200,
883        vec![
884            (
885                "content-type".to_string(),
886                "application/octet-stream".to_string(),
887            ),
888            (
889                "etag".to_string(),
890                format!("\"sha256:{}\"", response.sha256),
891            ),
892            (
893                "x-murmur-mtime-ms".to_string(),
894                response.mtime_ms.to_string(),
895            ),
896            ("x-murmur-generation".to_string(), generation.to_string()),
897            ("x-murmur-containment".to_string(), class.to_string()),
898            ("x-murmur-export-root".to_string(), export.declared_root),
899        ],
900        response.bytes,
901    )
902}
903
904async fn refuse_list(
905    plane: &ResourcePlane,
906    root: &str,
907    error: &ResourceError,
908    generation: u64,
909    class: ContainmentClass,
910) -> ResourceResponse {
911    if let Some(trace) = &plane.trace {
912        trace
913            .write_resource_list(
914                root,
915                0,
916                0,
917                generation,
918                class,
919                error.code(),
920                Some(error.message()),
921            )
922            .await;
923    }
924    error_response(error, Some(generation))
925}
926
927async fn refuse_read(
928    plane: &ResourcePlane,
929    path: &str,
930    error: &ResourceError,
931    generation: u64,
932    class: ContainmentClass,
933) -> ResourceResponse {
934    if let Some(trace) = &plane.trace {
935        trace
936            .write_resource_read(
937                path,
938                error.code(),
939                None,
940                None,
941                generation,
942                class,
943                Some(error.message()),
944            )
945            .await;
946    }
947    error_response(error, Some(generation))
948}
949
950/// The requested path as the trace records it: percent-decoded, lossily where the bytes are not
951/// UTF-8, and otherwise untouched.
952fn decoded_request_path(raw: &str) -> String {
953    String::from_utf8_lossy(&percent_decode(raw)).into_owned()
954}
955
956fn error_response(error: &ResourceError, generation: Option<u64>) -> ResourceResponse {
957    let body = serde_json::json!({"error": error.code(), "message": error.message()});
958    let mut headers = vec![("content-type".to_string(), "application/json".to_string())];
959    if let Some(generation) = generation {
960        headers.push(("x-murmur-generation".to_string(), generation.to_string()));
961    }
962    if matches!(error, ResourceError::MethodNotAllowed) {
963        headers.push(("allow".to_string(), "GET".to_string()));
964    }
965    ResourceResponse::framed(
966        error.status(),
967        headers,
968        serde_json::to_vec(&body).unwrap_or_default(),
969    )
970}
971
972/// The reason phrase for a status either plane can return. Only these appear; anything else is a
973/// programming error rather than a response shape callers depend on.
974pub fn reason_phrase(status: u16) -> &'static str {
975    match status {
976        200 => "OK",
977        400 => "Bad Request",
978        401 => "Unauthorized",
979        403 => "Forbidden",
980        404 => "Not Found",
981        405 => "Method Not Allowed",
982        409 => "Conflict",
983        410 => "Gone",
984        413 => "Payload Too Large",
985        415 => "Unsupported Media Type",
986        422 => "Unprocessable Entity",
987        _ => "Internal Server Error",
988    }
989}
990
991#[cfg(test)]
992mod tests {
993    use super::*;
994    use std::io::Write;
995
996    fn export_for(root: &Path, max_bytes: u64) -> DeclaredExport {
997        DeclaredExport {
998            declared_root: "out/".to_string(),
999            root: root.to_path_buf(),
1000            mode: ExportMode::ReadOnly,
1001            max_bytes,
1002        }
1003    }
1004
1005    // ── percent-decoding and path rejection ──────────────────────────────────
1006
1007    #[test]
1008    fn percent_decoding_happens_before_validation() {
1009        // The whole reason decoding is first: validated as written, this looks like one opaque
1010        // component and reaches the filesystem as `../secret.txt`.
1011        assert_eq!(
1012            export_relpath_components("%2e%2e%2fsecret.txt"),
1013            Err(ResourceError::OutsideRoot)
1014        );
1015        assert_eq!(
1016            export_relpath_components("%2E%2E/secret.txt"),
1017            Err(ResourceError::OutsideRoot)
1018        );
1019    }
1020
1021    #[test]
1022    fn percent_decoding_accepts_ordinary_escapes() {
1023        assert_eq!(
1024            export_relpath_components("sub%20dir/report.md").unwrap(),
1025            vec!["sub dir".to_string(), "report.md".to_string()]
1026        );
1027    }
1028
1029    #[test]
1030    fn a_lone_percent_is_left_as_written() {
1031        assert_eq!(percent_decode("100%"), b"100%".to_vec());
1032        assert_eq!(percent_decode("%zz"), b"%zz".to_vec());
1033    }
1034
1035    #[test]
1036    fn every_escaping_shape_is_refused() {
1037        for path in [
1038            "",
1039            "..",
1040            "../secret.txt",
1041            "out/../../secret.txt",
1042            "/etc/passwd",
1043            "/",
1044            "./report.md",
1045            "a//b",
1046            "a/./b",
1047            "a/../b",
1048            "report.md%00.txt",
1049            "%00",
1050        ] {
1051            assert_eq!(
1052                export_relpath_components(path),
1053                Err(ResourceError::OutsideRoot),
1054                "path {path:?} must be refused"
1055            );
1056        }
1057    }
1058
1059    #[test]
1060    fn a_trailing_slash_names_the_same_file() {
1061        assert_eq!(
1062            export_relpath_components("dir/report.md/").unwrap(),
1063            vec!["dir".to_string(), "report.md".to_string()]
1064        );
1065    }
1066
1067    #[test]
1068    fn ordinary_relative_paths_survive() {
1069        assert_eq!(
1070            export_relpath_components("a/b/c.txt").unwrap(),
1071            vec!["a".to_string(), "b".to_string(), "c.txt".to_string()]
1072        );
1073    }
1074
1075    // ── the class-keyed symlink decision ─────────────────────────────────────
1076
1077    #[test]
1078    fn symlink_policy_covers_every_containment_class() {
1079        assert_eq!(
1080            symlink_policy(ContainmentClass::Scoped),
1081            SymlinkPolicy::Refuse
1082        );
1083        assert_eq!(
1084            symlink_policy(ContainmentClass::Sealed),
1085            SymlinkPolicy::FollowWithinRoot
1086        );
1087        assert_eq!(
1088            symlink_policy(ContainmentClass::Advisory),
1089            SymlinkPolicy::FollowWithinRoot
1090        );
1091    }
1092
1093    #[test]
1094    fn an_escaping_symlink_is_refused_at_every_class() {
1095        let dir = tempfile::tempdir().unwrap();
1096        let secret = dir.path().join("secret.txt");
1097        std::fs::write(&secret, b"top secret").unwrap();
1098        let root = dir.path().join("out");
1099        std::fs::create_dir(&root).unwrap();
1100        std::os::unix::fs::symlink(&secret, root.join("escape.txt")).unwrap();
1101        let export = export_for(&root, 1024);
1102
1103        for class in [
1104            ContainmentClass::Advisory,
1105            ContainmentClass::Scoped,
1106            ContainmentClass::Sealed,
1107        ] {
1108            let error = read_export_file_with_policy(&export, "escape.txt", symlink_policy(class))
1109                .expect_err("an escaping symlink must never be served");
1110            let expected = match class {
1111                ContainmentClass::Scoped => ResourceError::SymlinkRefused,
1112                _ => ResourceError::OutsideRoot,
1113            };
1114            assert_eq!(error, expected, "class {class}");
1115
1116            let entries = list_export_files(&export, symlink_policy(class)).unwrap();
1117            assert!(
1118                entries.is_empty(),
1119                "class {class}: an escaping symlink must not be listed; got {entries:?}"
1120            );
1121        }
1122    }
1123
1124    #[test]
1125    fn an_in_root_symlink_is_refused_under_scoped_and_followed_otherwise() {
1126        let dir = tempfile::tempdir().unwrap();
1127        let root = dir.path().join("out");
1128        std::fs::create_dir(&root).unwrap();
1129        std::fs::write(root.join("real.txt"), b"real bytes").unwrap();
1130        std::os::unix::fs::symlink("real.txt", root.join("alias.txt")).unwrap();
1131        let export = export_for(&root, 1024);
1132
1133        assert_eq!(
1134            read_export_file_with_policy(&export, "alias.txt", SymlinkPolicy::Refuse),
1135            Err(ResourceError::SymlinkRefused)
1136        );
1137        assert_eq!(
1138            list_export_files(&export, SymlinkPolicy::Refuse)
1139                .unwrap()
1140                .iter()
1141                .map(|entry| entry.path.clone())
1142                .collect::<Vec<_>>(),
1143            vec!["real.txt".to_string()]
1144        );
1145
1146        let followed =
1147            read_export_file_with_policy(&export, "alias.txt", SymlinkPolicy::FollowWithinRoot)
1148                .unwrap();
1149        assert_eq!(followed.bytes, b"real bytes");
1150        assert_eq!(
1151            list_export_files(&export, SymlinkPolicy::FollowWithinRoot)
1152                .unwrap()
1153                .len(),
1154            2
1155        );
1156    }
1157
1158    #[test]
1159    fn a_symlinked_directory_on_the_path_is_refused_under_scoped() {
1160        let dir = tempfile::tempdir().unwrap();
1161        let root = dir.path().join("out");
1162        std::fs::create_dir_all(root.join("real")).unwrap();
1163        std::fs::write(root.join("real/report.md"), b"hello").unwrap();
1164        std::os::unix::fs::symlink("real", root.join("alias")).unwrap();
1165        let export = export_for(&root, 1024);
1166
1167        assert_eq!(
1168            read_export_file_with_policy(&export, "alias/report.md", SymlinkPolicy::Refuse),
1169            Err(ResourceError::SymlinkRefused)
1170        );
1171    }
1172
1173    // ── read semantics ───────────────────────────────────────────────────────
1174
1175    #[test]
1176    fn a_read_hashes_the_bytes_it_serves() {
1177        let dir = tempfile::tempdir().unwrap();
1178        let root = dir.path().join("out");
1179        std::fs::create_dir(&root).unwrap();
1180        std::fs::write(root.join("report.md"), b"# report\n").unwrap();
1181        let response = read_export_file_with_policy(
1182            &export_for(&root, 1024),
1183            "report.md",
1184            SymlinkPolicy::FollowWithinRoot,
1185        )
1186        .unwrap();
1187        assert_eq!(response.bytes, b"# report\n");
1188        assert_eq!(response.sha256, murmur_artifact::sha256_hex(b"# report\n"));
1189        assert!(response.mtime_ms > 0);
1190    }
1191
1192    #[test]
1193    fn max_bytes_refuses_the_read_but_not_the_listing() {
1194        let dir = tempfile::tempdir().unwrap();
1195        let root = dir.path().join("out");
1196        std::fs::create_dir(&root).unwrap();
1197        std::fs::write(root.join("small.txt"), vec![b'a'; 100]).unwrap();
1198        std::fs::write(root.join("big.bin"), vec![b'b'; 4096]).unwrap();
1199        let export = export_for(&root, 1024);
1200
1201        assert_eq!(
1202            read_export_file_with_policy(&export, "big.bin", SymlinkPolicy::FollowWithinRoot),
1203            Err(ResourceError::TooLarge { max_bytes: 1024 })
1204        );
1205        assert_eq!(
1206            read_export_file_with_policy(&export, "small.txt", SymlinkPolicy::FollowWithinRoot)
1207                .unwrap()
1208                .bytes
1209                .len(),
1210            100
1211        );
1212
1213        let entries = list_export_files(&export, SymlinkPolicy::FollowWithinRoot).unwrap();
1214        let big = entries.iter().find(|e| e.path == "big.bin").unwrap();
1215        assert_eq!(
1216            big.size_bytes, 4096,
1217            "discovery must not hide an oversized file"
1218        );
1219    }
1220
1221    #[test]
1222    fn a_directory_is_not_a_regular_file() {
1223        let dir = tempfile::tempdir().unwrap();
1224        let root = dir.path().join("out");
1225        std::fs::create_dir_all(root.join("nested")).unwrap();
1226        assert_eq!(
1227            read_export_file_with_policy(
1228                &export_for(&root, 1024),
1229                "nested",
1230                SymlinkPolicy::FollowWithinRoot
1231            ),
1232            Err(ResourceError::NotARegularFile)
1233        );
1234    }
1235
1236    #[test]
1237    fn a_missing_root_lists_empty_and_reads_not_found() {
1238        let dir = tempfile::tempdir().unwrap();
1239        let root = dir.path().join("out");
1240        let export = export_for(&root, 1024);
1241        assert_eq!(
1242            list_export_files(&export, SymlinkPolicy::FollowWithinRoot).unwrap(),
1243            Vec::new()
1244        );
1245        assert_eq!(
1246            read_export_file_with_policy(&export, "report.md", SymlinkPolicy::FollowWithinRoot),
1247            Err(ResourceError::NotFound)
1248        );
1249    }
1250
1251    #[test]
1252    fn a_listing_is_recursive_and_sorted() {
1253        let dir = tempfile::tempdir().unwrap();
1254        let root = dir.path().join("out");
1255        std::fs::create_dir_all(root.join("b/c")).unwrap();
1256        std::fs::write(root.join("z.txt"), b"z").unwrap();
1257        std::fs::write(root.join("b/y.txt"), b"y").unwrap();
1258        std::fs::write(root.join("b/c/x.txt"), b"x").unwrap();
1259        let entries = list_export_files(&export_for(&root, 1024), SymlinkPolicy::Refuse).unwrap();
1260        assert_eq!(
1261            entries
1262                .iter()
1263                .map(|entry| entry.path.clone())
1264                .collect::<Vec<_>>(),
1265            vec![
1266                "b/c/x.txt".to_string(),
1267                "b/y.txt".to_string(),
1268                "z.txt".to_string()
1269            ]
1270        );
1271        assert_eq!(entries[2].sha256, murmur_artifact::sha256_hex(b"z"));
1272    }
1273
1274    #[test]
1275    fn a_fifo_is_refused_without_blocking() {
1276        let dir = tempfile::tempdir().unwrap();
1277        let root = dir.path().join("out");
1278        std::fs::create_dir(&root).unwrap();
1279        let fifo = root.join("pipe");
1280        let status = std::process::Command::new("mkfifo")
1281            .arg(&fifo)
1282            .status()
1283            .expect("mkfifo should be runnable");
1284        if !status.success() {
1285            return;
1286        }
1287        assert_eq!(
1288            read_export_file_with_policy(
1289                &export_for(&root, 1024),
1290                "pipe",
1291                SymlinkPolicy::FollowWithinRoot
1292            ),
1293            Err(ResourceError::NotARegularFile)
1294        );
1295        assert!(
1296            list_export_files(&export_for(&root, 1024), SymlinkPolicy::Refuse)
1297                .unwrap()
1298                .is_empty()
1299        );
1300    }
1301
1302    // ── error table ──────────────────────────────────────────────────────────
1303
1304    #[test]
1305    fn every_error_maps_to_its_documented_status() {
1306        for (error, code, status) in [
1307            (ResourceError::NoResourcePlane, "no_resource_plane", 404),
1308            (ResourceError::NotFound, "not_found", 404),
1309            (ResourceError::OutsideRoot, "outside_root", 403),
1310            (ResourceError::SymlinkRefused, "symlink_refused", 403),
1311            (ResourceError::NotARegularFile, "not_a_regular_file", 403),
1312            (ResourceError::TooLarge { max_bytes: 1 }, "too_large", 413),
1313            (ResourceError::MethodNotAllowed, "method_not_allowed", 405),
1314            (ResourceError::IoError("x".into()), "io_error", 500),
1315        ] {
1316            assert_eq!(error.code(), code);
1317            assert_eq!(error.status(), status);
1318        }
1319    }
1320
1321    // ── the launch-time root check ───────────────────────────────────────────
1322
1323    fn file_export(root: &str) -> FileExport {
1324        FileExport {
1325            root: root.to_string(),
1326            mode: ExportMode::ReadOnly,
1327            max_bytes: 1024,
1328        }
1329    }
1330
1331    /// The refusal is at launch rather than per request, so the first file never leaves: a root
1332    /// that already exists as a symlink out of the workdir stops the session before it starts.
1333    #[test]
1334    fn a_root_that_already_escapes_the_workdir_refuses_the_launch() {
1335        let workdir = tempfile::tempdir().unwrap();
1336        let outside = tempfile::tempdir().unwrap();
1337        std::os::unix::fs::symlink(outside.path(), workdir.path().join("out")).unwrap();
1338
1339        let error = check_export_root(workdir.path(), &file_export("out/")).unwrap_err();
1340        let RuntimeError::ExportRootOutsideWorkdir {
1341            declared, resolved, ..
1342        } = &error
1343        else {
1344            panic!("expected ExportRootOutsideWorkdir, got {error:?}");
1345        };
1346        // Both paths are named, because "outside the workdir" is not actionable without saying
1347        // where the root actually landed.
1348        assert_eq!(declared, "out/");
1349        assert_eq!(
1350            Path::new(resolved),
1351            std::fs::canonicalize(outside.path()).unwrap()
1352        );
1353    }
1354
1355    /// A root the agent has not created yet is not an escape. `exports.files.root` is explicitly
1356    /// not required to exist at launch, and every request resolves it afresh.
1357    #[test]
1358    fn a_root_that_does_not_exist_yet_is_accepted() {
1359        let workdir = tempfile::tempdir().unwrap();
1360        assert!(check_export_root(workdir.path(), &file_export("out/")).is_ok());
1361
1362        std::fs::create_dir(workdir.path().join("out")).unwrap();
1363        assert!(check_export_root(workdir.path(), &file_export("out/")).is_ok());
1364    }
1365
1366    /// A workdir that does not exist yet — no `--workdir`, so the session directory is created
1367    /// after this check — has nothing under it that could already point elsewhere.
1368    #[test]
1369    fn a_workdir_that_does_not_exist_yet_is_accepted() {
1370        let parent = tempfile::tempdir().unwrap();
1371        let missing = parent.path().join("not-created-yet");
1372        assert!(check_export_root(&missing, &file_export("out/")).is_ok());
1373    }
1374
1375    /// A symlink that stays inside the workdir is not an escape: the check asks where the root
1376    /// landed, not how it was spelled.
1377    #[test]
1378    fn a_root_symlinked_within_the_workdir_is_accepted() {
1379        let workdir = tempfile::tempdir().unwrap();
1380        std::fs::create_dir(workdir.path().join("real")).unwrap();
1381        std::os::unix::fs::symlink(workdir.path().join("real"), workdir.path().join("out"))
1382            .unwrap();
1383
1384        assert!(check_export_root(workdir.path(), &file_export("out/")).is_ok());
1385    }
1386
1387    // ── the handler ──────────────────────────────────────────────────────────
1388
1389    fn plane_for(export: Option<DeclaredExport>, class: ContainmentClass) -> ResourcePlane {
1390        ResourcePlane::with_export(export, class, Arc::new(AtomicU64::new(0)), None)
1391    }
1392
1393    #[tokio::test]
1394    async fn an_undeclared_plane_denies_both_verbs() {
1395        let plane = plane_for(None, ContainmentClass::Advisory);
1396        for path in ["/resources/files", "/resources/files/report.md"] {
1397            let response = handle_resource_request(&plane, "GET", path).await;
1398            assert_eq!(response.status, 404);
1399            let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
1400            assert_eq!(body["error"], "no_resource_plane");
1401        }
1402    }
1403
1404    #[tokio::test]
1405    async fn every_write_verb_is_refused_with_an_allow_header() {
1406        let dir = tempfile::tempdir().unwrap();
1407        let root = dir.path().join("out");
1408        std::fs::create_dir(&root).unwrap();
1409        std::fs::write(root.join("report.md"), b"hello").unwrap();
1410        let plane = plane_for(Some(export_for(&root, 1024)), ContainmentClass::Advisory);
1411
1412        for method in ["POST", "PUT", "PATCH", "DELETE"] {
1413            let response =
1414                handle_resource_request(&plane, method, "/resources/files/report.md").await;
1415            assert_eq!(response.status, 405, "{method}");
1416            assert!(response
1417                .headers
1418                .iter()
1419                .any(|(name, value)| name == "allow" && value == "GET"));
1420        }
1421        assert_eq!(
1422            std::fs::read(root.join("report.md")).unwrap(),
1423            b"hello".to_vec()
1424        );
1425        assert!(!root.join("new.txt").exists());
1426    }
1427
1428    #[tokio::test]
1429    async fn a_read_carries_its_validator_and_provenance() {
1430        let dir = tempfile::tempdir().unwrap();
1431        let root = dir.path().join("out");
1432        std::fs::create_dir(&root).unwrap();
1433        let mut file = std::fs::File::create(root.join("report.md")).unwrap();
1434        file.write_all(b"# report\n").unwrap();
1435        drop(file);
1436
1437        let generation = Arc::new(AtomicU64::new(7));
1438        let plane = ResourcePlane::with_export(
1439            Some(export_for(&root, 1024)),
1440            ContainmentClass::Scoped,
1441            Arc::clone(&generation),
1442            None,
1443        );
1444        let response = handle_resource_request(&plane, "GET", "/resources/files/report.md").await;
1445        assert_eq!(response.status, 200);
1446        assert_eq!(response.body, b"# report\n");
1447        let header = |name: &str| {
1448            response
1449                .headers
1450                .iter()
1451                .find(|(key, _)| key == name)
1452                .map(|(_, value)| value.clone())
1453                .unwrap_or_default()
1454        };
1455        assert_eq!(
1456            header("etag"),
1457            format!("\"sha256:{}\"", murmur_artifact::sha256_hex(b"# report\n"))
1458        );
1459        assert_eq!(header("x-murmur-generation"), "7");
1460        assert_eq!(header("x-murmur-containment"), "scoped");
1461        assert_eq!(header("x-murmur-export-root"), "out/");
1462    }
1463
1464    #[tokio::test]
1465    async fn a_query_string_does_not_select_a_generation() {
1466        let dir = tempfile::tempdir().unwrap();
1467        let root = dir.path().join("out");
1468        std::fs::create_dir(&root).unwrap();
1469        std::fs::write(root.join("report.md"), b"now").unwrap();
1470        let plane = ResourcePlane::with_export(
1471            Some(export_for(&root, 1024)),
1472            ContainmentClass::Advisory,
1473            Arc::new(AtomicU64::new(3)),
1474            None,
1475        );
1476        let response =
1477            handle_resource_request(&plane, "GET", "/resources/files/report.md?generation=1").await;
1478        assert_eq!(response.status, 200);
1479        assert_eq!(response.body, b"now");
1480    }
1481
1482    #[tokio::test]
1483    async fn a_list_reports_the_declared_block_verbatim() {
1484        let dir = tempfile::tempdir().unwrap();
1485        let root = dir.path().join("out");
1486        std::fs::create_dir(&root).unwrap();
1487        std::fs::write(root.join("report.md"), b"hello").unwrap();
1488        let plane = plane_for(Some(export_for(&root, 4096)), ContainmentClass::Advisory);
1489        let response = handle_resource_request(&plane, "GET", "/resources/files").await;
1490        assert_eq!(response.status, 200);
1491        let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
1492        assert_eq!(body["root"], "out/");
1493        assert_eq!(body["mode"], "read-only");
1494        assert_eq!(body["max_bytes"], 4096);
1495        assert_eq!(body["generation"], 0);
1496        assert_eq!(body["containment_achieved"], "advisory");
1497        assert_eq!(body["entries"][0]["path"], "report.md");
1498        assert_eq!(body["entries"][0]["size_bytes"], 5);
1499    }
1500
1501    #[tokio::test]
1502    async fn an_unknown_route_under_the_prefix_is_not_found() {
1503        let plane = plane_for(None, ContainmentClass::Advisory);
1504        let response = handle_resource_request(&plane, "GET", "/resources/secrets").await;
1505        assert_eq!(response.status, 404);
1506        let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
1507        assert_eq!(body["error"], "not_found");
1508    }
1509
1510    /// There is no write path anywhere under the prefix, including at a path that names no route.
1511    #[tokio::test]
1512    async fn an_unknown_route_still_answers_the_method_first() {
1513        let plane = plane_for(None, ContainmentClass::Advisory);
1514        let response = handle_resource_request(&plane, "PUT", "/resources/secrets").await;
1515        assert_eq!(response.status, 405);
1516        assert!(response
1517            .headers
1518            .iter()
1519            .any(|(name, value)| name == "allow" && value == "GET"));
1520    }
1521
1522    /// Every response frames itself, so a transport never has to know it owed a `content-length`
1523    /// and a caller can tell a complete body from a truncated one.
1524    #[tokio::test]
1525    async fn every_response_carries_its_own_content_length() {
1526        let dir = tempfile::tempdir().unwrap();
1527        let root = dir.path().join("out");
1528        std::fs::create_dir(&root).unwrap();
1529        std::fs::write(root.join("report.md"), b"hello").unwrap();
1530        let plane = plane_for(Some(export_for(&root, 1024)), ContainmentClass::Advisory);
1531
1532        for (method, path) in [
1533            ("GET", "/resources/files"),
1534            ("GET", "/resources/files/report.md"),
1535            ("GET", "/resources/files/../secret.txt"),
1536            ("PUT", "/resources/files/report.md"),
1537        ] {
1538            let response = handle_resource_request(&plane, method, path).await;
1539            let declared = response
1540                .headers
1541                .iter()
1542                .find(|(name, _)| name == "content-length")
1543                .map(|(_, value)| value.clone())
1544                .unwrap_or_else(|| panic!("{method} {path} must declare a content-length"));
1545            assert_eq!(
1546                declared,
1547                response.body.len().to_string(),
1548                "{method} {path}: content-length must match the body served"
1549            );
1550        }
1551    }
1552}