From d80aa9ea86064d48721b44413957546e67176b78 Mon Sep 17 00:00:00 2001 From: Kylie Stradley <4666485+KyFaSt@users.noreply.github.com> Date: Mon, 12 Jan 2026 11:56:55 -0500 Subject: [PATCH] Potential fix for code scanning alert no. 3: Uncontrolled data used in path expression Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- pages/api/download.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/pages/api/download.js b/pages/api/download.js index c6727b2..7128b1e 100644 --- a/pages/api/download.js +++ b/pages/api/download.js @@ -12,14 +12,17 @@ export default function handler(req, res) { return res.status(400).json({ error: 'Filename is required' }); } - // VULNERABILITY: Path Traversal - // User input is used directly to construct file paths - // An attacker could use input like: "../../../../etc/passwd" - const filePath = path.join(process.cwd(), 'uploads', filename); - + // Securely construct a path under the uploads directory + const uploadsRoot = path.join(process.cwd(), 'uploads'); + const resolvedPath = path.resolve(uploadsRoot, String(filename)); + + // Ensure the resolved path is within the uploads root to prevent path traversal + if (!resolvedPath.startsWith(uploadsRoot + path.sep) && resolvedPath !== uploadsRoot) { + return res.status(400).json({ error: 'Invalid filename' }); + } + try { - // Reading file without proper validation - const fileContent = fs.readFileSync(filePath, 'utf8'); + const fileContent = fs.readFileSync(resolvedPath, 'utf8'); res.status(200).json({ filename: filename,