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.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- How do you run Path Normalize Traversal Guard?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.