Path Traversal in Flask with Bearer Tokens
Path Traversal in Flask with Bearer Tokens — how this specific combination creates or exposes the vulnerability
Path Traversal occurs when an API allows user-supplied input to navigate outside the intended directory, typically via sequences like ../. In Flask, this often manifests through endpoints that build file paths using unchecked query parameters or route variables. Combining this with Bearer Tokens introduces a nuanced risk: authentication proves identity but does not enforce authorization on file-system operations, so a token with limited logical permissions might still permit traversal if the endpoint trusts user input for file selection.
Consider a Flask route that serves user documents:
from flask import request, send_file
@app.route('/documents')
def get_document():
filename = request.args.get('file')
return send_file(f'/var/data/{filename}')
An attacker with a valid Bearer Token calls /documents?file=../../../etc/passwd. The token validates the request, but the endpoint concatenates the filename unsafely, allowing directory traversal. Because the scan tests unauthenticated attack surfaces, middleBrick can still detect the traversal vector even when endpoints require a token, since the logic that combines authentication state with path construction is analyzed for unsafe resolution. The presence of Bearer Tokens does not inherently neutralize traversal; it only ties the request to an identity without restricting filesystem navigation.
In the context of API security checks, middleBrick maps findings to frameworks such as OWASP API Top 10 (2023) A05:2023 — Broken Function Level Authorization, where excessive trust in input intersects with authenticated routes. Real-world patterns like CVE-2021-28101 — where path traversal in an administrative interface led to unauthorized file access — illustrate the class of issue. Even when endpoints validate scopes encoded in tokens, implementation-level path handling must enforce strict allowlists and canonicalization to prevent read/write outside intended directories.
Bearer Tokens-Specific Remediation in Flask — concrete code fixes
Remediation centers on avoiding direct concatenation of user input into filesystem paths and enforcing strict scope-based checks alongside token validation. Below are two concrete, safe patterns for Flask that work with Bearer Token authentication.
1. Use a validated allowlist and os.path.realpath
Define an allowlist of permitted filenames or paths and resolve the final location to prevent traversal regardless of token claims.
import os
from flask import Flask, request, jsonify
app = Flask(__name__)
ALLOWED = {'report.pdf', 'summary.xlsx', 'readme.txt'}
@app.route('/files')
def get_safe_file():
token = request.headers.get('Authorization', '').replace('Bearer ', '')
# token validation logic would occur here, e.g., verify_jwt(token)
name = request.args.get('name')
if name not in ALLOWED:
return jsonify(error='file not allowed'), 403
base = '/var/data'
safe_path = os.path.realpath(os.path.join(base, name))
if not safe_path.startswith(os.path.realpath(base)):
return jsonify(error='invalid path'), 403
return send_file(safe_path)
This ensures that even if a bearer token identifies a user, the resolved path cannot escape /var/data.
2. Use pathlib with strict relative resolution
Leverage pathlib to construct paths and assert that the final path remains within the intended directory tree.
from pathlib import Path
from flask import Flask, request, jsonify, send_file
app = Flask(__name__)
BASE = Path('/var/data').resolve()
@app.route('/assets')
def get_asset():
token = request.headers.get('Authorization', '').replace('Bearer ', '')
# perform token validation here
raw = request.args.get('file')
if not raw:
return jsonify(error='missing file'), 400
try:
target = (BASE / raw).resolve(strict=True)
except (OSError, RuntimeError):
return jsonify(error='file not found'), 404
if not str(target).startswith(str(BASE)):
return jsonify(error='access denied'), 403
return send_file(target)
Here, resolve() eliminates .. segments, and the prefix check adds a second guard. middleBrick’s OpenAPI/Swagger analysis can cross-reference such implementations against runtime behavior, confirming whether path construction aligns with declared security expectations.
For teams using the middleBrick CLI, scanning with middlebrick scan <url> can validate that these mitigations reduce the traversal risk. In environments requiring continuous oversight, the Pro plan’s continuous monitoring and GitHub Action integration can fail builds if new endpoints introduce unsafe path handling, complementing manual code reviews.
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 |