Path Normalization Guard

Normalize an untrusted relative path component by component and reject anything that would climb above the allowed root.

RustSecurity Boundaries

Code

rustsnippet
51 lines
use std::path::{Component, Path, PathBuf};

fn normalize_join(root: &Path, untrusted: &str) -> Result<PathBuf, String> {
    let candidate = Path::new(untrusted);
    if candidate.is_absolute() {
        return Err(format!("rejected absolute path: {untrusted}"));
    }

    let mut depth = 0usize;
    let mut normalized = PathBuf::new();
    for component in candidate.components() {
        match component {
            Component::Normal(part) => {
                normalized.push(part);
                depth += 1;
            }
            Component::CurDir => {}
            Component::ParentDir => {
                if depth == 0 {
                    return Err(format!("path escapes root: {untrusted}"));
                }
                normalized.pop();
                depth -= 1;
            }
            _ => return Err(format!("unsupported path component in {untrusted}")),
        }
    }

    let joined = root.join(&normalized);
    if !joined.starts_with(root) {
        return Err(format!("resolved path escapes root: {untrusted}"));
    }
    Ok(joined)
}

fn main() {
    let root = Path::new("/srv/uploads");
    let candidates = [
        "reports/2026/q1.csv",
        "reports/../notes.txt",
        "../secrets.env",
        "/etc/passwd",
        "a/../../b",
    ];
    for candidate in candidates {
        match normalize_join(root, candidate) {
            Ok(path) => println!("ok   {candidate:<22} => {}", path.display()),
            Err(error) => println!("skip {candidate:<22} => {error}"),
        }
    }
}

How the snippet works

The working surface is the functions normalize_join and main — everything else is wiring.

Repetition is confined to for component in candidate.components() — the rest of the file is straight-line. The function returns Result, so handling the error arm is not optional. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

What to watch for

  • The ? operators are load-bearing: delete one and the error handling becomes your job.

Applying it

The main signature reads fn normalize_join(root: &Path, untrusted: &str) -> Result<PathBuf, String>

The demo output is labeled (ok, skip), so every printed line maps back to its originating operation.

main is the driver: it invokes normalize_join before returning.

Statements that matter

return Err(format!("resolved path escapes root: {untrusted}"));
return Err(format!("rejected absolute path: {untrusted}"));
return Err(format!("path escapes root: {untrusted}"));

Interactive Tools for This Topic

FAQ

Is there exception handling?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
What does Path Normalization Guard print when run?
Invoke the file as-is — the `ok`, `skip` prefixes identify which step printed each line.