Skip to content

Commit b59e94d

Browse files
authored
Merge pull request #9 from github-samples/alert-autofix-3
Potential fix for code scanning alert no. 3: Uncontrolled data used in path expression
2 parents fae88b3 + d80aa9e commit b59e94d

1 file changed

Lines changed: 10 additions & 7 deletions

File tree

pages/api/download.js

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,17 @@ export default function handler(req, res) {
1212
return res.status(400).json({ error: 'Filename is required' });
1313
}
1414

15-
// VULNERABILITY: Path Traversal
16-
// User input is used directly to construct file paths
17-
// An attacker could use input like: "../../../../etc/passwd"
18-
const filePath = path.join(process.cwd(), 'uploads', filename);
19-
15+
// Securely construct a path under the uploads directory
16+
const uploadsRoot = path.join(process.cwd(), 'uploads');
17+
const resolvedPath = path.resolve(uploadsRoot, String(filename));
18+
19+
// Ensure the resolved path is within the uploads root to prevent path traversal
20+
if (!resolvedPath.startsWith(uploadsRoot + path.sep) && resolvedPath !== uploadsRoot) {
21+
return res.status(400).json({ error: 'Invalid filename' });
22+
}
23+
2024
try {
21-
// Reading file without proper validation
22-
const fileContent = fs.readFileSync(filePath, 'utf8');
25+
const fileContent = fs.readFileSync(resolvedPath, 'utf8');
2326

2427
res.status(200).json({
2528
filename: filename,

0 commit comments

Comments
 (0)