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