zlayer-paths 0.14.0

Centralized filesystem path resolution for ZLayer
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Symlink-safe filesystem tree operations.
//!
//! Recursive `chmod`/`chown`/delete walkers and tar extraction routinely escape
//! a container rootfs through an absolute symlink. The standard one is
//! `var/run -> /run`: a naive walker that decides "is this a directory?" with
//! [`std::path::Path::is_dir`] (which dereferences symlinks) recurses *through*
//! the link and mutates the host's `/run` — most painfully `chmod`/`chown`ing
//! the host's `/run/sshd`, which makes `sshd` reject every new connection
//! (`fatal: /run/sshd must be owned by root and not group or world-writable.`).
//! The TCP handshake still completes, so it looks exactly like a firewall drop
//! while being a filesystem-permissions bug, and only a reboot (tmpfs `/run`
//! recreated clean) recovers it.
//!
//! Every operation here uses [`std::fs::symlink_metadata`] (`lstat`, which does
//! NOT follow symlinks) to classify a node before touching it, and never
//! recurses into a symlink. The two helpers used by the OCI unpacker
//! ([`materialize_real_parent`] and [`lremove_if_symlink`]) additionally make
//! sure a write never lands *through* an on-disk symlinked parent that points
//! outside the destination tree.
//!
//! Prefer these over hand-rolled `read_dir` + `is_dir()` walks. The footguns
//! they avoid: `std::fs::{set_permissions, metadata, canonicalize}`,
//! `nix::unistd::chown`, and `Path::{is_dir, is_file}` all dereference symlinks;
//! only `symlink_metadata`/`lstat` and `remove_file` (on the link itself) do not.

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

/// Walk `root` depth-first **without ever following a symlink**, invoking
/// `visit(path, metadata)` for every real file and directory (the `metadata`
/// is the `lstat` result, so `metadata.is_dir()` is the true on-disk type).
///
/// Symlinks are skipped entirely — neither visited nor traversed — so the walk
/// can never leave `root`'s subtree. Per-node `lstat`/`read_dir` failures are
/// logged and skipped (best-effort traversal); only an error returned by
/// `visit` aborts the walk and propagates.
///
/// # Errors
///
/// Returns the first error produced by `visit`.
pub fn walk_no_follow<F>(root: &Path, mut visit: F) -> io::Result<()>
where
    F: FnMut(&Path, &std::fs::Metadata) -> io::Result<()>,
{
    let mut stack = vec![root.to_path_buf()];
    while let Some(p) = stack.pop() {
        // lstat — never follow a symlink when deciding what `p` is.
        let md = match std::fs::symlink_metadata(&p) {
            Ok(md) => md,
            Err(e) => {
                tracing::debug!(path = %p.display(), error = %e, "lstat failed during safe walk");
                continue;
            }
        };
        if md.file_type().is_symlink() {
            // A symlink — even one pointing at a directory — is left entirely
            // alone so the walk can never reach outside `root`.
            continue;
        }
        visit(&p, &md)?;
        if md.is_dir() {
            match std::fs::read_dir(&p) {
                Ok(entries) => stack.extend(entries.flatten().map(|e| e.path())),
                Err(e) => {
                    tracing::debug!(path = %p.display(), error = %e, "read_dir failed during safe walk");
                }
            }
        }
    }
    Ok(())
}

/// `chgrp` every real entry under `path` to `gid` and set every real directory
/// to `dir_mode` (e.g. `0o2775` for setgid + group write), skipping symlinks.
///
/// Best-effort: per-node failures are logged, not propagated (matches the
/// daemon build-dir normalize semantics). The owner is left as-is; only the
/// group and directory mode change.
#[cfg(unix)]
pub fn chgrp_setgid_tree(path: &Path, gid: nix::unistd::Gid, dir_mode: u32) {
    use std::os::unix::fs::PermissionsExt;

    if let Err(e) = std::fs::create_dir_all(path) {
        tracing::debug!(path = %path.display(), error = %e, "could not create dir for chgrp_setgid_tree");
        return;
    }
    let _ = walk_no_follow(path, |p, md| {
        // `p` is a real file/dir here (symlinks are skipped by the walker), so
        // `chown` has nothing to dereference.
        if let Err(e) = nix::unistd::chown(p, None, Some(gid)) {
            tracing::debug!(path = %p.display(), error = %e, "chgrp failed during tree normalize");
        }
        if md.is_dir() {
            if let Err(e) = std::fs::set_permissions(p, std::fs::Permissions::from_mode(dir_mode)) {
                tracing::debug!(path = %p.display(), error = %e, "chmod failed during tree normalize");
            }
        }
        Ok(())
    });
}

