Normalize And Guard Paths With Path::components

Resolve relative . and .. segments purely in memory via Path::components while rejecting root prefixes and traversals escaping above the sandbox.

RustSecurity Boundaries

Code

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

fn normalize_under(root: &Path, untrusted: &str) -> Result<PathBuf, &'static str> {
    let mut stack = Vec::new();
    for comp in Path::new(untrusted).components() {
        match comp {
            Component::CurDir => {}
            Component::Normal(seg) => stack.push(seg),
            Component::ParentDir => {
                if stack.pop().is_none() {
                    return Err("traversal escapes sandbox root");
                }
            }
            Component::RootDir | Component::Prefix(_) => {
                return Err("absolute or prefixed paths are forbidden");
            }
        }
    }
    let mut out = root.to_path_buf();
    for seg in stack {
        out.push(seg);
    }
    Ok(out)
}

fn main() {
    let root = Path::new("/srv/static");
    let cases = [
        "css/../js/app.js",
        "./images/logo.png",
        "assets/../../etc/passwd",
        "/etc/shadow",
    ];
    for candidate in cases {
        match normalize_under(root, candidate) {
            Ok(safe) => println!("{candidate:<25} -> {}", safe.display()),
            Err(err) => println!("{candidate:<25} -> blocked ({err})"),
        }
    }
}

Behavior overview — Normalize And Guard Paths With Path::components

The full behavior executes completely inside routines normalize_under and main.

Iteration happens inside for comp in Path::new(untrusted).components() — everything outside it runs once. Failure is encoded in the return type — Result leaves no room for an unhandled error. A match spells out every case; omit one and the code does not compile.

What to watch for

  • Works straight away on capabilities shipped with the toolchain — zero additions.
  • Every fallible call yields a Result you must unwrap or propagate; there is no implicit throw.

Applying it

The entry-point signature is fn normalize_under(root: &Path, untrusted: &str) -> Result<PathBuf, &'static str>

The entry point wires normalize_under together — run it once and the whole demo flows.

Statements that matter

return Err("absolute or prefixed paths are forbidden");
return Err("traversal escapes sandbox root");
match normalize_under(root, candidate) {
    Ok(safe) => println!("{candidate:<25} -> {}", safe.display()),
    Err(err) => println!("{candidate:<25} -> blocked ({err})"),
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
Through the type system: failures are `Result` variants the caller must consume.
How do you run Normalize And Guard Paths With Path::components?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.