simdutf8-cli 0.1.6

SIMD-accelerated UTF-8 validation CLI built on the simdutf8 crate, with hardened path handling.
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2025,2026 ndaal Gesellschaft für Sicherheit in der Informationstechnik mbH & Co KG, Cologne
// SPDX-FileCopyrightText: Author: Pierre Gronau <Pierre.Gronau@ndaal.eu>

//! Hardened file access for untrusted path arguments.
//!
//! A CLI that opens arbitrary user-supplied paths must defend against a number
//! of classic attacks. This module centralises that policy so the rest of the
//! program never touches the filesystem directly:
//!
//! * **Path traversal** — when a base directory is configured, a `..` component
//!   is rejected lexically *and* the fully resolved path is verified to stay
//!   inside the base directory.
//! * **Symlink escapes / TOCTOU** — paths are [canonicalized](std::fs::canonicalize)
//!   (resolving symlinks and `..`) before the containment check, and symlinks
//!   can be denied outright. The opened file handle's own metadata is then
//!   re-checked (`fstat` on the descriptor) so the type/size decision is made on
//!   the object we actually opened, not on a name that may have been swapped.
//! * **Non-regular files** — directories, devices, FIFOs and sockets are
//!   rejected; only regular files are accepted.
//! * **Resource exhaustion** — reads are hard-capped at a configurable byte
//!   limit, independent of the size the filesystem metadata claims.
//!
//! The entry points are [`PathPolicy::open`] / [`PathPolicy::read`] for files on
//! disk, [`read_capped`] for arbitrary readers such as standard input,
//! [`write_in_dir`] for capability-scoped writes (via `cap-std`), and the
//! lexical [`safe_join`] primitive for confining attacker-influenced relative
//! paths to a base directory.

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

use cap_std::ambient_authority;
use cap_std::fs::Dir;

/// Default upper bound on the number of bytes read from a single input (64 MiB).
pub const DEFAULT_MAX_FILE_SIZE: u64 = 64 * 1024 * 1024;

/// Errors that can occur while securely resolving and opening an input path.
#[derive(Debug, thiserror::Error)]
pub enum PathSecurityError {
    /// The supplied path was empty.
    #[error("input path is empty")]
    EmptyPath,

    /// The supplied path contained an interior NUL byte.
    #[error("input path contains an interior NUL byte")]
    InteriorNul,

    /// A `..` component was present while a base directory was configured.
    #[error("input path contains a '..' component, which is not allowed with --base-dir: {}", .0.display())]
    ParentTraversal(PathBuf),

    /// The resolved path lay outside the configured base directory.
    #[error("resolved path {} escapes the permitted base directory {}", .path.display(), .base.display())]
    OutsideBase {
        /// The fully resolved (canonical) path that was rejected.
        path: PathBuf,
        /// The configured base directory (canonical).
        base: PathBuf,
    },

    /// A symbolic link was encountered while symlinks were disallowed.
    #[error("symbolic links are not permitted: {}", .0.display())]
    SymlinkDenied(PathBuf),

    /// The path resolved to something other than a regular file.
    #[error("not a regular file: {}", .0.display())]
    NotRegularFile(PathBuf),

    /// The input exceeded the configured byte limit.
    #[error("input is too large: {size} bytes exceeds the {limit} byte limit")]
    TooLarge {
        /// Observed size in bytes (at least `limit + 1` for streamed inputs).
        size: u64,
        /// The configured limit in bytes.
        limit: u64,
    },

    /// An underlying I/O error occurred while accessing the path.
    #[error("failed to access {}: {source}", .path.display())]
    Io {
        /// The path that was being accessed.
        path: PathBuf,
        /// The underlying I/O error.
        #[source]
        source: std::io::Error,
    },
}

/// A successfully opened, validated input file.
#[derive(Debug)]
pub struct OpenedFile {
    /// The open file handle (already confirmed to be a regular file).
    pub file: File,
    /// The fully resolved (canonical) path of the file.
    pub path: PathBuf,
    /// The size in bytes as reported by the file handle's metadata.
    pub size: u64,
}