/// Make every real directory under `root` writable+executable by the owner
/// (`0o700`) so a subsequent [`std::fs::remove_dir_all`] can delete a tree that
/// contains read-only directories (e.g. Fedora's `0o555` `ca-trust`), skipping
/// symlinks. Best-effort.
///
/// Call this immediately before `remove_dir_all(root)`.
#[cfg(unix)]
pub fn chmod_tree_writable(root: &Path) {
    use std::os::unix::fs::PermissionsExt;

    let _ = walk_no_follow(root, |p, md| {
        if md.is_dir() {
            if let Err(e) = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o700)) {
                tracing::debug!(path = %p.display(), error = %e, "chmod-writable failed");
            }
        }
        Ok(())
    });
}

/// Apply `mode` to every real **file** under `root` (directories are left
/// untouched — applying a file mode such as `0o644` to a directory would clear
/// its execute bit and make it non-traversable), skipping symlinks. Used for
/// build `COPY/ADD --chmod`.
///
/// # Errors
///
/// Returns the first `set_permissions` error.
#[cfg(unix)]
pub fn chmod_tree_files(root: &Path, mode: u32) -> io::Result<()> {
    use std::os::unix::fs::PermissionsExt;

    walk_no_follow(root, |p, md| {
        if md.is_file() {
            std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode))
        } else {
            Ok(())
        }
    })
}

/// `chown` every real file and directory under `root` to `uid`/`gid` (either may
/// be `None` to leave unchanged), skipping symlinks. Used for build
/// `COPY/ADD --chown`. A no-op when both are `None`.
///
/// # Errors
///
/// Returns the first `chown` error.
#[cfg(unix)]
pub fn chown_tree(root: &Path, uid: Option<u32>, gid: Option<u32>) -> io::Result<()> {
    if uid.is_none() && gid.is_none() {
        return Ok(());
    }
    let owner_uid = uid.map(nix::unistd::Uid::from_raw);
    let owner_gid = gid.map(nix::unistd::Gid::from_raw);
    walk_no_follow(root, |p, _md| {
        nix::unistd::chown(p, owner_uid, owner_gid)
            .map_err(|e| io::Error::other(format!("chown failed on {}: {e}", p.display())))
    })
}

/// Remove `path` without ever following a symlink: a symlink (or any non-dir)
/// is unlinked via [`std::fs::remove_file`] (which removes the link itself, not
/// its target); a real directory is removed with [`std::fs::remove_dir_all`]
/// (whose own top-level entry is `lstat`'d, so it will not traverse a symlink
/// either). A missing path is not an error.
///
/// This replaces the `if path.is_dir() { remove_dir_all } else { remove_file }`
/// idiom, whose `is_dir()` follows symlinks and so deletes through a link.
///
/// # Errors
///
/// Returns any underlying removal error other than "not found".
pub fn remove_path_no_follow(path: &Path) -> io::Result<()> {
    let md = match std::fs::symlink_metadata(path) {
        Ok(md) => md,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e),
    };
    let res = if md.is_dir() {
        std::fs::remove_dir_all(path)
    } else {
        // Regular file, symlink, socket, fifo, … — unlink the entry itself.
        std::fs::remove_file(path)
    };
    match res {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e),
    }
}

/// If `path` currently exists as a symlink, unlink it (so a following
/// `File::create`/`set_permissions`/`create_dir` lands on a fresh real entry
/// instead of writing through the link). No-op if `path` is absent or is not a
/// symlink.
///
/// # Errors
///
/// Returns the unlink error if removing the symlink fails.
pub fn lremove_if_symlink(path: &Path) -> io::Result<()> {
    match std::fs::symlink_metadata(path) {
        Ok(md) if md.file_type().is_symlink() => std::fs::remove_file(path),
        _ => Ok(()),
    }
}

