Path Traversal in Loopback with Bearer Tokens
Path Traversal in Loopback with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Path Traversal in a Loopback application using Bearer Tokens occurs when an API endpoint accepts user-supplied paths—often derived from request parameters, query strings, or route placeholders—and uses them to construct filesystem operations without adequate validation. Even when requests include Bearer Tokens for authentication, the authorization boundary can be misaligned with the file access boundary, leading to scenarios where a valid token does not prevent unauthorized file reads or writes.
Consider a Loopback endpoint designed to retrieve user-uploaded documents. If the API uses an identifier such as req.query.file directly in a path join, an attacker authenticated with a valid Bearer Token can traverse directories using sequences like ../../../etc/passwd. The presence of the token confirms identity but does not restrict which files the identity is allowed to access; if the server resolves the path against the filesystem, the traversal succeeds. This is a classic broken access control pattern mapped to OWASP API Top 10 A01:2023 (Broken Object Level Authorization) and A05:2023 (Security Misconfiguration), and it can be discovered by the 12 security checks in middleBrick, including Property Authorization and BOLA/IDOR.
Middleware that normalizes and validates paths is essential. For example, using path.resolve without restricting the base directory can still allow escapes if the input contains encoded characters or null bytes. Similarly, failing to canonicalize paths before comparison can let an attacker bypass simple prefix checks. middleBrick’s OpenAPI/Swagger spec analysis resolves $ref definitions across 2.0, 3.0, and 3.1 specs and cross-references them with runtime findings, highlighting where documented parameters do not match actual server-side handling. This is important because an endpoint may claim to accept a simple file name while the implementation permits directory sequences.
Real-world attack patterns include exploiting predictable file names, leveraging insecure file upload storages, or abusing endpoints that return directory listings. In a Loopback context, this can intersect with SSRF if user-controlled paths are used to reach internal resources. middleBrick tests for Data Exposure and Input Validation to surface such issues, providing severity-ranked findings and remediation guidance rather than attempting to fix or block traffic.
An example of a vulnerable route definition and a crafted request illustrates the risk. The server may implement a route like /api/files/:filename, and an authenticated request with header Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 and query ?file=../../../etc/passwd can return sensitive system data if the server does not confine file access to an intended directory. middleBrick’s scan would flag this with a severity rating and reference relevant compliance mappings such as PCI-DSS and SOC2 controls.
Bearer Tokens-Specific Remediation in Loopback — concrete code fixes
Securing Path Traversal in Loopback while using Bearer Tokens requires strict input validation, canonical path resolution, and scoping file access to a designated base directory. Bearer Tokens should continue to be used for authentication and identity, but they must not be conflated with authorization over filesystem resources. Implement explicit allowlists, avoid dynamic path joins with user input, and enforce scope boundaries.
Below are concrete code examples demonstrating secure patterns. The first shows a vulnerable endpoint that naively joins user input, and the second shows a hardened version that restricts file access to a permitted directory.
// Vulnerable example — do not use
const path = require('path');
const fs = require('fs');
router.get('/files/:filename', (req, res) => {
const userToken = req.headers.authorization?.split(' ')[1]; // Bearer token present but unused for file scope
const filename = req.params.filename;
const filePath = path.join(__dirname, 'uploads', filename); // No validation
fs.readFile(filePath, (err, data) => {
if (err) return res.status(404).send('Not found');
res.send(data);
});
});
In the example above, the Bearer Token is extracted but does not influence which files can be read, and the filename is directly concatenated, enabling traversal. An authenticated request with Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 and filename ../../../etc/passwd would escape the intended directory.
The hardened version below uses a base directory, validates the resolved path, and rejects unsafe sequences. It retains Bearer Token authentication for audit logging or rate limiting but does not rely on the token for file access decisions.
// Secure example — recommended pattern
const path = require('path');
const fs = require('fs');
const BASE_DIR = path.resolve(__dirname, 'uploads');
router.get('/files/:filename', (req, res) =>
{
const userToken = req.headers.authorization?.split(' ')[1];
const filename = req.params.filename;
// Validate filename: allow only safe characters and no path separators
if (!/^[a-zA-Z0-9._-]+$/.test(filename)) {
return res.status(400).send('Invalid filename');
}
const resolvedPath = path.resolve(BASE_DIR, filename);
if (!resolvedPath.startsWith(BASE_DIR)) {
return res.status(403).send('Forbidden');
}
fs.readFile(resolvedPath, (err, data) => {
if (err) return res.status(404).send('Not found');
res.setHeader('Content-Type', 'text/plain');
res.send(data);
});
});
Key remediation steps include:
- Use a fixed base directory and resolve it once at startup.
- Canonicalize user input with path.resolve and confirm the result remains within the base directory.
- Apply allowlists for filenames, rejecting .., path separators, and encoding tricks.
- Continue to validate Bearer Tokens for authentication, and consider tying tokens to scopes or tenant identifiers in application logic, but do not use them as the sole mechanism for filesystem permissions.
middleBrick’s scans can detect missing validation and insecure path handling, surfacing findings with severity levels and guidance mapped to frameworks like OWASP API Top 10. For ongoing protection, the Pro plan enables continuous monitoring and configurable scans, while the CLI allows integration into scripts to verify remediation.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |
Frequently Asked Questions
Does a valid Bearer Token guarantee that path traversal is prevented in Loopback APIs?
How can I test if my Loopback API is vulnerable to path traversal when using Bearer Tokens?
../../../etc/passwd, then verify that the server does not return sensitive files.