/// Policy controlling how input paths are resolved and opened.
///
/// Construct with [`PathPolicy::new`] (or [`Default`]) and refine with the
/// builder-style methods.
#[derive(Clone, Debug)]
pub struct PathPolicy {
    base_dir: Option<PathBuf>,
    allow_symlinks: bool,
    max_file_size: u64,
}

impl Default for PathPolicy {
    fn default() -> Self {
        Self::new()
    }
}

impl PathPolicy {
    /// Create a policy with safe defaults: no base-directory confinement,
    /// symlinks allowed (but resolved and re-checked), and a
    /// [`DEFAULT_MAX_FILE_SIZE`] byte cap.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            base_dir: None,
            allow_symlinks: true,
            max_file_size: DEFAULT_MAX_FILE_SIZE,
        }
    }

    /// Confine all inputs to `base`: resolved paths must stay within it.
    #[must_use]
    pub fn base_dir(mut self, base: impl Into<PathBuf>) -> Self {
        self.base_dir = Some(base.into());
        self
    }

    /// Allow (`true`, the default) or deny (`false`) symbolic links.
    #[must_use]
    pub const fn allow_symlinks(mut self, allow: bool) -> Self {
        self.allow_symlinks = allow;
        self
    }

    /// Set the maximum number of bytes that may be read from a single input.
    #[must_use]
    pub const fn max_file_size(mut self, limit: u64) -> Self {
        self.max_file_size = limit;
        self
    }

    /// The configured byte limit.
    #[must_use]
    pub const fn limit(&self) -> u64 {
        self.max_file_size
    }

    /// Resolve, validate and open `requested`, returning an [`OpenedFile`].
    ///
    /// # Errors
    ///
    /// Returns a [`PathSecurityError`] if the path is empty, contains an
    /// interior NUL, traverses outside the configured base directory, is a
    /// disallowed symlink, is not a regular file, exceeds the size limit, or
    /// cannot be accessed.
    pub fn open(&self, requested: &Path) -> Result<OpenedFile, PathSecurityError> {
        let canonical = self.resolve_path(requested)?;

        // Open the canonical path, then re-derive type and size from the open
        // descriptor itself (fstat) so the decision is made on the object we hold
        // open rather than on a name that could have changed (TOCTOU mitigation).
        let file = File::open(&canonical).map_err(|source| PathSecurityError::Io {
            path: canonical.clone(),
            source,
        })?;
        let meta = file.metadata().map_err(|source| PathSecurityError::Io {
            path: canonical.clone(),
            source,
        })?;
        if !meta.is_file() {
            return Err(PathSecurityError::NotRegularFile(canonical));
        }

        // Enforce the size limit (the subsequent read is hard-capped too).
        let size = meta.len();
        if size > self.max_file_size {
            return Err(PathSecurityError::TooLarge {
                size,
                limit: self.max_file_size,
            });
        }

        Ok(OpenedFile {
            file,
            path: canonical,
            size,
        })
    }

    /// Validate `requested` and resolve it to a canonical path that is confined
    /// to the configured base directory (if any). Performs no file open.
    ///
    /// # Errors
    ///
    /// Returns a [`PathSecurityError`] for an empty/NUL path, a `..` traversal,
    /// a disallowed symlink, a path escaping the base directory, or I/O failure.
    fn resolve_path(&self, requested: &Path) -> Result<PathBuf, PathSecurityError> {
        // 1. Reject an empty path outright.
        if requested.as_os_str().is_empty() {
            return Err(PathSecurityError::EmptyPath);
        }

        // 2. Reject interior NUL bytes before touching the filesystem.
        if requested.as_os_str().as_encoded_bytes().contains(&0) {
            return Err(PathSecurityError::InteriorNul);
        }

        // 3. With a base directory, reject `..` lexically as defence in depth
        //    (the canonical containment check below is the authoritative one).
        if self.base_dir.is_some()
            && requested
                .components()
                .any(|component| matches!(component, Component::ParentDir))
        {
            return Err(PathSecurityError::ParentTraversal(requested.to_path_buf()));
        }

        // 4. If symlinks are disallowed, reject a symlinked final component.
        if !self.allow_symlinks {
            let meta =
                std::fs::symlink_metadata(requested).map_err(|source| PathSecurityError::Io {
                    path: requested.to_path_buf(),
                    source,
                })?;
            if meta.file_type().is_symlink() {
                return Err(PathSecurityError::SymlinkDenied(requested.to_path_buf()));
            }
        }

        // 5. Canonicalize: resolves `.`/`..` and every symlink, yielding an
        //    absolute path to the real object on disk.
        let canonical = requested
            .canonicalize()
            .map_err(|source| PathSecurityError::Io {
                path: requested.to_path_buf(),
                source,
            })?;

        // 6. Containment: the resolved path must live inside the resolved base.
        if let Some(base) = &self.base_dir {
            let canonical_base = base
                .canonicalize()
                .map_err(|source| PathSecurityError::Io {
                    path: base.clone(),
                    source,
                })?;
            if !canonical.starts_with(&canonical_base) {
                return Err(PathSecurityError::OutsideBase {
                    path: canonical,
                    base: canonical_base,
                });
            }
        }

        Ok(canonical)
    }

    /// Open `requested` and read its contents, hard-capped at the byte limit.
    ///
    /// # Errors
    ///
    /// As for [`PathPolicy::open`], plus [`PathSecurityError::TooLarge`] if the
    /// file streams more than the configured limit.
    pub fn read(&self, requested: &Path) -> Result<Vec<u8>, PathSecurityError> {
        let OpenedFile { file, path, .. } = self.open(requested)?;
        read_capped(file, self.max_file_size).map_err(move |error| match error {
            // Replace the placeholder stream path with the real file path.
            PathSecurityError::Io { source, .. } => PathSecurityError::Io { path, source },
            other => other,
        })
    }
}

