mermaid-runtime 0.12.2

Daemon-safe runtime core for Mermaid
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Lexical path containment for the runtime crate.
//!
//! Resolves a caller- or manifest-supplied path against a trusted root,
//! collapsing `.`/`..` *without* touching the filesystem, and rejects anything
//! that escapes the root. Used by approval replay ([`crate::approval`]) and
//! checkpoint restore ([`crate::checkpoint`]) to confine writes/deletes whose
//! paths come from stored (and therefore potentially tampered) state.
//!
//! This is the runtime-crate sibling of the main crate's `path_safety` helper;
//! `mermaid-runtime` is the lower crate and cannot depend on it.

use std::fs::File;
use std::io;
use std::path::{Component, Path, PathBuf};

use anyhow::Result;

/// Resolve `raw` against `root` and confirm it stays inside `root`.
///
/// `raw` may be relative (joined onto `root`) or absolute (taken as-is). Both
/// the candidate and the root are normalized lexically — `.` is dropped and
/// `..` pops the previous component — so traversal is resolved without symlink
/// expansion or filesystem access (the target may not exist yet, as on a fresh
/// checkout). Returns the normalized in-root path, or `Err` if it escapes.
pub(crate) fn contain_within(root: &Path, raw: &str) -> Result<PathBuf> {
    let candidate = if Path::new(raw).is_absolute() {
        PathBuf::from(raw)
    } else {
        root.join(raw)
    };
    let lexical = normalize_lexical(&candidate);
    let root = normalize_lexical(root);
    anyhow::ensure!(
        lexical.starts_with(&root),
        "path escapes the project root: {raw}"
    );
    Ok(lexical)
}

/// Like [`contain_within`], but also defeats a symlink planted *inside* the
/// root that would redirect a write/delete outside it: the canonical form of
/// the target's nearest existing ancestor must stay within the canonical root.
///
/// The target itself may not exist yet (restoring a deleted file), so we walk
/// up to the nearest existing ancestor and canonicalize that. Falls back to the
/// lexical result when the root doesn't yet exist on disk (nothing to escape
/// through).
pub(crate) fn contain_within_canonical(root: &Path, raw: &str) -> Result<PathBuf> {
    let lexical = contain_within(root, raw)?;
    let canon_root = match std::fs::canonicalize(root) {
        Ok(r) => r,
        Err(_) => return Ok(lexical),
    };
    let mut ancestor = lexical.as_path();
    let existing = loop {
        if ancestor.exists() {
            break Some(ancestor);
        }
        match ancestor.parent() {
            Some(p) => ancestor = p,
            None => break None,
        }
    };
    if let Some(existing) = existing
        && let Ok(canon) = std::fs::canonicalize(existing)
    {
        anyhow::ensure!(
            canon.starts_with(&canon_root),
            "path escapes the project root via a symlink: {raw}"
        );
    }
    Ok(lexical)
}

/// Collapse `.` and `..` components lexically (no filesystem access, no symlink
/// resolution).
fn normalize_lexical(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {},
            Component::ParentDir => {
                out.pop();
            },
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// What kind of access an [`open_beneath`] call needs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenIntent {
    /// Open an existing file read-only.
    Read,
    /// Create-or-truncate for writing (`O_WRONLY|O_CREAT|O_TRUNC`).
    WriteTruncate,
}

/// Open `root`-relative `rel` for `intent` **without ever traversing out of
/// `root`** — closing the check-then-write TOCTOU where an intermediate
/// directory is swapped for a symlink after a lexical path check but before the
/// operation (#77). The returned [`File`] is bound to the exact inode the
/// confinement resolved, so subsequent reads/writes can't be redirected.
///
/// On Linux this is enforced atomically by the kernel via
/// `openat2(RESOLVE_BENEATH)` relative to a directory fd for `root`. We use
/// `RESOLVE_BENEATH` (which forbids escaping the root via absolute paths, `..`,
/// or magic links) but **not** `RESOLVE_NO_SYMLINKS`, so legitimate *in-tree*
/// symlinks keep working — only escapes are refused, matching the existing
/// [`contain_within_canonical`] semantics. On pre-5.6 kernels (`ENOSYS`) or
/// non-Linux targets it falls back to `contain_within_canonical` + a plain open
/// (documented best-effort: the lexical check still holds, but the open is by
/// path).
pub fn open_beneath(root: &Path, rel: &Path, intent: OpenIntent) -> io::Result<File> {
    #[cfg(target_os = "linux")]
    {
        match linux::open_beneath(root, rel, intent) {
            Err(e) if e == rustix::io::Errno::NOSYS => {}, // pre-5.6 kernel: fall through
            other => return other.map_err(io::Error::from),
        }
    }
    fallback::open(root, rel, intent)
}

