HIGH path traversalrestifybearer tokens

Path Traversal in Restify with Bearer Tokens

Path Traversal in Restify with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Path Traversal in a Restify service becomes high risk when endpoints rely on Bearer Tokens for authorization but do not validate or sanitize user-controlled path inputs. In this combination, an authenticated request (with a valid Bearer Token) can traverse directories outside the intended file or resource scope by supplying crafted sequences such as ../../ or encoded variants in URL paths or query parameters.

Consider a Restify endpoint that serves files from a base directory using a user-supplied path segment:

const fs = require('fs');
const path = require('path');
const restify = require('restify');

const server = restify.createServer();
server.get('/files/:filename', (req, res, next) => {
  const base = './public';
  const file = path.join(base, req.params.filename);
  fs.readFile(file, (err, data) => {
    if (err) return next(new restify.NotFoundError('File not found'));
    res.send(data);
    return next();
  });
});
server.listen(8080);

If the API validates Bearer Tokens but does not restrict or canonicalize req.params.filename, an authenticated attacker can send a request like GET /files/../../../etc/passwd with a valid token and potentially read sensitive host files. The token proves identity but does not enforce authorization boundaries on file system access, allowing the traversal to escape the intended ./public directory.

In the context of middleBrick’s checks, this scenario maps to multiple security controls: Authentication (token presence is valid), BOLA/IDOR (insufficient ownership checks on file resources), Input Validation (lack of path canonicalization and denylist/allowlist), and Property Authorization (missing verification that the authenticated subject is permitted to access the specific resolved path). The scanner can detect the presence of Bearer Token usage and flag the absence of strict path validation as a high-severity finding, even though the endpoint is technically authenticated.

Moreover, if query parameters or URL-encoded paths are used to locate resources (e.g., /download?name=..%2F..%2Fsecret.txt), similar traversal can occur. Bearer Tokens may be checked at a gateway or middleware layer, but if the downstream handler does not independently validate and constrain paths, the authenticated context is abused to reach arbitrary files. This highlights the need to treat authentication and authorization separately: tokens establish identity, but path handling must enforce strict allowlist rules and resolve paths safely before filesystem operations.

Bearer Tokens-Specific Remediation in Restify — concrete code fixes

Remediation focuses on ensuring that Bearer Token authentication does not inadvertently authorize unsafe path resolution. You must validate and sanitize all path inputs independently of authentication status, and enforce strict allowlists for accessible resources.

1. Use a strict allowlist of permitted files or a mapping of safe identifiers to filesystem paths, and never directly concatenate user input into filesystem paths:

const allowed = new Set(['report.pdf', 'image.png', 'readme.txt']);

server.get('/files/:filename', (req, res, next) => {
  const filename = req.params.filename;
  if (!allowed.has(filename)) {
    return next(new restify.ForbiddenError('Access denied'));
  }
  const file = path.join('./public', filename);
  const resolved = path.resolve(file);
  if (!resolved.startsWith(path.resolve('./public'))) {
    return next(new restify.ForbiddenError('Invalid path'));
  }
  fs.readFile(resolved, (err, data) => {
    if (err) return next(new restify.NotFoundError('File not found'));
    res.send(data);
    return next();
  });
});

2. Prefer an allowlist mapping for sensitive resources, where tokens establish identity but the server decides access per scope:

const userAccess = {
  'token-abc123': ['report.pdf', 'readme.txt'],
  'token-xyz789': ['image.png']
};

server.get('/files/:filename', (req, res, next) => {
  const token = req.authorization?.bearer;
  const filename = req.params.filename;
  if (!token || !userAccess[token] || !userAccess[token].includes(filename)) {
    return next(new restify.UnauthorizedError('Invalid token or scope'));
  }
  const file = path.join('./public', filename);
  const resolved = path.resolve(file);
  if (!resolved.startsWith(path.resolve('./public'))) {
    return next(new restify.ForbiddenError('Invalid path'));
  }
  fs.readFile(resolved, (err, data) => {
    if (err) return next(new restify.NotFoundError('File not found'));
    res.send(data);
    return next();
  });
});

3. Always canonicalize and validate paths with path.resolve and explicit prefix checks. Reject paths containing null bytes, encoded slashes, or directory traversal sequences regardless of token presence:

server.get('/files/:filename', (req, res, next) => {
  let filename = req.params.filename;
  if (filename.includes('..') || filename.includes('\0')) {
    return next(new restify.BadRequestError('Invalid filename'));
  }
  const file = path.resolve('./public', filename);
  if (!file.startsWith(path.resolve('./public'))) {
    return next(new restify.ForbiddenError('Path traversal attempt'));
  }
  fs.readFile(file, (err, data) => {
    if (err) return next(new restify.NotFoundError('File not found'));
    res.send(data);
    return next();
  });
});

These patterns ensure that Bearer Tokens provide authentication while additional controls enforce authorization and path integrity, reducing the risk of Path Traversal in Restify services.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Does using Bearer Tokens alone prevent Path Traversal in Restify APIs?
No. Bearer Tokens confirm identity but do not restrict filesystem or resource access. You must validate and sanitize path inputs and enforce allowlists regardless of token presence to prevent traversal.
How does middleBrick assess Path Traversal risks when Bearer Tokens are used?
middleBrick scans unauthenticated attack surfaces and also tests authenticated checks when credentials are supplied. It flags missing path validation, improper canonicalization, and authorization gaps even when tokens are accepted, mapping findings to relevant standards such as OWASP API Top 10.