noyalib 0.0.55

A pure Rust YAML library with zero unsafe code and full serde integration
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 Noyalib. All rights reserved.

//! Capability-rooted filesystem support for `!include`.

use super::{IncludeRequest, IncludeResolver, InputSource, split_fragment};
use crate::error::{Error, Result};
use crate::prelude::*;

/// How [`SafeFileResolver`] handles symbolic links it
/// encounters while resolving a path.
///
/// # Examples
///
/// ```
/// use noyalib::include::SymlinkPolicy;
/// assert_eq!(SymlinkPolicy::default(), SymlinkPolicy::FollowWithinRoot);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum SymlinkPolicy {
    /// Follow symlinks that resolve to a path still inside the
    /// resolver's root directory. Reject anything pointing
    /// outside. Default.
    #[default]
    FollowWithinRoot,
    /// Reject all symbolic links regardless of target. Strictest
    /// posture; appropriate for untrusted document graphs.
    Reject,
}

/// Filesystem-backed [`IncludeResolver`] with root-dir
/// sandboxing.
///
/// Behind the `include_fs` Cargo feature (which implies
/// `include` + `std`).
///
/// # Sandboxing
///
/// On Unix, the root is opened once as a directory capability. Every
/// subsequent file open is relative to that handle, so renaming or
/// replacing the path used to construct the resolver cannot redirect
/// later reads. Targets canonicalise to a root-relative path and then
/// open every component without following symlinks. Windows retains
/// canonical root checks. Path-traversal attempts (`../../etc/passwd`)
/// and symlink targets outside the root are rejected before content is
/// read.
///
/// # What is read
///
/// Only regular files are read. A directory, FIFO, socket or device is
/// refused, and on Unix the file is opened non-blocking so that a FIFO
/// planted under the root cannot stall the parse before it is refused.
/// At most [`IncludeRequest::max_bytes`] plus one bytes are read, so an
/// oversized file costs no more memory than the budget it exceeds.
///
/// Paths in error messages and [`InputSource::name`] are relative to
/// the root and use `/` separators on every platform: a document author
/// learns nothing about where the root sits on the host, and a source
/// has the same name on Windows as elsewhere.
///
/// # Symlinks
///
/// Controlled by [`SymlinkPolicy`]. On Unix, the default
/// [`SymlinkPolicy::FollowWithinRoot`] resolves symlinks through
/// the directory capability. [`SymlinkPolicy::Reject`] opens each
/// directory component and the final file without following
/// symlinks, avoiding a metadata-then-open race. Windows enforces
/// the same policies through canonical path and metadata checks; there
/// the path is canonicalised and then opened by name, so a link swapped
/// in between those two steps is not detected. The regular-file check
/// runs on the opened handle on every platform, which also refuses
/// Windows device names such as `CON` or `NUL`. Hard links are not
/// symlinks and are followed on every platform: a hard link inside the
/// root to a file outside it is read.
///
/// # Examples
///
/// ```no_run
/// use noyalib::include::{SafeFileResolver, SymlinkPolicy};
///
/// let resolver = SafeFileResolver::new("/srv/configs")
///     .symlink_policy(SymlinkPolicy::Reject)
///     .into_resolver();
/// let cfg = noyalib::ParserConfig::new().include_resolver(resolver);
/// # let _ = cfg;
/// ```
#[derive(Debug, Clone)]
pub struct SafeFileResolver {
    symlink_policy: SymlinkPolicy,
    capability: Arc<RootCapability>,
}

#[derive(Debug)]
enum RootCapability {
    #[cfg(unix)]
    Ready {
        dir: std::fs::File,
        canonical_root: std::path::PathBuf,
    },
    #[cfg(not(unix))]
    Ready {
        canonical_root: std::path::PathBuf,
    },
    Failed(String),
}

impl SafeFileResolver {
    /// Construct a resolver rooted at `root`. All resolved paths
    /// must canonicalise to a descendant of `root`.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::include::SafeFileResolver;
    /// let r = SafeFileResolver::new("/srv/configs");
    /// let _ = r;
    /// ```
    ///
    /// The root is opened during construction. Because this constructor
    /// retains its historical infallible signature, an open failure is
    /// stored and returned when the resolver is first invoked.
    #[must_use]
    pub fn new(root: impl Into<std::path::PathBuf>) -> Self {
        let root = root.into();
        let capability = match open_root_capability(&root) {
            Ok(capability) => capability,
            Err(error) => RootCapability::Failed(error.to_string()),
        };
        Self {
            symlink_policy: SymlinkPolicy::default(),
            capability: Arc::new(capability),
        }
    }

