diff --git a/plugin/adapter.py b/plugin/adapter.py index 692b873..2500e72 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -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: diff --git a/tests/test_p1_fb08_file_security.py b/tests/test_p1_fb08_file_security.py new file mode 100644 index 0000000..9d8c5db --- /dev/null +++ b/tests/test_p1_fb08_file_security.py @@ -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