Path Traversal

File system operations with unsanitized user input

criticalSecuritypath-traversal

Why this matters

Path traversal lets attackers read files outside the intended directory — like /etc/passwd, .env, or your source code — by injecting ../ sequences into file paths.

Bad
import { readFile } from "fs/promises";
import path from "path";

export async function GET(req: Request) {
  const url = new URL(req.url);
  const file = url.searchParams.get("file")!;
  const data = await readFile(
    path.join("./uploads", file)
  );
  return new Response(data);
}
Good
import { readFile } from "fs/promises";
import path from "path";

export async function GET(req: Request) {
  const url = new URL(req.url);
  const file = url.searchParams.get("file")!;
  const resolved = path.resolve("./uploads", file);
  if (!resolved.startsWith(path.resolve("./uploads"))) {
    return new Response("Forbidden", { status: 403 });
  }
  const data = await readFile(resolved);
  return new Response(data);
}

How to fix

Resolve the full path and verify it stays within the intended directory. Reject any path containing .. or that resolves outside the allowed root.

All rules