/// Ensure every parent component of `full_path`, from `rootfs` down to
/// `full_path.parent()`, is a **real directory inside `rootfs`** — replacing any
/// component that is currently a symlink with a real directory — so a subsequent
/// write to `full_path` cannot be redirected outside `rootfs`.
///
/// This is the OCI-unpack defense: a layer may ship `var/run -> /run` and then a
/// later entry `var/run/sshd`; without this, `create_dir_all`/`File::create`
/// follow the link and write to the host's `/run`. Replacing a symlinked parent
/// with a directory is OCI-correct — a later layer is allowed to put a real
/// directory where an earlier layer had a symlink.
///
/// `full_path` must be `rootfs.join(<relative entry path>)`; if it does not lie
/// under `rootfs` this is a no-op (nothing outside `rootfs` is touched).
///
/// # Errors
///
/// Returns an error if a symlinked/foreign parent cannot be unlinked or a real
/// directory cannot be created.
pub fn materialize_real_parent(rootfs: &Path, full_path: &Path) -> io::Result<()> {
    let Some(parent) = full_path.parent() else {
        return Ok(());
    };
    // Only operate within rootfs; never touch anything above it.
    let Ok(rel) = parent.strip_prefix(rootfs) else {
        return Ok(());
    };

    let mut cur = rootfs.to_path_buf();
    for comp in rel.components() {
        // `rel` is relative and the entry path was already validated to contain
        // no `..`/absolute components, but match defensively and only descend
        // through normal components.
        let Component::Normal(name) = comp else {
            continue;
        };
        cur.push(name);
        match std::fs::symlink_metadata(&cur) {
            // A symlink parent would redirect the write outside rootfs — unlink
            // it and put a real directory in its place.
            Ok(md) if md.file_type().is_symlink() => {
                std::fs::remove_file(&cur)?;
                std::fs::create_dir(&cur)?;
            }
            // Already a real directory — good.
            Ok(md) if md.is_dir() => {}
            // A non-dir file sits where we need a directory — replace it.
            Ok(_) => {
                std::fs::remove_file(&cur)?;
                std::fs::create_dir(&cur)?;
            }
            // Does not exist yet — create it.
            Err(_) => {
                std::fs::create_dir(&cur)?;
            }
        }
    }
    Ok(())
}

