Path traversal in AI-built apps: when ../ in a download link reads your .env (and a safe test)

2026-11-29来源 dev.toEnglish

Path traversal is when a user controls part of a file path and uses ../ to climb out of the folder you meant to serve. A route like /download?file=report.pdf becomes /download?file=../../.env, and your server hands over its secrets. AI-built apps add download, preview and "serve this upload" routes all the time, and the path handling is often one line.

1. The pattern to look for

Unsafe:

app.get("/download", (req, res) => { res.sendFile(path.join(__dirname, "uploads", req.query.file)); }); 

path.join does not stop ../. Safer:

const base = path.resolve(__dirname, "uploads"); const target = path.resolve(base, req.query.file); if (!target.startsWith(base + path.sep)) return res.status(400).end(); res.sendFile(target); 

Better still: store files under random IDs in a database, and let users ask for the ID, not a path.

2. Where it hides

  • Download and export endpoints
  • Image or avatar routes that take a file name
  • "Preview this file" features
  • Template or language-file loaders that take a name from the URL
  • Zip upload features that unpack names from inside the archive

3. A safe test on your own app

  1. Find a route that takes a file name.
  2. Request it with a file you know exists but should not be served, such as a harmless text file one folder up, using ../ in the name. Try the URL-encoded form too (..%2f).
  3. If the content comes back, the route is open.
  4. Do this on your own app, with a test file, not a real secrets file.

4. Fixes that hold up

  • Do not build paths from user input. Map an ID to a stored path on the server.
  • If you must accept a name, resolve the full path and check it stays inside the allowed folder.
  • Allow only a short list of file extensions.
  • Run the app as a user with no read access to secrets outside its own folder.
  • Keep .env and keys out of the folder the web server can serve.

What an outside scan can and cannot tell you

An outside scan can check common exposed files, such as .env or .git, at the paths a stranger would try first. It does not probe your custom download routes, so test those by hand.

Check your own app from the outside, free. Run the free ProofForge scan on your live URL. No account needed for the first scan. It looks at your public site the way a stranger would and says pass, fail or inconclusive, so you know what is confirmed and what it could not see. One-time reports start at $9: see pricing. Building with an AI agent? There is an MCP server so it can check before it deploys.

原文:https://www.a8q9.cn/en/article/path-traversal-in-ai-built-apps-when-in-a-download-link-reads-your-env-and-a-saf-f24f67.html

相关文章