    /// Set the [`SymlinkPolicy`].
    #[must_use]
    pub fn symlink_policy(mut self, policy: SymlinkPolicy) -> Self {
        self.symlink_policy = policy;
        self
    }

    /// Convert this configuration into a boxed [`IncludeResolver`]
    /// suitable for [`crate::ParserConfig::include_resolver`].
    #[must_use]
    pub fn into_resolver(self) -> IncludeResolver {
        let this = self;
        IncludeResolver::new(move |req: IncludeRequest<'_>| this.resolve(req))
    }

    fn resolve(&self, req: IncludeRequest<'_>) -> Result<InputSource> {
        // Strip the optional `#anchor` fragment. The loader handles anchor
        // selection after parse, so the resolver only needs the path portion.
        let (path_part, _fragment) = split_fragment(req.spec);
        let relative = normalize_relative_path(path_part).map_err(|message| {
            Error::Custom(format!("include resolver: `{path_part}` {message}"))
        })?;
        let capability = self.root_capability()?;
        let (file, name) =
            open_from_root(capability, &relative, self.symlink_policy).map_err(|error| {
                Error::Custom(format!(
                    "include resolver: `{}` escapes sandbox root, contains a rejected symlink, or cannot read securely: {error}",
                    slash_path(&relative)
                ))
            })?;
        let bytes = read_regular_file(file, req.max_bytes).map_err(|error| {
            Error::Custom(format!(
                "include resolver: cannot read `{}`: {error}",
                slash_path(&name)
            ))
        })?;
        Ok(InputSource::new(slash_path(&name), bytes))
    }

    fn root_capability(&self) -> Result<&RootCapability> {
        match self.capability.as_ref() {
            ready @ RootCapability::Ready { .. } => Ok(ready),
            RootCapability::Failed(error) => Err(Error::Custom(format!(
                "include resolver: cannot open root: {error}"
            ))),
        }
    }
}

/// Read `file` if it is a regular file, stopping one byte past
/// `max_bytes` so the caller's budget check sees the overrun without
/// the whole file being buffered.
fn read_regular_file(file: std::fs::File, max_bytes: usize) -> std::io::Result<String> {
    use std::io::Read as _;

    if !file.metadata()?.is_file() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "not a regular file",
        ));
    }
    let limit = u64::try_from(max_bytes)
        .unwrap_or(u64::MAX)
        .saturating_add(1);
    let mut bytes = String::new();
    let _read = file.take(limit).read_to_string(&mut bytes)?;
    Ok(bytes)
}

/// A root-relative path written with `/` between its components, so
/// error messages and source names read the same on every platform.
fn slash_path(path: &std::path::Path) -> String {
    let parts: Vec<_> = path
        .components()
        .map(|c| c.as_os_str().to_string_lossy())
        .collect();
    parts.join("/")
}

fn normalize_relative_path(path: &str) -> core::result::Result<std::path::PathBuf, &'static str> {
    use std::path::Component;

    let mut normalized = std::path::PathBuf::new();
    for component in std::path::Path::new(path).components() {
        match component {
            Component::Prefix(_) | Component::RootDir => {
                return Err("must be relative to the root");
            }
            Component::CurDir => {}
            Component::ParentDir => {
                if !normalized.pop() {
                    return Err("escapes sandbox root");
                }
            }
            Component::Normal(part) => normalized.push(part),
        }
    }
    Ok(normalized)
}

#[cfg(unix)]
fn open_root_capability(root: &std::path::Path) -> std::io::Result<RootCapability> {
    use rustix::fs::{Mode, OFlags};

    let fd = rustix::fs::open(
        root,
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
    )?;
    let dir = std::fs::File::from(fd);
    #[cfg(target_vendor = "apple")]
    let canonical_root = {
        use std::os::unix::ffi::OsStringExt as _;

        let path = rustix::fs::getpath(&dir)?;
        std::path::PathBuf::from(std::ffi::OsString::from_vec(path.into_bytes()))
    };
    #[cfg(not(target_vendor = "apple"))]
    let canonical_root = std::fs::canonicalize(root)?;

    Ok(RootCapability::Ready {
        dir,
        canonical_root,
    })
}

#[cfg(not(unix))]
fn open_root_capability(root: &std::path::Path) -> std::io::Result<RootCapability> {
    Ok(RootCapability::Ready {
        canonical_root: std::fs::canonicalize(root)?,
    })
}