/// Read at most `limit` bytes from `reader`, erroring if more are available.
///
/// This bounds memory use for streamed inputs (e.g. standard input) where no
/// size is known in advance.
///
/// # Errors
///
/// Returns [`PathSecurityError::TooLarge`] if `reader` yields more than `limit`
/// bytes, or [`PathSecurityError::Io`] on an underlying read error.
pub fn read_capped<R: Read>(reader: R, limit: u64) -> Result<Vec<u8>, PathSecurityError> {
    // Read at most `limit + 1` bytes: the extra byte lets us detect overflow
    // without trusting any externally reported size.
    let mut limited = reader.take(limit.saturating_add(1));
    let mut buf = Vec::new();
    limited
        .read_to_end(&mut buf)
        .map_err(|source| PathSecurityError::Io {
            path: PathBuf::from("<stream>"),
            source,
        })?;

    let len = u64::try_from(buf.len()).unwrap_or(u64::MAX);
    if len > limit {
        return Err(PathSecurityError::TooLarge { size: len, limit });
    }
    Ok(buf)
}

/// Write `bytes` to a file named `name` inside the directory `dir`, using a
/// capability-scoped [`cap_std::fs::Dir`] handle (see `skills/rust-path-security.md`).
///
/// `name` must be a single relative file name; `cap-std` rejects any `..`,
/// absolute path, or symlink that would escape `dir` at the syscall layer, so a
/// crafted report file name cannot redirect the write outside `dir`. This is the
/// one place ambient authority crosses into the program for writes.
///
/// # Errors
///
/// Returns [`PathSecurityError::Io`] if `dir` cannot be opened or the file
/// cannot be created/written.
pub fn write_in_dir(dir: &Path, name: &str, bytes: &[u8]) -> Result<(), PathSecurityError> {
    let handle = Dir::open_ambient_dir(dir, ambient_authority()).map_err(|source| {
        PathSecurityError::Io {
            path: dir.to_path_buf(),
            source,
        }
    })?;
    let mut file = handle
        .create(name)
        .map_err(|source| PathSecurityError::Io {
            path: dir.join(name),
            source,
        })?;
    file.write_all(bytes)
        .map_err(|source| PathSecurityError::Io {
            path: dir.join(name),
            source,
        })?;
    Ok(())
}

