Path Normalize Traversal Guard

Resolve user-controlled paths against a base directory, normalize away dot segments, and reject results that escape the base with startsWith.

JavaSecurity Boundaries

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class DocumentStore {

    public static void main(String[] args) throws IOException {
        Path base = Files.createTempDirectory("docs");
        // path traversal 防御:先 resolve 再 normalize,最后确认仍在 base 内
        for (String request : new String[] {"reports/q4.pdf", "../../etc/passwd", "a/./b.txt"}) {
            Path resolved = base.resolve(request).normalize();
            boolean traversalGuard = resolved.startsWith(base);
            System.out.println(request + " -> " + resolved + " inside: " + traversalGuard);
        }
    }
}

How the snippet works

The working surface is the class DocumentStore — everything else is wiring.

Repetition is confined to for (String request : new String[] {"reports/q4.pdf", "../../etc/passwd", "a/./b.txt"}) — the rest of the file is straight-line.

Statements that matter

boolean traversalGuard = resolved.startsWith(base);
Path resolved = base.resolve(request).normalize();
Path base = Files.createTempDirectory("docs");

Interactive Tools for This Topic

FAQ

How do you run Path Normalize Traversal Guard?
Nothing to install first — run the file and the program does the rest.