/// Confined `mkdir -p` for a `root`-relative directory path: creates each
/// missing component beneath `root`, refusing to descend through a symlink that
/// escapes (#77). On Linux: `mkdirat` + `openat2(RESOLVE_BENEATH)` per
/// component; otherwise the `contain_within_canonical` + `std::fs` fallback.
pub fn create_dir_all_beneath(root: &Path, rel: &Path) -> io::Result<()> {
    #[cfg(target_os = "linux")]
    {
        match linux::create_dir_all_beneath(root, rel) {
            Err(e) if e == rustix::io::Errno::NOSYS => {},
            other => return other.map_err(io::Error::from),
        }
    }
    fallback::create_dir_all(root, rel)
}

/// Confined unlink of a `root`-relative file (#77): opens the parent under
/// `RESOLVE_BENEATH` and `unlinkat`s the leaf, so a swapped-in symlink parent
/// can't redirect the delete outside `root`.
pub fn remove_file_beneath(root: &Path, rel: &Path) -> io::Result<()> {
    #[cfg(target_os = "linux")]
    {
        match linux::remove_file_beneath(root, rel) {
            Err(e) if e == rustix::io::Errno::NOSYS => {},
            other => return other.map_err(io::Error::from),
        }
    }
    fallback::remove_file(root, rel)
}

/// Linux `openat2(RESOLVE_BENEATH)` implementation. Each fn returns
/// `Err(Errno::NOSYS)` on a kernel that predates `openat2` (5.6) so the public
/// wrapper can fall back.
#[cfg(target_os = "linux")]
mod linux {
    use std::fs::File;
    use std::path::{Component, Path};

    use rustix::fd::OwnedFd;
    use rustix::fs::{AtFlags, Mode, OFlags, ResolveFlags, mkdirat, open, openat2, unlinkat};
    use rustix::io::Errno;

    use super::OpenIntent;

    /// Open a path-only (`O_PATH`) directory fd for `dir`, used as the anchor
    /// for the confined `openat2` calls below.
    fn open_dir(dir: &Path) -> Result<OwnedFd, Errno> {
        open(
            dir,
            OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,
            Mode::empty(),
        )
    }

    /// Descend into `name` beneath `dir_fd`, refusing any escape.
    fn open_subdir(dir_fd: &OwnedFd, name: &Path) -> Result<OwnedFd, Errno> {
        openat2(
            dir_fd,
            name,
            OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,
            Mode::empty(),
            ResolveFlags::BENEATH,
        )
    }

    pub(super) fn open_beneath(root: &Path, rel: &Path, intent: OpenIntent) -> Result<File, Errno> {
        let root_fd = open_dir(root)?;
        let (flags, mode) = match intent {
            OpenIntent::Read => (OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty()),
            OpenIntent::WriteTruncate => (
                OFlags::WRONLY | OFlags::CREATE | OFlags::TRUNC | OFlags::CLOEXEC,
                Mode::from_raw_mode(0o644),
            ),
        };
        let fd = openat2(&root_fd, rel, flags, mode, ResolveFlags::BENEATH)?;
        Ok(File::from(fd))
    }

    pub(super) fn create_dir_all_beneath(root: &Path, rel: &Path) -> Result<(), Errno> {
        let mut dir = open_dir(root)?;
        for comp in rel.components() {
            let name: &Path = match comp {
                Component::Normal(n) => Path::new(n),
                Component::CurDir => continue,
                // Absolute prefixes / `..` would be rejected by BENEATH anyway;
                // surface a clean error rather than attempting them.
                _ => return Err(Errno::INVAL),
            };
            match mkdirat(&dir, name, Mode::from_raw_mode(0o755)) {
                Ok(()) | Err(Errno::EXIST) => {},
                Err(e) => return Err(e),
            }
            dir = open_subdir(&dir, name)?;
        }
        Ok(())
    }

