P1 FB-08: Path-Traversal-Sanitization + Response-Size-Cap in download_file
- Add _sanitize_file_path_component() — strips all chars except [a-zA-Z0-9._-] - download_file() now sanitizes file_id and filename before URL construction - URL-encode path components with urllib.parse.quote() - Response size cap: read in 64KB chunks, stop at max_size (default 10MB) - Reject downloads when sanitized file_id or filename is empty - Add 10 new tests in test_p1_fb08_file_security.py (all green) - No regressions: 578 archivar tests pass, 82 top-level tests pass
This commit is contained in:
+55
-3
@@ -24,6 +24,7 @@ import ssl
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import uuid
|
||||
@@ -236,6 +237,27 @@ def _get_config_str(config: PlatformConfig, key: str, env_var: str, default: str
|
||||
return os.getenv(env_var) or extra.get(key, default)
|
||||
|
||||
|
||||
# P1 FB-08: File path component sanitizer for download_file
|
||||
# Reduces a string to only safe characters: alphanumeric, dot, underscore, hyphen.
|
||||
# Returns empty string if nothing remains after sanitization.
|
||||
_FILE_PATH_SAFE_RE = re.compile(r'[^a-zA-Z0-9._-]')
|
||||
|
||||
|
||||
def _sanitize_file_path_component(value: str) -> str:
|
||||
"""Sanitize a file path component for use in URL construction.
|
||||
|
||||
Removes all characters except [a-zA-Z0-9._-] to prevent path traversal
|
||||
attacks (e.g. '../etc/passwd' → 'etcpasswd').
|
||||
|
||||
Args:
|
||||
value: Raw file_id or filename from user input.
|
||||
|
||||
Returns:
|
||||
Sanitized string, or empty string if nothing remains.
|
||||
"""
|
||||
return _FILE_PATH_SAFE_RE.sub('', value)
|
||||
|
||||
|
||||
class RocketChatREST:
|
||||
def __init__(self, base_url: str):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
@@ -318,22 +340,52 @@ class RocketChatREST:
|
||||
return (r.get("message") or {}).get("_id")
|
||||
return None
|
||||
|
||||
def download_file(self, file_id: str, filename: str) -> Optional[str]:
|
||||
def download_file(self, file_id: str, filename: str, max_size: int = 10 * 1024 * 1024) -> Optional[str]:
|
||||
"""Download a file from Rocket.Chat using the authenticated REST client.
|
||||
|
||||
Returns the file content as a string (text files) or None on failure.
|
||||
Uses the existing authToken — no security scanner triggers.
|
||||
|
||||
P1 Security (FB-08): Sanitizes file_id and filename to prevent path
|
||||
traversal, URL-encodes path components, and caps response size to
|
||||
prevent DoS via oversized downloads.
|
||||
"""
|
||||
if not self.auth_token:
|
||||
return None
|
||||
url = f"{self.base_url}/file-upload/{file_id}/{filename}"
|
||||
|
||||
# P1 FB-08: Sanitize file_id and filename — allow only safe characters
|
||||
file_id = _sanitize_file_path_component(file_id)
|
||||
filename = _sanitize_file_path_component(filename)
|
||||
if not file_id or not filename:
|
||||
logger.warning("File download rejected: invalid file_id or filename after sanitization")
|
||||
return None
|
||||
|
||||
# P1 FB-08: URL-encode path components to prevent traversal
|
||||
safe_fid = urllib.parse.quote(file_id, safe='')
|
||||
safe_fname = urllib.parse.quote(filename, safe='')
|
||||
url = f"{self.base_url}/file-upload/{safe_fid}/{safe_fname}"
|
||||
req = urllib.request.Request(url, headers={
|
||||
"X-Auth-Token": self.auth_token,
|
||||
"X-User-Id": self.user_id,
|
||||
})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
content = resp.read()
|
||||
# P1 FB-08: Response size cap — read in chunks, stop at max_size
|
||||
chunks = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = resp.read(min(65536, max_size - total))
|
||||
if not chunk:
|
||||
break
|
||||
chunks.append(chunk)
|
||||
total += len(chunk)
|
||||
if total >= max_size:
|
||||
logger.warning(
|
||||
"File download truncated at %d bytes (max_size=%d): %s",
|
||||
total, max_size, filename,
|
||||
)
|
||||
break
|
||||
content = b"".join(chunks)
|
||||
try:
|
||||
return content.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
|
||||
Reference in New Issue
Block a user