Security How-to

Your agent's file-download endpoint passes the ../ test and still leaks the folder next door

Agents write a path check that stops ../ and misses sibling directories and symlinks. A seven-row Vitest attack table fails the first draft, and a 20-line fix that resolves real paths passes it. About 20 minutes.

A dark concrete corridor crossed by a low wall, with a single narrow shaft of peach light slipping through a gap in its centre

A feature ticket says users should be able to download the reports they uploaded. The agent writes a handler that takes ?file=reports/q3.txt, resolves it against the uploads folder, checks the result still starts with that folder, and reads the file. It even adds a test that ../secret.txt is refused. Green. Merged.

Then somebody asks for ../uploads-private/keys.txt and gets it, because the check compares strings, and /srv/uploads-private starts with /srv/uploads. Or a user uploads an archive containing a symlink, and the “inside the folder” file is a pointer to /etc/passwd.

This is path traversal, and generated code reproduces it for a boring reason: the version that handles the textbook ../ case looks finished. What follows is a short attack table as a Vitest file, the failing run against the usual first draft, and a small function that passes. The method works with any coding agent that can read files and run a shell, and the prompt at the end is written to be pasted into one.

The first draft

This is the shape an agent tends to produce, and it’s what a reviewer tends to wave through:

import path from "node:path";
import { readFile } from "node:fs/promises";

export async function readUpload(root: string, requested: string): Promise<Buffer> {
  const target = path.resolve(root, requested);
  if (!target.startsWith(path.resolve(root))) {
    throw new Error("Forbidden");
  }
  return readFile(target);
}

Using path.resolve is the right instinct. It collapses .. segments, so reports/../../secret.txt becomes a plain absolute path before the check sees it. And an absolute request like /etc/passwd is dealt with too: per the Node documentation, path.resolve processes segments from right to left until it has an absolute path, so a later absolute segment replaces everything before it. The target becomes /etc/passwd, which doesn’t start with the root, and the request is refused.

So the obvious attacks fail. Two others don’t.

Write the attack table first

Put the attacks in a test file before touching the implementation. The fixture builds a temporary directory with a deliberately awkward layout: the uploads root, a sibling whose name starts with the same characters, a secret one level above, and a symlink inside the root that points at the secret.

import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdtemp, mkdir, writeFile, symlink, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { readUpload } from "../src/files";

let base: string;
let root: string;

beforeAll(async () => {
  base = await mkdtemp(path.join(tmpdir(), "uploads-"));
  root = path.join(base, "uploads");
  await mkdir(path.join(root, "reports"), { recursive: true });
  await mkdir(path.join(base, "uploads-private"));
  await writeFile(path.join(root, "reports", "q3.txt"), "public report");
  await writeFile(path.join(base, "secret.txt"), "top secret");
  await writeFile(path.join(base, "uploads-private", "keys.txt"), "private key");
  await symlink(path.join(base, "secret.txt"), path.join(root, "shortcut.txt"));
});
afterAll(() => rm(base, { recursive: true, force: true }));

describe("legitimate reads", () => {
  it.each(["reports/q3.txt", "./reports/q3.txt", "reports/../reports/q3.txt"])(
    "serves %s",
    async (p) => {
      expect((await readUpload(root, p)).toString()).toBe("public report");
    },
  );
});

describe("attacks", () => {
  const attacks: [string, string][] = [
    ["parent traversal", "../secret.txt"],
    ["deep traversal", "reports/../../secret.txt"],
    ["sibling with shared prefix", "../uploads-private/keys.txt"],
    ["absolute path", "/etc/passwd"],
    ["NUL byte", "reports/q3.txt\0.png"],
    ["symlink out of root", "shortcut.txt"],
    ["the root itself", "."],
  ];
  it.each(attacks)("rejects %s", async (_name, p) => {
    await expect(readUpload(root, p)).rejects.toThrow();
  });
});

The first group matters as much as the second. A guard that rejects everything passes every attack row, and the legitimate reads (including the ./ and reports/../reports spellings that normalise to the same file) are what stop an overzealous fix.

Run it against the first draft:

 ❯ test/files.test.ts (10 tests | 2 failed)
   ❯ attacks (7)
     × rejects sibling with shared prefix
     × rejects symlink out of root
 FAIL  test/files.test.ts > attacks > rejects sibling with shared prefix
AssertionError: promise resolved "Buffer[ 112, 114, 105, 118, 97, …" instead of rejecting

Eight rows pass and two fail. That’s the useful shape: the draft isn’t broken everywhere, which is exactly why it survives review. (The NUL-byte row passes only because Node’s readFile throws on a path containing one. The test pins that behaviour so a later refactor can’t quietly lose it.)

Why the sibling check fails

startsWith compares characters, not path segments. With the root at /tmp/x/uploads, the string /tmp/x/uploads-private/keys.txt starts with it. Nothing about “begins with these characters” means “is inside this directory”.