    pub(super) fn remove_file_beneath(root: &Path, rel: &Path) -> Result<(), Errno> {
        let root_fd = open_dir(root)?;
        let leaf = rel.file_name().ok_or(Errno::INVAL)?;
        let parent = rel.parent().unwrap_or_else(|| Path::new(""));
        let parent_fd = if parent.as_os_str().is_empty() {
            root_fd
        } else {
            open_subdir(&root_fd, parent)?
        };
        unlinkat(&parent_fd, Path::new(leaf), AtFlags::empty())
    }
}

/// Best-effort fallback used on non-Linux targets and pre-`openat2` kernels:
/// the lexical + canonical-ancestor containment check, then a plain `std::fs`
/// open by path. The TOCTOU window remains here, but the lexical guarantee does
/// not regress relative to the prior implementation.
///
/// One deliberate behavioral difference from the Linux path: because this leans
/// on `std::fs::canonicalize`, it *follows* an absolute symlink that resolves
/// back inside the root, whereas `RESOLVE_BENEATH` rejects every absolute
/// symlink outright. Both still refuse escapes — the fallback is simply more
/// permissive on that one in-tree edge case. Reconciling it would mean
/// hand-rolling per-component symlink inspection here, exactly the fragile
/// logic `openat2` exists to replace, so the mismatch is documented rather than
/// papered over.
mod fallback {
    use std::fs::{File, OpenOptions};
    use std::io;
    use std::path::{Path, PathBuf};

    use super::{OpenIntent, contain_within_canonical};

