diff --git a/src/vice_core/adapters/python_ast.py b/src/vice_core/adapters/python_ast.py index e9ddb17..9cb70d9 100644 --- a/src/vice_core/adapters/python_ast.py +++ b/src/vice_core/adapters/python_ast.py @@ -10,6 +10,7 @@ from collections.abc import Callable, Sequence from vice_core.adapters.base import CompilerDescriptor +from vice_core.adapters.python_dis import MAX_PYTHON_SOURCE_BYTES, _truncate_utf8_lines from vice_core.parsers.diagnostics import parse_diagnostics as parse_stderr_diagnostics from vice_core.parsers.gas import ParsedAssembly from vice_core.parsers.python_ast import format_python_ast_to_text, parse_python_ast_text @@ -85,6 +86,14 @@ def execute( ) filename = req.source_path or "" + if len(req.source_text.encode("utf-8")) > MAX_PYTHON_SOURCE_BYTES: + return RunResult( + exit_code=1, + stdout="", + stderr=f"{filename}:1:1: error: Python source exceeds safety limit ({MAX_PYTHON_SOURCE_BYTES} bytes)\n", + compile_ms=int((time.perf_counter() - start) * 1000), + raw_bytes=0, + ) try: text = format_python_ast_to_text(req.source_text, filename=filename) except SyntaxError as exc: @@ -99,27 +108,22 @@ def execute( compile_ms=int((time.perf_counter() - start) * 1000), raw_bytes=0, ) - except ValueError as exc: + except (ValueError, RecursionError, MemoryError) as exc: return RunResult( exit_code=1, stdout="", - stderr=f"{filename}:1:1: error: {exc}\n", + stderr=f"{filename}:1:1: error: {type(exc).__name__}: {exc}\n", compile_ms=int((time.perf_counter() - start) * 1000), raw_bytes=0, ) - encoded = text.encode("utf-8") - truncated = False - if len(encoded) > req.max_output_bytes: - encoded = encoded[: req.max_output_bytes] - text = encoded.decode("utf-8", errors="replace") - truncated = True + text, raw_bytes, truncated = _truncate_utf8_lines(text, req.max_output_bytes) return RunResult( exit_code=0, stdout=text, stderr="", compile_ms=int((time.perf_counter() - start) * 1000), - raw_bytes=len(encoded), + raw_bytes=raw_bytes, truncated=truncated, ) diff --git a/src/vice_core/adapters/python_dis.py b/src/vice_core/adapters/python_dis.py index 40c0874..50aa3cb 100644 --- a/src/vice_core/adapters/python_dis.py +++ b/src/vice_core/adapters/python_dis.py @@ -20,6 +20,19 @@ from vice_core.runner import RunResult from vice_core.schema import CommandSpec, CompileRequest, CompilerInfo, Diagnostic +MAX_PYTHON_SOURCE_BYTES: int = 2 * 1024 * 1024 + + +def _truncate_utf8_lines(text: str, max_bytes: int) -> tuple[str, int, bool]: + encoded = text.encode("utf-8") + if len(encoded) <= max_bytes: + return text, len(encoded), False + cut = encoded[:max_bytes] + nl = cut.rfind(b"\n") + if nl > 0: + cut = cut[: nl + 1] + return cut.decode("utf-8", errors="ignore"), len(cut), True + class PythonDisAdapter: """Statically compiles Python source into CPython bytecode without executing it.""" @@ -105,6 +118,15 @@ def execute( elif "-O" in spec.argv: opt = 1 filename = req.source_path or "" + if len(req.source_text.encode("utf-8")) > MAX_PYTHON_SOURCE_BYTES: + elapsed_ms = int((time.perf_counter() - start) * 1000) + return RunResult( + exit_code=1, + stdout="", + stderr=f"{filename}:1:1: error: Python source exceeds safety limit ({MAX_PYTHON_SOURCE_BYTES} bytes)\n", + compile_ms=elapsed_ms, + raw_bytes=0, + ) try: text = disassemble_python_to_text( @@ -126,10 +148,9 @@ def execute( compile_ms=elapsed_ms, raw_bytes=0, ) - except ValueError as exc: - # E.g. source code string cannot contain null bytes + except (ValueError, RecursionError, MemoryError) as exc: elapsed_ms = int((time.perf_counter() - start) * 1000) - stderr = f"{filename}:1:1: error: {exc}\n" + stderr = f"{filename}:1:1: error: {type(exc).__name__}: {exc}\n" return RunResult( exit_code=1, stdout="", @@ -138,19 +159,14 @@ def execute( raw_bytes=0, ) - encoded = text.encode("utf-8") - truncated = False - if len(encoded) > req.max_output_bytes: - encoded = encoded[: req.max_output_bytes] - text = encoded.decode("utf-8", errors="replace") - truncated = True + text, raw_bytes, truncated = _truncate_utf8_lines(text, req.max_output_bytes) elapsed_ms = int((time.perf_counter() - start) * 1000) return RunResult( exit_code=0, stdout=text, stderr="", compile_ms=elapsed_ms, - raw_bytes=len(encoded), + raw_bytes=raw_bytes, truncated=truncated, ) diff --git a/src/vice_core/compile_db.py b/src/vice_core/compile_db.py index a597071..38fd475 100644 --- a/src/vice_core/compile_db.py +++ b/src/vice_core/compile_db.py @@ -15,11 +15,35 @@ import json import shlex import sys +import threading from dataclasses import dataclass from pathlib import Path from typing import Any -from vice_core.config import WorkspaceTrustStore, canonical_key +from vice_core.config import WorkspaceTrustStore, bytes_sha256, canonical_key + +MAX_RSP_BYTES: int = 1 * 1024 * 1024 +MAX_DB_CACHE_ENTRIES: int = 64 + +# Flags that take a separate argument whose value must NOT be mistaken for a source file. +_KEEP_FLAGS_WITH_ARG: frozenset[str] = frozenset( + { + "-I", + "-isystem", + "-iquote", + "-include", + "-imacros", + "-D", + "-U", + "-x", + "-target", + "-arch", + "-sysroot", + "--sysroot", + "-isysroot", + "-F", + } +) # Flags taking a single separate argument that must be removed for assembly output. _FLAGS_WITH_ARG: frozenset[str] = frozenset( @@ -56,7 +80,6 @@ # Prefixes for attached-value flags to strip. _STRIP_PREFIXES: tuple[str, ...] = ( - "-o", "-flto=", "-Werror=", "-save-temps=", @@ -78,16 +101,18 @@ class CompileDbMatch: @dataclass class _CachedDb: - mtime_ns: int + content_hash: str entries_by_file: dict[str, dict[str, Any]] _DB_CACHE: dict[str, _CachedDb] = {} +_DB_CACHE_LOCK = threading.Lock() def clear_compile_db_cache() -> None: """Clear the in-memory ``compile_commands.json`` cache (useful for tests).""" - _DB_CACHE.clear() + with _DB_CACHE_LOCK: + _DB_CACHE.clear() def _split_windows_command_line(cmd: str) -> list[str]: @@ -148,15 +173,35 @@ def split_command_line(cmd: str, *, is_windows: bool | None = None) -> list[str] return shlex.split(cmd, posix=True) +def _is_within_any_root(candidate: Path, roots: tuple[Path, ...]) -> bool: + try: + resolved = candidate.resolve() + except OSError: + return False + for root in roots: + try: + resolved.relative_to(root.resolve()) + return True + except ValueError: + continue + except OSError: + continue + return False + + def _expand_response_files( tokens: list[str], directory: Path, *, is_windows: bool | None = None, + trust_store: WorkspaceTrustStore | None = None, + allowed_roots: tuple[Path, ...] | None = None, + untrusted_out: list[Path] | None = None, depth: int = 0, ) -> list[str]: if depth > 4: - return tokens + return [tok for tok in tokens if not (tok.startswith("@") and len(tok) > 1)] + roots = allowed_roots if allowed_roots is not None else (directory,) expanded: list[str] = [] for tok in tokens: if tok.startswith("@") and len(tok) > 1: @@ -164,18 +209,40 @@ def _expand_response_files( rsp_path = Path(rsp_raw) if not rsp_path.is_absolute(): rsp_path = directory / rsp_path - if rsp_path.is_file(): - content = rsp_path.read_text(encoding="utf-8", errors="replace") - sub_tokens = split_command_line(content, is_windows=is_windows) - expanded.extend( - _expand_response_files( - sub_tokens, - directory, - is_windows=is_windows, - depth=depth + 1, - ) - ) + # Security: block path traversal outside allowed project/build roots. + if not _is_within_any_root(rsp_path, roots): + if untrusted_out is not None: + untrusted_out.append(rsp_path) + continue + if not rsp_path.is_file(): continue + if trust_store is not None: + trusted_bytes = trust_store.read_trusted_bytes(rsp_path, max_bytes=MAX_RSP_BYTES) + if trusted_bytes is None: + if untrusted_out is not None: + untrusted_out.append(rsp_path.resolve()) + continue + content = trusted_bytes.decode("utf-8", errors="replace") + else: + try: + if rsp_path.stat().st_size > MAX_RSP_BYTES: + continue + content = rsp_path.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + sub_tokens = split_command_line(content, is_windows=is_windows) + expanded.extend( + _expand_response_files( + sub_tokens, + directory, + is_windows=is_windows, + trust_store=trust_store, + allowed_roots=roots, + untrusted_out=untrusted_out, + depth=depth + 1, + ) + ) + continue expanded.append(tok) return expanded @@ -197,13 +264,23 @@ def sanitize_compile_db_args( source_file: str, directory: Path, is_windows: bool | None = None, + trust_store: WorkspaceTrustStore | None = None, + allowed_roots: tuple[Path, ...] | None = None, + untrusted_out: list[Path] | None = None, ) -> tuple[str, ...]: """Strip compiler executable, input file, and incompatible build flags.""" if not raw_args: return () # Drop argv[0] (the compiler executable itself). - tokens = _expand_response_files(raw_args[1:], directory, is_windows=is_windows) + tokens = _expand_response_files( + raw_args[1:], + directory, + is_windows=is_windows, + trust_store=trust_store, + allowed_roots=allowed_roots, + untrusted_out=untrusted_out, + ) target_norm = _norm_compare(source_file, directory) target_name = Path(source_file).name.lower() @@ -217,12 +294,20 @@ def sanitize_compile_db_args( idx += 2 continue + if tok in _KEEP_FLAGS_WITH_ARG and idx + 1 < n: + sanitized.append(tok) + sanitized.append(tokens[idx + 1]) + idx += 2 + continue + if tok in _STANDALONE_STRIP_FLAGS: idx += 1 continue - # Handle attached forms like -ofoo.o or -flto=thin, being careful not to strip -O2! - if any(tok.startswith(prefix) and len(tok) > len(prefix) for prefix in _STRIP_PREFIXES): + # Handle attached forms like -ofoo.o or -flto=thin without stripping -O2 or -objc*. + if (tok.startswith("-o") and len(tok) > 2 and not tok.startswith("-obj")) or any( + tok.startswith(prefix) and len(tok) > len(prefix) for prefix in _STRIP_PREFIXES + ): idx += 1 continue @@ -252,14 +337,15 @@ def find_compile_commands(start_path: Path) -> Path | None: return None -def _load_cached_db(db_path: Path) -> dict[str, dict[str, Any]]: +def _load_cached_db(db_path: Path, trusted_bytes: bytes) -> dict[str, dict[str, Any]]: key = canonical_key(db_path) - mtime_ns = db_path.stat().st_mtime_ns - cached = _DB_CACHE.get(key) - if cached is not None and cached.mtime_ns == mtime_ns: - return cached.entries_by_file + content_hash = bytes_sha256(trusted_bytes) + with _DB_CACHE_LOCK: + cached = _DB_CACHE.get(key) + if cached is not None and cached.content_hash == content_hash: + return cached.entries_by_file - raw = json.loads(db_path.read_text(encoding="utf-8")) + raw = json.loads(trusted_bytes.decode("utf-8")) if not isinstance(raw, list): raise ValueError("compile_commands.json root must be a JSON array") @@ -274,7 +360,10 @@ def _load_cached_db(db_path: Path) -> dict[str, dict[str, Any]]: norm_key = _norm_compare(file_val, Path(dir_val)) index[norm_key] = entry - _DB_CACHE[key] = _CachedDb(mtime_ns=mtime_ns, entries_by_file=index) + with _DB_CACHE_LOCK: + if len(_DB_CACHE) >= MAX_DB_CACHE_ENTRIES: + _DB_CACHE.clear() + _DB_CACHE[key] = _CachedDb(content_hash=content_hash, entries_by_file=index) return index @@ -286,17 +375,19 @@ def lookup_compile_flags( ) -> tuple[CompileDbMatch | None, Path | None]: """Look up sanitized flags for ``source_path`` from a TRUSTED ``compile_commands.json``. - Returns ``(match, untrusted_db_path)``. + Returns ``(match, untrusted_path)``. Any referenced ``@file.rsp`` response + files must also reside inside the project/build directory and be trusted. """ resolved_db = db_path or find_compile_commands(source_path) if resolved_db is None or not resolved_db.is_file(): return None, None store = trust_store or WorkspaceTrustStore() - if not store.is_trusted(resolved_db): - return None, resolved_db + trusted_bytes = store.read_trusted_bytes(resolved_db) + if trusted_bytes is None: + return None, resolved_db.resolve() - entries = _load_cached_db(resolved_db) + entries = _load_cached_db(resolved_db, trusted_bytes) lookup_key = _norm_compare(str(source_path), source_path.parent) entry = entries.get(lookup_key) if entry is None: @@ -310,11 +401,17 @@ def lookup_compile_flags( else: return None, None + untrusted_rsps: list[Path] = [] sanitized = sanitize_compile_db_args( raw_args, source_file=str(entry["file"]), directory=directory, + trust_store=store, + allowed_roots=(directory, resolved_db.parent), + untrusted_out=untrusted_rsps, ) + if untrusted_rsps: + return None, untrusted_rsps[0] return ( CompileDbMatch( directory=str(directory), diff --git a/src/vice_core/config.py b/src/vice_core/config.py index a0a342b..f4ba902 100644 --- a/src/vice_core/config.py +++ b/src/vice_core/config.py @@ -11,10 +11,12 @@ from __future__ import annotations +import contextlib import hashlib import json import os import sys +import tempfile import tomllib from dataclasses import dataclass from pathlib import Path @@ -83,6 +85,11 @@ def default_user_state_dir() -> Path: return Path.home() / ".local" / "state" / "vice" +def bytes_sha256(data: bytes) -> str: + """Compute SHA-256 hex digest of an in-memory byte buffer.""" + return hashlib.sha256(data).hexdigest() + + def file_sha256(path: Path) -> str: """Compute SHA-256 hex digest of a file's bytes.""" h = hashlib.sha256() @@ -123,20 +130,52 @@ def _load(self) -> dict[str, str]: def _save(self, entries: dict[str, str]) -> None: self._path.parent.mkdir(parents=True, exist_ok=True) - self._path.write_text( - json.dumps(entries, indent=2, sort_keys=True) + "\n", - encoding="utf-8", - ) - - def is_trusted(self, config_file: Path) -> bool: - """Return True iff ``config_file`` exists and its exact SHA-256 hash is trusted.""" + payload = json.dumps(entries, indent=2, sort_keys=True) + "\n" + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=self._path.parent, + prefix=".trust_", + suffix=".tmp", + delete=False, + ) as fh: + tmp_path = Path(fh.name) + fh.write(payload) + fh.flush() + os.replace(tmp_path, self._path) + finally: + if tmp_path is not None and tmp_path.exists(): + with contextlib.suppress(OSError): + tmp_path.unlink() + + def read_trusted_bytes( + self, config_file: Path, *, max_bytes: int = 8 * 1024 * 1024 + ) -> bytes | None: + """Read ``config_file`` once and return its exact bytes ONLY if its SHA-256 is trusted. + + Eliminates TOCTOU windows between trust verification and parsing. + """ if not config_file.is_file(): - return False + return None entries = self._load() expected = entries.get(canonical_key(config_file)) if not expected: - return False - return expected == file_sha256(config_file) + return None + try: + if config_file.stat().st_size > max_bytes: + return None + data = config_file.read_bytes() + except OSError: + return None + if bytes_sha256(data) != expected: + return None + return data + + def is_trusted(self, config_file: Path) -> bool: + """Return True iff ``config_file`` exists and its exact SHA-256 hash is trusted.""" + return self.read_trusted_bytes(config_file) is not None def trust(self, config_file: Path) -> str: """Record ``config_file``'s current SHA-256 hash as trusted and return the digest.""" @@ -258,10 +297,11 @@ def load_project_config( return None, None store = trust_store or WorkspaceTrustStore() - if not store.is_trusted(cfg_path): + trusted_bytes = store.read_trusted_bytes(cfg_path) + if trusted_bytes is None: return None, cfg_path - raw = tomllib.loads(cfg_path.read_text(encoding="utf-8")) + raw = tomllib.loads(trusted_bytes.decode("utf-8")) # Hard security boundary: repository .vice.toml may NEVER define compilers or executables. forbidden_keys = {"compilers", "compiler_command", "executable", "command", "commands"} diff --git a/src/vice_core/mcp_server.py b/src/vice_core/mcp_server.py index 0577c93..19b1017 100644 --- a/src/vice_core/mcp_server.py +++ b/src/vice_core/mcp_server.py @@ -22,7 +22,40 @@ from vice_core.schema import CompileRequest, SyntaxFlavor MCP_PROTOCOL_VERSION = "2024-11-05" +SUPPORTED_MCP_VERSIONS: frozenset[str] = frozenset({"2024-11-05", "2025-03-26", "2025-06-18"}) JSONRPC_VERSION = "2.0" +MAX_MCP_LINE_BYTES = 16 * 1024 * 1024 + +_BLOCKED_MCP_EXACT_FLAGS: frozenset[str] = frozenset( + { + "-o", + "-d", + "-Xclang", + "-plugin", + "--plugin", + "-processor", + "-processorpath", + "--out-dir", + "-save-temps", + "/Fo", + "/Fa", + "/Fe", + "/Fd", + } +) +_BLOCKED_MCP_FLAG_PREFIXES: tuple[str, ...] = ( + "-fplugin", + "-specs=", + "-femit-bin=", + "-femit-asm=", + "--out-dir=", + "-o", + "/Fo", + "/Fa", + "/Fe", + "/Fd", + "@", +) ERR_PARSE = -32700 ERR_INVALID_REQUEST = -32600 @@ -121,7 +154,29 @@ def _as_str_tuple(raw: Any) -> tuple[str, ...]: return () if not isinstance(raw, list) or not all(isinstance(x, str) for x in raw): raise ValueError("Expected a list of strings for compiler args") - return tuple(raw) + args = tuple(raw) + _validate_mcp_extra_args(args) + return args + + +def _validate_mcp_extra_args(args: tuple[str, ...]) -> None: + """Block compiler flags that write arbitrary host files or load plugins via MCP.""" + for arg in args: + if arg in _BLOCKED_MCP_EXACT_FLAGS: + raise ValueError(f"Disallowed compiler flag in MCP request: {arg!r}") + for prefix in _BLOCKED_MCP_FLAG_PREFIXES: + if prefix == "-o" and arg.startswith("-obj"): + continue + if arg.startswith(prefix) and len(arg) > len(prefix): + raise ValueError(f"Disallowed compiler flag in MCP request: {arg!r}") + + +def _as_bool(raw: Any, *, default: bool = True, field_name: str = "flag") -> bool: + if raw is None: + return default + if not isinstance(raw, bool): + raise ValueError(f"Expected boolean for {field_name!r}, got {type(raw).__name__}") + return raw def _as_syntax(raw: Any) -> SyntaxFlavor: @@ -196,7 +251,7 @@ def _call_tool(self, name: str, arguments: Mapping[str, Any]) -> dict[str, Any]: compiler_id=str(arguments.get("compiler_id", "auto")), extra_args=_as_str_tuple(arguments.get("extra_args")), syntax=_as_syntax(arguments.get("syntax")), - demangle=bool(arguments.get("demangle", True)), + demangle=_as_bool(arguments.get("demangle"), default=True, field_name="demangle"), ) res = compile_source(req, registry=self._registry, trust_store=self._trust_store) res_dict = res.to_dict() @@ -215,7 +270,7 @@ def _call_tool(self, name: str, arguments: Mapping[str, Any]) -> dict[str, Any]: ) ft = str(arguments["filetype"]) if arguments.get("filetype") is not None else None syntax = _as_syntax(arguments.get("syntax")) - demangle = bool(arguments.get("demangle", True)) + demangle = _as_bool(arguments.get("demangle"), default=True, field_name="demangle") left_req = CompileRequest( source_text=source_text, @@ -289,7 +344,11 @@ def handle_line(self, raw_line: bytes, out: BinaryIO) -> None: if method == "initialize": client_proto = params.get("protocolVersion") - proto = str(client_proto) if isinstance(client_proto, str) else MCP_PROTOCOL_VERSION + proto = ( + client_proto + if isinstance(client_proto, str) and client_proto in SUPPORTED_MCP_VERSIONS + else MCP_PROTOCOL_VERSION + ) self._send_result( out, req_id, @@ -338,9 +397,21 @@ def handle_line(self, raw_line: bytes, out: BinaryIO) -> None: def serve(self, inp: BinaryIO, out: BinaryIO) -> int: while True: - raw_line = inp.readline() + raw_line = inp.readline(MAX_MCP_LINE_BYTES + 1) if not raw_line: break + if len(raw_line) > MAX_MCP_LINE_BYTES and not raw_line.endswith(b"\n"): + while True: + chunk = inp.readline(65536) + if not chunk or chunk.endswith(b"\n"): + break + self._send_error( + out, + None, + ERR_INVALID_REQUEST, + f"MCP request exceeds limit ({MAX_MCP_LINE_BYTES} bytes)", + ) + continue self.handle_line(raw_line, out) return 0 diff --git a/src/vice_core/rpc.py b/src/vice_core/rpc.py index 268ba87..f70f895 100644 --- a/src/vice_core/rpc.py +++ b/src/vice_core/rpc.py @@ -27,6 +27,7 @@ from vice_core.schema import SCHEMA_VERSION, CompileRequest JSONRPC_VERSION = "2.0" +MAX_RPC_LINE_BYTES = 16 * 1024 * 1024 ERR_PARSE = -32700 ERR_INVALID_REQUEST = -32600 @@ -191,7 +192,8 @@ def _worker() -> None: on_process_start=job.attach_process, ) if job.cancel_event.is_set(): - self._send_error(out, req_id, ERR_CANCELLED, "Compilation cancelled") + if req_id is not None: + self._send_error(out, req_id, ERR_CANCELLED, "Compilation cancelled") else: self._send_result(out, req_id, result.to_dict()) except Exception as exc: # pragma: no cover - defensive RPC boundary @@ -349,9 +351,22 @@ def serve(self, inp: BinaryIO, out: BinaryIO) -> int: """Read NDJSON requests until EOF or ``shutdown``, waiting cleanly for workers.""" try: while not self._shutdown.is_set(): - raw_line = inp.readline() + raw_line = inp.readline(MAX_RPC_LINE_BYTES + 1) if not raw_line: break + if len(raw_line) > MAX_RPC_LINE_BYTES and not raw_line.endswith(b"\n"): + # Drain remainder of oversized line cleanly. + while True: + chunk = inp.readline(65536) + if not chunk or chunk.endswith(b"\n"): + break + self._send_error( + out, + None, + ERR_INVALID_REQUEST, + f"JSON-RPC request exceeds limit ({MAX_RPC_LINE_BYTES} bytes)", + ) + continue should_continue = self.handle_line(raw_line, out) if not should_continue: break diff --git a/tests/unit/test_mcp_server.py b/tests/unit/test_mcp_server.py index 2eb9437..0862bc4 100644 --- a/tests/unit/test_mcp_server.py +++ b/tests/unit/test_mcp_server.py @@ -102,3 +102,79 @@ def test_mcp_stdio_compile_and_compare_live_clang(tmp_path: Path) -> None: assert ( sc["semantic_diff"]["summary"]["left_total"] > sc["semantic_diff"]["summary"]["right_total"] ) + + +def test_mcp_security_guards_and_python_dos_protection() -> None: + srv = McpServer() + + def _call(msg: dict[str, object]) -> dict[str, object]: + out = io.BytesIO() + srv.handle_line((json.dumps(msg) + "\n").encode("utf-8"), out) + return dict(json.loads(out.getvalue().decode("utf-8"))) + + # Unsupported protocolVersion falls back to MCP_PROTOCOL_VERSION + init_resp = _call( + { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": {"protocolVersion": "1999-01-01"}, + } + ) + assert init_resp["result"]["protocolVersion"] == "2024-11-05" # type: ignore[index] + + # String "false" for boolean demangle must be rejected (not silently coerced to True) + bad_bool = _call( + { + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "compile_code", + "arguments": { + "source_text": "x = 1\n", + "compiler_id": "python-dis", + "demangle": "false", + }, + }, + } + ) + assert "error" in bad_bool + assert bad_bool["error"]["code"] == -32602 # type: ignore[index] + + # Dangerous flags (-fplugin=, -o, @rsp) must be rejected by MCP + for bad_flag in ("-fplugin=./evil.so", "-o", "/Foevil.obj", "@evil.rsp", "-processor"): + blocked = _call( + { + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "compile_code", + "arguments": { + "source_text": "int f() { return 1; }\n", + "compiler_id": "clang", + "extra_args": [bad_flag], + }, + }, + } + ) + assert "error" in blocked, f"Expected {bad_flag!r} to be blocked" + assert blocked["error"]["code"] == -32602 # type: ignore[index] + + # Deeply nested Python code must return compile_error cleanly (not crash server) + deep_expr = "(" * 2500 + "1" + ")" * 2500 + for cid in ("python-dis", "python-ast"): + res = _call( + { + "jsonrpc": "2.0", + "id": 4, + "method": "tools/call", + "params": { + "name": "compile_code", + "arguments": {"source_text": deep_expr, "compiler_id": cid}, + }, + } + ) + assert "result" in res + assert res["result"]["isError"] is True # type: ignore[index] diff --git a/tests/unit/test_trust_and_compile_db.py b/tests/unit/test_trust_and_compile_db.py index 751efa3..46a2955 100644 --- a/tests/unit/test_trust_and_compile_db.py +++ b/tests/unit/test_trust_and_compile_db.py @@ -143,3 +143,73 @@ def test_compile_db_lookup_trust_gating_and_caching(tmp_path: Path) -> None: assert match is not None assert match.args == ("-std=c++20", "-O3", "-DMY_MACRO=42") assert Path(match.directory) == repo + + +def test_rsp_trust_enforcement_and_path_traversal_blocked(tmp_path: Path) -> None: + clear_compile_db_cache() + store = WorkspaceTrustStore(tmp_path / "state/trust.json") + repo = tmp_path / "repo" + repo.mkdir() + src = repo / "app.cpp" + src.write_text("int f() { return 1; }\n", encoding="utf-8") + + outside_rsp = tmp_path / "outside.rsp" + outside_rsp.write_text("-fplugin=evil.so", encoding="utf-8") + + local_rsp = repo / "flags.rsp" + local_rsp.write_text("-DMACRO=1 -O2", encoding="utf-8") + + db = repo / "compile_commands.json" + db.write_text( + json.dumps( + [ + { + "directory": str(repo), + "file": str(src), + "arguments": ["clang++", "@flags.rsp", "-c", str(src)], + } + ] + ), + encoding="utf-8", + ) + store.trust(db) + + # Trusting compile_commands.json alone MUST NOT blindly expand untrusted flags.rsp! + match, untrusted = lookup_compile_flags(src, trust_store=store) + assert match is None + assert untrusted == local_rsp.resolve() + + # Once flags.rsp is trusted, it expands safely. + store.trust(local_rsp) + match, untrusted = lookup_compile_flags(src, trust_store=store) + assert untrusted is None + assert match is not None + assert match.args == ("-DMACRO=1", "-O2") + + # Mutating flags.rsp invalidates trust immediately! + local_rsp.write_text("-fplugin=./evil.so", encoding="utf-8") + match2, untrusted2 = lookup_compile_flags(src, trust_store=store) + assert match2 is None + assert untrusted2 == local_rsp.resolve() + + # Path traversal @../outside.rsp MUST be blocked even if outside_rsp were trusted. + store.trust(outside_rsp) + untrusted_list: list[Path] = [] + sanitized = sanitize_compile_db_args( + ["clang++", "@../outside.rsp", "-objc-arc", "-include", "app.cpp", str(src)], + source_file=str(src), + directory=repo, + trust_store=store, + allowed_roots=(repo,), + untrusted_out=untrusted_list, + ) + assert len(untrusted_list) == 1 + assert "-fplugin=evil.so" not in sanitized + assert "-objc-arc" in sanitized + assert "-include" in sanitized + assert "app.cpp" in sanitized + + # Verify atomic revoke & list_trusted + assert store.revoke(local_rsp) is True + assert store.revoke(local_rsp) is False + assert len(store.list_trusted()) >= 1