/// Compute a rootfs-confined **relative** target for an **absolute** symlink.
///
/// `link_rel` is the symlink's path *relative to the rootfs root* (e.g.
/// `var/run` for a link at `<rootfs>/var/run`); `abs_target` is its current
/// absolute target (e.g. `/run`). Returns the equivalent relative target (e.g.
/// `../run`) that resolves to the **same** location *inside* the rootfs —
/// post-pivot the container's `/` IS the rootfs, so `/run` and `../run`
/// (from `/var`) are identical — but can never escape the rootfs for a
/// host-context operation that resolves the link before pivot_root.
///
/// Returns `None` when `abs_target` is not absolute (nothing to rewrite) or
/// `link_rel` has no parent.
#[must_use]
pub fn relativize_abs_symlink(link_rel: &Path, abs_target: &Path) -> Option<PathBuf> {
    if !abs_target.is_absolute() {
        return None;
    }
    // Depth of the directory CONTAINING the link, in normal components from the
    // rootfs root (`var/run` -> parent `var` -> depth 1 -> one `..`).
    let parent = link_rel.parent()?;
    let depth = parent
        .components()
        .filter(|c| matches!(c, Component::Normal(_)))
        .count();
    // The absolute target without its leading `/` IS the path relative to the
    // rootfs root.
    let target_rel: PathBuf = abs_target
        .components()
        .filter_map(|c| match c {
            Component::Normal(n) => Some(n),
            _ => None,
        })
        .collect();
    let mut out = PathBuf::new();
    for _ in 0..depth {
        out.push("..");
    }
    if target_rel.as_os_str().is_empty() {
        // Target was `/` (the rootfs root). A link directly under rootfs maps
        // to `.`; deeper links already point at the root via the `..` prefix.
        if out.as_os_str().is_empty() {
            out.push(".");
        }
    } else {
        out.push(&target_rel);
    }
    Some(out)
}

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

    /// Build `<base>/rootfs/var/run -> <base>/host_run` (an absolute escaping
    /// symlink, like a container's `var/run -> /run`) plus a sentinel file
    /// `<base>/host_run/sshd`. Returns (rootfs, host_run, sentinel).
    fn rootfs_with_escaping_symlink(base: &Path) -> (PathBuf, PathBuf, PathBuf) {
        let rootfs = base.join("rootfs");
        let host_run = base.join("host_run");
        std::fs::create_dir_all(rootfs.join("var")).unwrap();
        std::fs::create_dir_all(&host_run).unwrap();
        let sentinel = host_run.join("sshd");
        std::fs::write(&sentinel, b"i am the host sshd runtime dir contents").unwrap();
        #[cfg(unix)]
        std::os::unix::fs::symlink(&host_run, rootfs.join("var").join("run")).unwrap();
        (rootfs, host_run, sentinel)
    }

    #[cfg(unix)]
    #[test]
    fn chmod_tree_files_does_not_follow_symlink_out_of_root() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let (rootfs, host_run, sentinel) = rootfs_with_escaping_symlink(tmp.path());
        // Put a real file inside the rootfs so we know chmod actually ran.
        let inside = rootfs.join("var").join("inside.txt");
        std::fs::write(&inside, b"x").unwrap();
        let before = std::fs::metadata(&sentinel).unwrap().permissions().mode() & 0o777;

        chmod_tree_files(&rootfs, 0o600).unwrap();

        // The host sentinel (reachable only through the var/run symlink) is untouched.
        let after = std::fs::metadata(&sentinel).unwrap().permissions().mode() & 0o777;
        assert_eq!(before, after, "sentinel host file mode must be unchanged");
        // The in-rootfs file WAS chmod'd.
        assert_eq!(
            std::fs::metadata(&inside).unwrap().permissions().mode() & 0o777,
            0o600
        );
        let _ = host_run;
    }

    #[cfg(unix)]
    #[test]
    fn walk_skips_symlinked_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let (rootfs, _host_run, _sentinel) = rootfs_with_escaping_symlink(tmp.path());
        let mut visited = Vec::new();
        walk_no_follow(&rootfs, |p, _md| {
            visited.push(p.to_path_buf());
            Ok(())
        })
        .unwrap();
        // The symlink `var/run` itself is never visited, and nothing under the
        // host_run target is visited.
        assert!(visited.iter().any(|p| p.ends_with("var")));
        assert!(
            !visited.iter().any(|p| p.ends_with("var/run")),
            "symlink must not be visited"
        );
        assert!(
            !visited.iter().any(|p| p.ends_with("sshd")),
            "must not cross the symlink into the host dir"
        );
    }

    #[test]
    fn materialize_real_parent_replaces_escaping_symlink() {
        let tmp = tempfile::tempdir().unwrap();
        let (rootfs, _host_run, sentinel) = rootfs_with_escaping_symlink(tmp.path());

        // A later entry wants to write rootfs/var/run/sshd. Materialize parents.
        let target = rootfs.join("var").join("run").join("sshd");
        materialize_real_parent(&rootfs, &target).unwrap();

        // var/run is now a REAL directory inside rootfs, not a symlink.
        let md = std::fs::symlink_metadata(rootfs.join("var").join("run")).unwrap();
        assert!(md.is_dir(), "var/run must be a real dir now");
        assert!(
            !md.file_type().is_symlink(),
            "var/run must not be a symlink"
        );

        // Writing the target now stays inside rootfs; the host sentinel is intact.
        std::fs::write(&target, b"contained").unwrap();
        assert_eq!(
            std::fs::read(&sentinel).unwrap(),
            b"i am the host sshd runtime dir contents",
            "host sentinel must be untouched"
        );
        assert!(target.exists());
    }

    #[test]
    fn remove_path_no_follow_unlinks_symlink_not_target() {
        let tmp = tempfile::tempdir().unwrap();
        let (rootfs, _host_run, sentinel) = rootfs_with_escaping_symlink(tmp.path());
        let link = rootfs.join("var").join("run");

        remove_path_no_follow(&link).unwrap();

        assert!(
            std::fs::symlink_metadata(&link).is_err(),
            "the symlink itself must be gone"
        );
        assert!(
            sentinel.exists(),
            "the symlink target (host file) must NOT be deleted"
        );
    }

    #[test]
    fn lremove_if_symlink_only_removes_links() {
        let tmp = tempfile::tempdir().unwrap();
        let real = tmp.path().join("real.txt");
        std::fs::write(&real, b"keep").unwrap();
        lremove_if_symlink(&real).unwrap();
        assert!(real.exists(), "a real file must not be removed");

        #[cfg(unix)]
        {
            let link = tmp.path().join("link");
            std::os::unix::fs::symlink(&real, &link).unwrap();
            lremove_if_symlink(&link).unwrap();
            assert!(std::fs::symlink_metadata(&link).is_err(), "link removed");
            assert!(real.exists(), "link target preserved");
        }
    }

    #[test]
    fn relativize_abs_symlink_confines_targets() {
        // The canonical escape: var/run -> /run becomes var/run -> ../run.
        assert_eq!(
            relativize_abs_symlink(Path::new("var/run"), Path::new("/run")),
            Some(PathBuf::from("../run"))
        );
        // Deeper link: var/lock -> /run/lock => ../run/lock.
        assert_eq!(
            relativize_abs_symlink(Path::new("var/lock"), Path::new("/run/lock")),
            Some(PathBuf::from("../run/lock"))
        );
        // Top-level link (directly under rootfs): bin -> /usr/bin => usr/bin.
        assert_eq!(
            relativize_abs_symlink(Path::new("bin"), Path::new("/usr/bin")),
            Some(PathBuf::from("usr/bin"))
        );
        // Two-deep: a/b/c -> /x => ../../x.
        assert_eq!(
            relativize_abs_symlink(Path::new("a/b/c"), Path::new("/x")),
            Some(PathBuf::from("../../x"))
        );
        // Target is the rootfs root.
        assert_eq!(
            relativize_abs_symlink(Path::new("here"), Path::new("/")),
            Some(PathBuf::from("."))
        );
        assert_eq!(
            relativize_abs_symlink(Path::new("a/here"), Path::new("/")),
            Some(PathBuf::from(".."))
        );
        // Already relative: nothing to do.
        assert_eq!(
            relativize_abs_symlink(Path::new("var/run"), Path::new("../run")),
            None
        );
    }
}