The popular patch is to append a separator and compare against root + path.sep. That closes this row, and it’s worth checking whether it’s enough. With that one-line change the same table prints:

 ❯ test/files.test.ts (10 tests | 1 failed)
     × rejects symlink out of root
 Tests  1 failed | 9 passed (10)

The sibling is blocked and the symlink still gets through. path.resolve works on the text of the path and never touches the filesystem. The Node path documentation describes it as segment manipulation and says nothing about following links, so root/shortcut.txt is “inside the root” as far as any string comparison can tell, and readFile then follows the link to the file it points at.

A string-level fix can’t catch this class. The check has to ask the filesystem where the path really ends up.

The fix: compare real paths, with path.relative

import path from "node:path";
import { open, realpath } from "node:fs/promises";

export class ForbiddenPathError extends Error {}

export async function resolveInside(root: string, requested: string): Promise<string> {
  if (requested.includes("\0")) throw new ForbiddenPathError("NUL byte");
  if (path.isAbsolute(requested)) throw new ForbiddenPathError("absolute path");

  const realRoot = await realpath(root);
  // realpath follows symlinks, so a link inside root that points outside is caught here.
  const realTarget = await realpath(path.resolve(realRoot, requested));

  const rel = path.relative(realRoot, realTarget);
  if (rel === "" || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) {
    throw new ForbiddenPathError("outside root");
  }
  return realTarget;
}

export async function readUpload(root: string, requested: string): Promise<Buffer> {
  const target = await resolveInside(root, requested);
  const handle = await open(target, "r");
  try {
    return await handle.readFile();
  } finally {
    await handle.close();
  }
}

Three decisions are worth understanding, because an agent will “simplify” each of them if left alone.

First, the root is resolved with realpath as well as the target. If the uploads folder is itself reached through a symlink (common with mounted volumes), comparing a real target against an unresolved root rejects everything.

Second, the containment test uses path.relative. It returns a path from the root to the target, climbing with .. segments when the target is elsewhere, and an empty string when both are the same. So “inside” means the relative path doesn’t start with .. and isn’t absolute (on Windows, a different drive produces an absolute result). The ".." + path.sep form matters: a file legitimately named ..hidden has a relative path that starts with two dots but isn’t a parent reference.

Third, the root itself is refused (rel === ""). A request for . is a request to read a directory, and returning an error here is cleaner than letting open fail with a platform-specific message.

Run the table again:

 Test Files  1 passed (1)
      Tests  10 passed (10)

All ten pass: three legitimate spellings served, seven attacks refused.

What this still doesn’t cover

Realpath-then-open has a gap between the check and the use. If an attacker can swap a file for a symlink after realpath returns and before open runs, the check was about a different file. For a service where untrusted users can write into the same directory tree that another request reads, that’s a real race. The mitigations sit outside this function: keep upload storage write-only for the process that serves downloads, store files under generated names and keep the user’s filename in a database column, or serve from object storage where there are no links. OWASP’s guidance on this class points the same way: don’t let the user supply all parts of a path, and prefer known-good identifiers over sanitising names.

That last option is often the best one. If the download route takes a document ID and looks up the stored location, there is no user-controlled path to validate. The attack table is for the code that has to accept names, such as static asset routes, archive extraction and anything that reads a path out of a config or a prompt.

One platform note: the table was run on Linux only. On Windows, path.relative across drives returns an absolute path, which the guard rejects, but run the table on a Windows runner before trusting it there.

Making any agent keep the table

The failure mode to prevent is the agent “tidying” the guard later: replacing path.relative with startsWith because it looks simpler, or dropping realpath because a test environment doesn’t need it. The table catches that, provided the agent is told to run it. A prompt that works in any coding agent:

Add a download endpoint that serves files from ./uploads by a user-supplied relative path.

Before writing the implementation:
1. Create test/files.test.ts with a fixture containing the uploads root, a sibling
   directory whose name starts with "uploads", a file above the root, and a symlink
   inside the root pointing at that file.
2. Add legitimate reads and an attack table: parent traversal, deep traversal, sibling
   with shared prefix, absolute path, NUL byte, symlink out of root, and the root itself.
3. Run `npx vitest run` and show me the failing output.

Then implement resolveInside() so every row passes. Compare real paths (fs.realpath on
both root and target) and test containment with path.relative, not startsWith.
Do not weaken or delete a row to get green. Run the suite again and show the result.

The instruction to show the failing output first is the part that carries weight. It forces the agent to prove the table can fail, so a table that was accidentally written to pass doesn’t get through. Add npx vitest run to CI and the guard stays pinned whichever tool touches the file next.

First 20 minutes

Search your codebase for startsWith( near path.resolve or path.join, and for any handler that builds a path from req.query, req.params or a filename in an uploaded archive. Pick one, copy the fixture and attack table above, and point readUpload at the real function. If every row passes on the first run, the code was already sound. If one fails, the failing row is the bug report.