Skip to main content

tabnas_multisource/
vfs.rs

1/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */
2
3//! The read-only filesystem seam the `file` and `pkg` resolvers reach
4//! through.
5//!
6//! The canonical TypeScript injects a filesystem per parse as
7//! `ctx.meta.fs`, because a JavaScript parse metadata object can carry a
8//! whole `node:fs` module. A Rust parse metadata value is a
9//! [`tabnas::Value`] and cannot carry a trait object, so the seam is a
10//! typed option instead: [`SourceFs`] on the plugin options, or on one
11//! resolver. That is the Rust spelling of Go's `MultiSourceOptions.FS`,
12//! and it is what lets a test resolve from a map with no disk at all and
13//! a caller confine resolution to a directory it chooses.
14
15use std::collections::BTreeMap;
16use std::fmt;
17use std::path::{Component, Path, PathBuf};
18use std::sync::Arc;
19
20/// One entry of a directory listing.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct DirEntry {
23    /// The entry's own name, without any directory part.
24    pub name: String,
25    /// Whether the entry is a directory.
26    pub is_dir: bool,
27}
28
29/// A read-only view of a filesystem.
30///
31/// Every path a resolver touches goes through one of these, so a caller
32/// decides what a document can reach. [`OsFs`] reads the real filesystem
33/// with absolute paths; [`MapFs`] reads an in-memory map with relative,
34/// slash-separated paths, the Rust counterpart of Go's
35/// `testing/fstest.MapFS` and of the `memfs` the TypeScript tests inject.
36///
37/// Implementations must be `Send + Sync`: a `Tabnas` instance parses
38/// through `&self` and may be shared between threads.
39pub trait SourceFs: Send + Sync {
40    /// Read the file at a canonical path. `None` means it is not there,
41    /// or cannot be read, which resolution treats the same way.
42    fn read_file(&self, path: &str) -> Option<String>;
43
44    /// List a directory. `None` means it is not there or is unreadable.
45    fn read_dir(&self, path: &str) -> Option<Vec<DirEntry>>;
46
47    /// Join path elements in this filesystem's convention.
48    fn join(&self, parts: &[&str]) -> String;
49
50    /// The parent directory of `path`.
51    fn dir(&self, path: &str) -> String;
52
53    /// The canonical lookup form of a possibly relative path.
54    fn canon(&self, path: &str) -> String;
55
56    /// The path `path` names once every link on the way to it has been
57    /// followed, which is what a sandbox root has to be compared
58    /// against: a purely lexical comparison answers for the path as
59    /// written, and a later read follows the links.
60    ///
61    /// `None` means the path cannot be reduced to a real one and must
62    /// therefore be refused rather than guessed at: a dangling or
63    /// looping symbolic link is the case, and its target could come
64    /// into existence before the read.
65    ///
66    /// The default is the lexical [`SourceFs::canon`], which is exact
67    /// for a filesystem that has no links at all, such as [`MapFs`].
68    /// [`OsFs`] overrides it, because the real one does.
69    fn real_path(&self, path: &str) -> Option<String> {
70        Some(self.canon(path))
71    }
72
73    /// Whether this filesystem addresses files by NATIVE absolute
74    /// paths, as [`OsFs`] does, rather than by relative,
75    /// slash-separated ones.
76    ///
77    /// It decides only how a sandbox root is compared against a
78    /// candidate, and the default is the conservative answer: an
79    /// injected filesystem keys on slashes, so `/` is the separator and
80    /// a Windows drive letter is not in play.
81    fn native_paths(&self) -> bool {
82        false
83    }
84}
85
86impl fmt::Debug for dyn SourceFs {
87    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88        formatter.write_str("<SourceFs>")
89    }
90}
91
92/// The real filesystem, addressed by absolute native paths.
93#[derive(Clone, Copy, Debug, Default)]
94pub struct OsFs;
95
96impl SourceFs for OsFs {
97    fn read_file(&self, path: &str) -> Option<String> {
98        std::fs::read(path)
99            .ok()
100            .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
101    }
102
103    fn read_dir(&self, path: &str) -> Option<Vec<DirEntry>> {
104        let mut entries = Vec::new();
105        for entry in std::fs::read_dir(path).ok()? {
106            let Ok(entry) = entry else { continue };
107            let is_dir = entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false);
108            entries.push(DirEntry {
109                name: entry.file_name().to_string_lossy().into_owned(),
110                is_dir,
111            });
112        }
113        // `read_dir` yields entries in whatever order the platform
114        // stores them, so a preload of one directory would key its map
115        // differently from run to run. Sorting makes a scan reproducible.
116        entries.sort_by(|left, right| left.name.cmp(&right.name));
117        Some(entries)
118    }
119
120    fn join(&self, parts: &[&str]) -> String {
121        let mut joined = PathBuf::new();
122        for part in parts {
123            joined.push(part);
124        }
125        lexical(&joined).to_string_lossy().into_owned()
126    }
127
128    fn dir(&self, path: &str) -> String {
129        match Path::new(path).parent() {
130            // A bare relative name such as `main.jsonic` has an EMPTY
131            // parent, and empty is the answer: the canonical resolver
132            // reads `Path.parse(path).dir`, which is `''` for that path,
133            // and `source_dir` returns the same. Discarding it and
134            // falling back to the filename made the file its own
135            // directory, so a reference beside it was searched for at
136            // `main.jsonic/child.jsonic`.
137            Some(parent) => parent.to_string_lossy().into_owned(),
138            // A root has no parent: it is its own directory, which is
139            // also what stops an ancestor walk.
140            None => path.to_string(),
141        }
142    }
143
144    fn native_paths(&self) -> bool {
145        true
146    }
147
148    fn canon(&self, path: &str) -> String {
149        lexical(&absolute(path)).to_string_lossy().into_owned()
150    }
151
152    fn real_path(&self, path: &str) -> Option<String> {
153        let absolute = lexical(&absolute(path));
154
155        // The whole path exists: the kernel has just followed every
156        // link in it for us, so this is the path a read would reach.
157        if let Ok(real) = std::fs::canonicalize(&absolute) {
158            return Some(real.to_string_lossy().into_owned());
159        }
160
161        // It does not, which is the ordinary case while a reference is
162        // still being searched for. Resolve the deepest part that DOES
163        // exist and re-attach the rest, so the answer is real as far as
164        // the filesystem goes and lexical only beyond it, where there
165        // is nothing yet to follow.
166        let mut prefix = absolute.clone();
167        let mut rest: Vec<std::ffi::OsString> = Vec::new();
168        loop {
169            if let Ok(real) = std::fs::canonicalize(&prefix) {
170                let mut resolved = real;
171                for name in rest.iter().rev() {
172                    resolved.push(name);
173                }
174                return Some(resolved.to_string_lossy().into_owned());
175            }
176            // The component is THERE but did not resolve: a dangling or
177            // looping link. Its target may exist by the time anything
178            // reads it, and nothing here can say where that target
179            // would be, so refuse rather than answer.
180            if std::fs::symlink_metadata(&prefix).is_ok() {
181                return None;
182            }
183            let (Some(parent), Some(name)) = (prefix.parent(), prefix.file_name()) else {
184                // Nothing of the path exists, not even its root, so
185                // there is no link in it to follow.
186                return Some(absolute.to_string_lossy().into_owned());
187            };
188            rest.push(name.to_os_string());
189            prefix = parent.to_path_buf();
190        }
191    }
192}
193
194/// `path` as an absolute path, against the working directory when it is
195/// relative. Purely textual: nothing is read.
196fn absolute(path: &str) -> PathBuf {
197    let candidate = Path::new(path);
198    if candidate.is_absolute() {
199        candidate.to_path_buf()
200    } else {
201        match std::env::current_dir() {
202            Ok(cwd) => cwd.join(candidate),
203            Err(_) => candidate.to_path_buf(),
204        }
205    }
206}
207
208/// An in-memory filesystem: relative, slash-separated paths to content.
209///
210/// Directories are implied by the keys, so `MapFs::from([("a/b.jsonic",
211/// "x:1")])` has a directory `a`. This is the hermetic resolver the
212/// tests use, and the shape a caller supplies to sandbox a parse to
213/// content it has already vetted.
214#[derive(Clone, Debug, Default)]
215pub struct MapFs {
216    files: BTreeMap<String, String>,
217}
218
219impl MapFs {
220    /// An empty filesystem.
221    pub fn new() -> Self {
222        Self::default()
223    }
224
225    /// Add one file, replacing any file already at that path.
226    pub fn insert(&mut self, path: impl AsRef<str>, content: impl Into<String>) -> &mut Self {
227        self.files.insert(clean(path.as_ref()), content.into());
228        self
229    }
230
231    /// Add one file, by value, so a filesystem can be built in an
232    /// expression.
233    pub fn with(mut self, path: impl AsRef<str>, content: impl Into<String>) -> Self {
234        self.insert(path, content);
235        self
236    }
237
238    /// Every path this filesystem holds, in sorted order.
239    pub fn paths(&self) -> Vec<&str> {
240        self.files.keys().map(String::as_str).collect()
241    }
242}
243
244impl<K, V> FromIterator<(K, V)> for MapFs
245where
246    K: AsRef<str>,
247    V: Into<String>,
248{
249    fn from_iter<T: IntoIterator<Item = (K, V)>>(entries: T) -> Self {
250        let mut filesystem = MapFs::new();
251        for (path, content) in entries {
252            filesystem.insert(path, content);
253        }
254        filesystem
255    }
256}
257
258impl<K, V, const N: usize> From<[(K, V); N]> for MapFs
259where
260    K: AsRef<str>,
261    V: Into<String>,
262{
263    fn from(entries: [(K, V); N]) -> Self {
264        entries.into_iter().collect()
265    }
266}
267
268impl SourceFs for MapFs {
269    fn read_file(&self, path: &str) -> Option<String> {
270        self.files.get(&clean(path)).cloned()
271    }
272
273    fn read_dir(&self, path: &str) -> Option<Vec<DirEntry>> {
274        let folder = clean(path);
275        let prefix = if folder == "." {
276            String::new()
277        } else {
278            format!("{folder}/")
279        };
280        let mut entries: BTreeMap<String, bool> = BTreeMap::new();
281        for key in self.files.keys() {
282            let Some(rest) = key.strip_prefix(prefix.as_str()) else {
283                continue;
284            };
285            if rest.is_empty() {
286                continue;
287            }
288            match rest.split_once('/') {
289                Some((head, _)) => {
290                    entries.insert(head.to_string(), true);
291                }
292                None => {
293                    entries.insert(rest.to_string(), false);
294                }
295            }
296        }
297        if entries.is_empty() && folder != "." {
298            return None;
299        }
300        Some(
301            entries
302                .into_iter()
303                .map(|(name, is_dir)| DirEntry { name, is_dir })
304                .collect(),
305        )
306    }
307
308    fn join(&self, parts: &[&str]) -> String {
309        clean(&parts.join("/"))
310    }
311
312    fn dir(&self, path: &str) -> String {
313        let cleaned = clean(path);
314        match cleaned.rsplit_once('/') {
315            Some((head, _)) if !head.is_empty() => head.to_string(),
316            Some(_) => ".".to_string(),
317            None => ".".to_string(),
318        }
319    }
320
321    fn canon(&self, path: &str) -> String {
322        clean(path)
323    }
324}
325
326/// Normalize a path into a map key: slash separated, `.` and `..`
327/// resolved, no leading slash, and `.` for the root. The counterpart of
328/// Go's `fsClean`.
329pub(crate) fn clean(path: &str) -> String {
330    let unified = path.replace('\\', "/");
331    let mut parts: Vec<&str> = Vec::new();
332    for segment in unified.split('/') {
333        match segment {
334            "" | "." => {}
335            ".." => {
336                // A `..` that would climb above the root is dropped,
337                // exactly as `path.Clean` drops it, so a reference can
338                // never name a parent of the filesystem root.
339                parts.pop();
340            }
341            other => parts.push(other),
342        }
343    }
344    if parts.is_empty() {
345        ".".to_string()
346    } else {
347        parts.join("/")
348    }
349}
350
351/// Resolve `.` and `..` without touching the filesystem.
352///
353/// Deliberately lexical: `std::fs::canonicalize` requires the path to
354/// exist, and resolution asks about paths that mostly do not. That makes
355/// it the wrong answer for a confinement check, which has to know where
356/// the links go: [`SourceFs::real_path`] is what that check uses, and it
357/// falls back to this only for the part of a path that is not there yet.
358fn lexical(path: &Path) -> PathBuf {
359    let mut out = PathBuf::new();
360    for component in path.components() {
361        match component {
362            Component::CurDir => {}
363            Component::ParentDir => {
364                if !out.pop() {
365                    out.push("..");
366                }
367            }
368            other => out.push(other.as_os_str()),
369        }
370    }
371    if out.as_os_str().is_empty() {
372        out.push(".");
373    }
374    out
375}
376
377/// Is `candidate` at or below `root`, comparing whole path segments?
378///
379/// Both are compared after lexical resolution, so `root/../etc` is
380/// rejected rather than accepted on the strength of its prefix. Segment
381/// comparison is what stops `/srv/appdata` passing for `/srv/app`.
382///
383/// This is the comparison only. A caller confining reads to a root must
384/// pass paths that [`SourceFs::real_path`] has already resolved, or a
385/// symbolic link inside the root will pass a check its target could
386/// never pass.
387pub(crate) fn within_root(candidate: &str, root: &str, os_paths: bool) -> bool {
388    let (candidate, root) = if os_paths {
389        (
390            lexical(Path::new(candidate)).to_string_lossy().into_owned(),
391            lexical(Path::new(root)).to_string_lossy().into_owned(),
392        )
393    } else {
394        (clean(candidate), clean(root))
395    };
396    if root.is_empty() || root == "." {
397        return true;
398    }
399    if candidate == root {
400        return true;
401    }
402    let separator = if os_paths {
403        std::path::MAIN_SEPARATOR
404    } else {
405        '/'
406    };
407    let mut prefix = root;
408    if !prefix.ends_with(separator) {
409        prefix.push(separator);
410    }
411    candidate.starts_with(&prefix)
412}
413
414/// A shared filesystem handle.
415pub type SharedFs = Arc<dyn SourceFs>;
416
417/// The real filesystem as a shared handle.
418pub fn os_fs() -> SharedFs {
419    Arc::new(OsFs)
420}