#[cfg(unix)]
fn open_from_root(
    capability: &RootCapability,
    relative: &std::path::Path,
    policy: SymlinkPolicy,
) -> std::io::Result<(std::fs::File, std::path::PathBuf)> {
    let RootCapability::Ready {
        dir,
        canonical_root,
    } = capability
    else {
        unreachable!("failed root capabilities are rejected before open")
    };
    let active_root = current_root_path(dir).unwrap_or_else(|_| canonical_root.clone());
    let open_path = if policy == SymlinkPolicy::FollowWithinRoot {
        let canonical = std::fs::canonicalize(active_root.join(relative))?;
        canonical
            .strip_prefix(&active_root)
            .map_err(|_| {
                std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "resolved path escapes sandbox root",
                )
            })?
            .to_path_buf()
    } else {
        relative.to_path_buf()
    };
    let file = open_relative_nofollow(dir, &open_path)?;
    // The root-relative path is the source's identity: canonical within
    // the root (symlinks resolved, or rejected), so cycle detection
    // still sees one name per file, and free of the host's layout.
    Ok((file, open_path))
}

#[cfg(all(unix, target_vendor = "apple"))]
fn current_root_path(root: &std::fs::File) -> std::io::Result<std::path::PathBuf> {
    use std::os::unix::ffi::OsStringExt as _;

    let path = rustix::fs::getpath(root)?;
    Ok(std::path::PathBuf::from(std::ffi::OsString::from_vec(
        path.into_bytes(),
    )))
}

#[cfg(all(unix, any(target_os = "linux", target_os = "android")))]
fn current_root_path(root: &std::fs::File) -> std::io::Result<std::path::PathBuf> {
    use std::os::fd::AsRawFd as _;

    std::fs::read_link(format!("/proc/self/fd/{}", root.as_raw_fd()))
}

#[cfg(all(
    unix,
    not(any(target_vendor = "apple", target_os = "linux", target_os = "android"))
))]
fn current_root_path(_root: &std::fs::File) -> std::io::Result<std::path::PathBuf> {
    Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "the target cannot recover a path from a directory handle",
    ))
}

#[cfg(not(unix))]
fn open_from_root(
    capability: &RootCapability,
    relative: &std::path::Path,
    policy: SymlinkPolicy,
) -> std::io::Result<(std::fs::File, std::path::PathBuf)> {
    let RootCapability::Ready { canonical_root } = capability else {
        unreachable!("failed root capabilities are rejected before open")
    };
    let canonical = std::fs::canonicalize(canonical_root.join(relative))?;
    let Ok(beneath) = canonical.strip_prefix(canonical_root) else {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "resolved path escapes sandbox root",
        ));
    };
    if policy == SymlinkPolicy::Reject && path_contains_symlink(canonical_root, relative)? {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "symlink rejected by policy",
        ));
    }
    Ok((std::fs::File::open(&canonical)?, beneath.to_path_buf()))
}

#[cfg(unix)]
fn open_relative_nofollow(
    root: &std::fs::File,
    relative: &std::path::Path,
) -> std::io::Result<std::fs::File> {
    use rustix::fs::{Mode, OFlags};

    let file_name = relative.file_name().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "include path names no file",
        )
    })?;
    let mut parent = rustix::fs::openat(
        root,
        ".",
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
        Mode::empty(),
    )?;
    if let Some(ancestors) = relative.parent() {
        for component in ancestors.components() {
            parent = rustix::fs::openat(
                &parent,
                component.as_os_str(),
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
                Mode::empty(),
            )?;
        }
    }
    // `NONBLOCK`: opening a FIFO for reading otherwise waits for a
    // writer. The regular-file check after the open refuses it; for a
    // regular file the flag has no effect on reads.
    let fd = rustix::fs::openat(
        &parent,
        file_name,
        OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC | OFlags::NONBLOCK,
        Mode::empty(),
    )?;
    Ok(std::fs::File::from(fd))
}

#[cfg(not(unix))]
fn path_contains_symlink(
    root: &std::path::Path,
    relative: &std::path::Path,
) -> std::io::Result<bool> {
    let mut candidate = root.to_path_buf();
    for component in relative.components() {
        candidate.push(component.as_os_str());
        if std::fs::symlink_metadata(&candidate)?
            .file_type()
            .is_symlink()
        {
            return Ok(true);
        }
    }
    Ok(false)
}

#[cfg(test)]
mod tests {
    use super::slash_path;
    use std::path::Path;

    #[test]
    fn source_names_use_forward_slashes_on_every_platform() {
        // `join` writes the platform separator (`\` on Windows); the
        // name a document author sees must not depend on it.
        let nested = Path::new("sub").join("deeper").join("a.yaml");
        assert_eq!(slash_path(&nested), "sub/deeper/a.yaml");
        assert_eq!(slash_path(Path::new("a.yaml")), "a.yaml");
    }
}