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:
Bernd (Hermes)
2026-07-29 06:09:28 +02:00
parent 0308ce0fd2
commit d2945e185b
2 changed files with 198 additions and 3 deletions
+55 -3
View File
@@ -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:
+143
View File
@@ -0,0 +1,143 @@
"""
P1 FB-08: Path-Traversal-Sanitization + Response-Size-Cap Tests.
Tests for _sanitize_file_path_component and download_file security fixes.
"""
from __future__ import annotations
import sys
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
class TestSanitizeFilePathComponent(unittest.TestCase):
"""P1 FB-08: _sanitize_file_path_component strips dangerous characters."""
def test_normal_filename_passes(self):
"""Normal filenames pass through unchanged."""
from plugin.adapter import _sanitize_file_path_component
assert _sanitize_file_path_component("report.pdf") == "report.pdf"
assert _sanitize_file_path_component("my-file_2024.txt") == "my-file_2024.txt"
assert _sanitize_file_path_component("abc123") == "abc123"
def test_path_traversal_stripped(self):
"""Path traversal characters are removed."""
from plugin.adapter import _sanitize_file_path_component
assert _sanitize_file_path_component("../etc/passwd") == "..etcpasswd"
assert _sanitize_file_path_component("..\\windows\\system32") == "..windowssystem32"
def test_special_chars_stripped(self):
"""Special characters are removed."""
from plugin.adapter import _sanitize_file_path_component
assert _sanitize_file_path_component("file name.txt") == "filename.txt"
assert _sanitize_file_path_component("file<script>.js") == "filescript.js"
assert _sanitize_file_path_component("test;rm -rf /") == "testrm-rf"
def test_empty_after_sanitize(self):
"""Completely invalid input returns empty string."""
from plugin.adapter import _sanitize_file_path_component
assert _sanitize_file_path_component("../../../") == "......"
assert _sanitize_file_path_component(" ") == ""
def test_file_id_sanitized(self):
"""File IDs with special chars are sanitized."""
from plugin.adapter import _sanitize_file_path_component
assert _sanitize_file_path_component("abc123/../../etc") == "abc123....etc"
assert _sanitize_file_path_component("file-id_123") == "file-id_123"
class TestDownloadFileSecurity(unittest.TestCase):
"""P1 FB-08: download_file sanitizes inputs and caps response size."""
def test_rejects_empty_file_id_after_sanitize(self):
"""download_file returns None when file_id sanitizes to empty."""
from plugin.adapter import RocketChatREST
rest = RocketChatREST("https://chat.example.com")
rest.auth_token = "token"
rest.user_id = "user1"
# file_id is only special chars → sanitizes to empty
result = rest.download_file(" ", "test.txt")
assert result is None
def test_rejects_empty_filename_after_sanitize(self):
"""download_file returns None when filename sanitizes to empty."""
from plugin.adapter import RocketChatREST
rest = RocketChatREST("https://chat.example.com")
rest.auth_token = "token"
rest.user_id = "user1"
result = rest.download_file("abc123", " ")
assert result is None
def test_url_encoded_path_components(self):
"""URL path components are sanitized then percent-encoded."""
from plugin.adapter import RocketChatREST
rest = RocketChatREST("https://chat.example.com")
rest.auth_token = "token"
rest.user_id = "user1"
with patch("urllib.request.urlopen") as mock_urlopen:
mock_resp = MagicMock()
mock_resp.read.side_effect = [b"hello", b""]
mock_resp.__enter__ = MagicMock(return_value=mock_resp)
mock_resp.__exit__ = MagicMock(return_value=False)
mock_urlopen.return_value = mock_resp
# Spaces are stripped by sanitizer, but the URL should still
# be properly constructed with sanitized values
result = rest.download_file("abc 123", "my file.txt")
assert result == "hello"
# Verify the URL was constructed with sanitized values
call_args = mock_urlopen.call_args
req = call_args[0][0]
url = req.full_url if hasattr(req, 'full_url') else req.get_full_url()
# Sanitized: "abc 123" → "abc123", "my file.txt" → "myfile.txt"
assert "/file-upload/abc123/myfile.txt" in url
def test_response_size_capped(self):
"""Response larger than max_size is truncated."""
from plugin.adapter import RocketChatREST
rest = RocketChatREST("https://chat.example.com")
rest.auth_token = "token"
rest.user_id = "user1"
big_data = b"x" * 200_000 # 200KB
with patch("urllib.request.urlopen") as mock_urlopen:
mock_resp = MagicMock()
# Simulate read(size) — return at most `size` bytes per call
remaining = [big_data]
def mock_read(size=-1):
if not remaining:
return b""
chunk = remaining[0]
if size < 0 or size >= len(chunk):
remaining.clear()
return chunk
remaining[0] = chunk[size:]
return chunk[:size]
mock_resp.read = mock_read
mock_resp.__enter__ = MagicMock(return_value=mock_resp)
mock_resp.__exit__ = MagicMock(return_value=False)
mock_urlopen.return_value = mock_resp
# max_size=50KB
result = rest.download_file("abc", "test.txt", max_size=50_000)
assert result is not None
assert len(result.encode("utf-8")) <= 50_000
def test_no_auth_returns_none(self):
"""download_file returns None without auth_token."""
from plugin.adapter import RocketChatREST
rest = RocketChatREST("https://chat.example.com")
result = rest.download_file("abc", "test.txt")
assert result is None
if __name__ == "__main__":
unittest.main()