    fn validated(root: &Path, rel: &Path) -> io::Result<PathBuf> {
        let rel_str = rel
            .to_str()
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "non-UTF-8 path"))?;
        contain_within_canonical(root, rel_str)
            .map_err(|e| io::Error::new(io::ErrorKind::PermissionDenied, e.to_string()))
    }

    pub(super) fn open(root: &Path, rel: &Path, intent: OpenIntent) -> io::Result<File> {
        let path = validated(root, rel)?;
        match intent {
            OpenIntent::Read => File::open(&path),
            OpenIntent::WriteTruncate => OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&path),
        }
    }

    pub(super) fn create_dir_all(root: &Path, rel: &Path) -> io::Result<()> {
        let path = validated(root, rel)?;
        std::fs::create_dir_all(&path)
    }

    pub(super) fn remove_file(root: &Path, rel: &Path) -> io::Result<()> {
        let path = validated(root, rel)?;
        std::fs::remove_file(&path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rejects_parent_escape() {
        let root = std::env::temp_dir().join("mermaid_pathguard_root");
        assert!(contain_within(&root, "../escape").is_err());
    }

    #[test]
    fn rejects_absolute_outside_root() {
        let root = std::env::temp_dir().join("mermaid_pathguard_root2");
        #[cfg(unix)]
        assert!(contain_within(&root, "/etc/passwd").is_err());
        #[cfg(windows)]
        assert!(contain_within(&root, "C:\\Windows\\System32\\drivers\\etc\\hosts").is_err());
    }

    #[test]
    fn accepts_in_root_relative() {
        let root = std::env::temp_dir().join("mermaid_pathguard_root3");
        let p = contain_within(&root, "a/b.txt").unwrap();
        assert!(p.starts_with(normalize_lexical(&root)));
        assert!(p.ends_with("b.txt"));
    }

    #[test]
    fn collapses_interior_parent_within_root() {
        let root = std::env::temp_dir().join("mermaid_pathguard_root4");
        // `a/../b.txt` stays inside the root.
        let p = contain_within(&root, "a/../b.txt").unwrap();
        assert!(p.ends_with("b.txt"));
        assert!(p.starts_with(normalize_lexical(&root)));
    }
}

#[cfg(all(test, target_os = "linux"))]
mod confined_tests {
    use std::io::{Read, Write};

    use super::*;

    /// A throwaway directory unique to this test run + `tag` (tests share a PID).
    fn unique_dir(tag: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("mermaid_beneath_{tag}_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn create_write_read_roundtrip_stays_in_root() {
        let root = unique_dir("rw");
        create_dir_all_beneath(&root, Path::new("sub/inner")).unwrap();
        {
            let mut f = open_beneath(
                &root,
                Path::new("sub/inner/file.txt"),
                OpenIntent::WriteTruncate,
            )
            .unwrap();
            f.write_all(b"hello").unwrap();
        }
        // The bytes landed at the confined inode.
        assert_eq!(
            std::fs::read_to_string(root.join("sub/inner/file.txt")).unwrap(),
            "hello"
        );
        // And read back through the confined opener.
        let mut buf = String::new();
        open_beneath(&root, Path::new("sub/inner/file.txt"), OpenIntent::Read)
            .unwrap()
            .read_to_string(&mut buf)
            .unwrap();
        assert_eq!(buf, "hello");
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn open_beneath_refuses_write_through_escaping_symlink() {
        let root = unique_dir("escape_root");
        let outside = unique_dir("escape_outside");
        // Plant a symlink *inside* the root that redirects outside it — the
        // exact TOCTOU shape #77 is about.
        std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();

        let res = open_beneath(
            &root,
            Path::new("escape/evil.txt"),
            OpenIntent::WriteTruncate,
        );
        assert!(
            res.is_err(),
            "write through escaping symlink must be refused"
        );
        assert!(
            !outside.join("evil.txt").exists(),
            "nothing should have been written outside the root"
        );

        let _ = std::fs::remove_dir_all(&root);
        let _ = std::fs::remove_dir_all(&outside);
    }

    #[test]
    fn open_beneath_follows_in_tree_symlink() {
        // The crux of choosing RESOLVE_BENEATH over RESOLVE_NO_SYMLINKS: a
        // symlink that stays *inside* the root (the node_modules / monorepo
        // case) must still resolve. A relative in-tree link is followed; only
        // escapes are refused.
        let root = unique_dir("intree");
        std::fs::create_dir(root.join("real")).unwrap();
        // Relative target so resolution stays beneath the root.
        std::os::unix::fs::symlink("real", root.join("link")).unwrap();

        {
            let mut f =
                open_beneath(&root, Path::new("link/file.txt"), OpenIntent::WriteTruncate).unwrap();
            f.write_all(b"via-symlink").unwrap();
        }
        // The bytes landed in the real directory the in-tree link points at.
        assert_eq!(
            std::fs::read_to_string(root.join("real/file.txt")).unwrap(),
            "via-symlink"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn create_dir_all_beneath_refuses_escape() {
        let root = unique_dir("mkdir_root");
        let outside = unique_dir("mkdir_outside");
        std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();

        let res = create_dir_all_beneath(&root, Path::new("escape/newdir"));
        assert!(
            res.is_err(),
            "mkdir through escaping symlink must be refused"
        );
        assert!(!outside.join("newdir").exists());

        let _ = std::fs::remove_dir_all(&root);
        let _ = std::fs::remove_dir_all(&outside);
    }

    #[test]
    fn remove_file_beneath_deletes_in_root_and_refuses_escape() {
        let root = unique_dir("rm_root");
        {
            let mut f =
                open_beneath(&root, Path::new("gone.txt"), OpenIntent::WriteTruncate).unwrap();
            f.write_all(b"x").unwrap();
        }
        assert!(root.join("gone.txt").exists());
        remove_file_beneath(&root, Path::new("gone.txt")).unwrap();
        assert!(!root.join("gone.txt").exists());

        // A victim outside the root, reachable only via an escaping symlink, is
        // safe from a confined unlink.
        let outside = unique_dir("rm_outside");
        std::fs::write(outside.join("victim.txt"), b"keep").unwrap();
        std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();
        let res = remove_file_beneath(&root, Path::new("escape/victim.txt"));
        assert!(
            res.is_err(),
            "unlink through escaping symlink must be refused"
        );
        assert!(outside.join("victim.txt").exists());

        let _ = std::fs::remove_dir_all(&root);
        let _ = std::fs::remove_dir_all(&outside);
    }
}