/// Lexically join a relative, attacker-influenced `candidate` onto `base`,
/// returning `None` if the candidate would escape `base`.
///
/// This is a *string-level* primitive (see `skills/rust-path-security.md`): it
/// performs no filesystem access and does not resolve symlinks — it is the
/// auditable companion to the syscall-level confinement enforced by
/// [`PathPolicy`] / [`cap_std`]. A candidate is rejected when it:
///
/// * contains an interior NUL byte;
/// * is absolute or carries a path prefix (e.g. a Windows drive / UNC); or
/// * contains a `..` that pops above `base` (balanced `a/../b` is fine).
///
/// On success the returned path is guaranteed to start with `base` and to
/// contain no `..` component.
#[must_use]
pub fn safe_join(base: &Path, candidate: &str) -> Option<PathBuf> {
    if candidate.as_bytes().contains(&0) {
        return None;
    }

    let mut stack: Vec<std::ffi::OsString> = Vec::new();
    for component in Path::new(candidate).components() {
        match component {
            Component::CurDir => {},
            Component::Normal(segment) => stack.push(segment.to_os_string()),
            Component::ParentDir => {
                // A `..` that cannot be balanced by a previously pushed segment
                // would escape `base`.
                stack.pop()?;
            },
            Component::RootDir | Component::Prefix(_) => return None,
        }
    }

    let mut resolved = base.to_path_buf();
    for segment in &stack {
        resolved.push(segment);
    }

    // Belt-and-braces post-conditions the fuzz target also asserts.
    if !resolved.starts_with(base) {
        return None;
    }
    if resolved
        .components()
        .any(|component| matches!(component, Component::ParentDir))
    {
        return None;
    }
    Some(resolved)
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use super::*;

    fn write_temp(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf {
        let path = dir.join(name);
        let mut f = File::create(&path).expect("create temp file");
        f.write_all(bytes).expect("write temp file");
        path
    }

    #[test]
    fn opens_and_reads_a_regular_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_temp(dir.path(), "hello.txt", b"hello");

        let policy = PathPolicy::new();
        let opened = policy.open(&path).expect("open should succeed");
        assert_eq!(opened.size, 5);
        assert!(opened.path.is_absolute());

        let bytes = policy.read(&path).expect("read should succeed");
        assert_eq!(bytes, b"hello");
    }

    #[test]
    fn empty_path_is_rejected() {
        let policy = PathPolicy::new();
        let err = policy.open(Path::new("")).unwrap_err();
        assert!(matches!(err, PathSecurityError::EmptyPath));
    }

    #[test]
    fn missing_file_is_io_error() {
        let dir = tempfile::tempdir().unwrap();
        let policy = PathPolicy::new();
        let err = policy.open(&dir.path().join("nope")).unwrap_err();
        assert!(matches!(err, PathSecurityError::Io { .. }), "got: {err:?}");
    }

    #[test]
    fn directory_is_not_a_regular_file() {
        let dir = tempfile::tempdir().unwrap();
        let policy = PathPolicy::new();
        let err = policy.open(dir.path()).unwrap_err();
        assert!(
            matches!(err, PathSecurityError::NotRegularFile(_)),
            "got: {err:?}"
        );
    }

    #[test]
    fn oversize_file_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_temp(dir.path(), "big.bin", b"0123456789");
        let policy = PathPolicy::new().max_file_size(4);
        let err = policy.open(&path).unwrap_err();
        assert!(
            matches!(err, PathSecurityError::TooLarge { limit: 4, .. }),
            "got: {err:?}"
        );
    }

    #[test]
    fn read_is_capped() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_temp(dir.path(), "data.bin", b"0123456789");
        let policy = PathPolicy::new().max_file_size(4);
        let err = policy.read(&path).unwrap_err();
        assert!(matches!(err, PathSecurityError::TooLarge { .. }));
    }

    #[test]
    fn read_capped_accepts_within_limit() {
        let bytes = read_capped(&b"hello"[..], 10).unwrap();
        assert_eq!(bytes, b"hello");
    }

    #[test]
    fn read_capped_rejects_over_limit() {
        let err = read_capped(&b"hello"[..], 3).unwrap_err();
        assert!(matches!(err, PathSecurityError::TooLarge { limit: 3, .. }));
    }

    #[test]
    fn base_dir_allows_contained_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_temp(dir.path(), "inside.txt", b"ok");
        let policy = PathPolicy::new().base_dir(dir.path());
        let opened = policy.open(&path).expect("contained file should open");
        assert!(opened.path.starts_with(dir.path().canonicalize().unwrap()));
    }

    #[test]
    fn base_dir_rejects_parent_traversal() {
        let base = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let _secret = write_temp(outside.path(), "secret.txt", b"top secret");

        let policy = PathPolicy::new().base_dir(base.path());
        // Lexical traversal out of the base directory.
        let traversal = base
            .path()
            .join("..")
            .join(outside.path().file_name().unwrap());
        let err = policy.open(&traversal.join("secret.txt")).unwrap_err();
        assert!(
            matches!(
                err,
                PathSecurityError::ParentTraversal(_) | PathSecurityError::OutsideBase { .. }
            ),
            "got: {err:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn base_dir_rejects_symlink_escape() {
        use std::os::unix::fs::symlink;

        let base = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let secret = write_temp(outside.path(), "secret.txt", b"top secret");

        let link = base.path().join("link.txt");
        symlink(&secret, &link).unwrap();

        // Symlinks allowed, but the resolved target escapes the base dir.
        let policy = PathPolicy::new().base_dir(base.path());
        let err = policy.open(&link).unwrap_err();
        assert!(
            matches!(err, PathSecurityError::OutsideBase { .. }),
            "got: {err:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn symlinks_can_be_denied() {
        use std::os::unix::fs::symlink;

        let dir = tempfile::tempdir().unwrap();
        let target = write_temp(dir.path(), "target.txt", b"data");
        let link = dir.path().join("link.txt");
        symlink(&target, &link).unwrap();

        let policy = PathPolicy::new().allow_symlinks(false);
        let err = policy.open(&link).unwrap_err();
        assert!(
            matches!(err, PathSecurityError::SymlinkDenied(_)),
            "got: {err:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn interior_nul_is_rejected() {
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;

        let policy = PathPolicy::new();
        let path = Path::new(OsStr::from_bytes(b"a\0b"));
        let err = policy.open(path).unwrap_err();
        assert!(
            matches!(err, PathSecurityError::InteriorNul),
            "got: {err:?}"
        );
    }

    // -- safe_join (lexical confinement) --------------------------------------

    const BASE: &str = "/var/lib/simdutf8-cli/data";

    fn base() -> PathBuf {
        PathBuf::from(BASE)
    }

    #[test]
    fn safe_join_accepts_well_formed_relative_paths() {
        for candidate in [
            "advisory.json",
            "2026/001/file.json",
            "./a/./b.json",
            ".hidden",
            "",
        ] {
            let resolved = safe_join(&base(), candidate)
                .unwrap_or_else(|| panic!("expected accept for {candidate:?}"));
            assert!(resolved.starts_with(base()), "{candidate:?} escaped base");
            assert!(!resolved
                .components()
                .any(|c| matches!(c, Component::ParentDir)));
        }
    }

    #[test]
    fn safe_join_accepts_balanced_parent() {
        assert_eq!(
            safe_join(&base(), "a/../b.json"),
            Some(base().join("b.json"))
        );
        assert_eq!(safe_join(&base(), "2026/.."), Some(base()));
    }

    #[test]
    fn safe_join_rejects_traversal_and_absolute_and_nul() {
        for candidate in [
            "..",
            "../etc/passwd",
            "../../../../etc/passwd",
            "2026/../../etc/passwd",
            "/etc/passwd",
            "advisory.json\0",
            "a\0b",
        ] {
            assert!(
                safe_join(&base(), candidate).is_none(),
                "expected reject for {candidate:?}"
            );
        }
    }

    #[test]
    fn safe_join_rejects_every_traversal_depth() {
        for depth in 1..=64 {
            let attack = "../".repeat(depth) + "etc/passwd";
            assert!(
                safe_join(&base(), &attack).is_none(),
                "depth {depth} should be rejected"
            );
        }
    }
}