diff --git a/README.md b/README.md index 84a9c31..88fcc08 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ It executes a bounded request on a disposable GitHub-hosted Ubuntu runner and re - Manual `workflow_dispatch` only for target execution. - Public GitHub repositories at an exact 40-character commit SHA only. - v1 adapter: `node_stdio` with `package-lock.json` and frozen `npm ci` installation. -- v1 action profile: `mcp_initialize`. +- v1 action profile: legacy `mcp_initialize` for protocol version `2025-06-18` only. - v1 network mode: `OPEN` only. - Credentials: `NONE`; public/synthetic data only. - Target acquisition, install hooks, and runtime execute as a dedicated unprivileged OS user. @@ -31,19 +31,25 @@ Run **Actions → Bounded MCP runtime review → Run workflow** and supply one ` v1 supports one executable stop condition: `output_capture_limit`. Any unknown stop condition is rejected as unsupported rather than interpreted as free-form instructions. -For `mcp_initialize`, the harness starts the stdio server, sends `initialize`, waits for the matching JSON-RPC response, sends `notifications/initialized`, and then terminates the disposable target process tree itself. A normal long-lived MCP server is therefore not expected to exit after initialization. +For `mcp_initialize`, the harness starts the stdio server, sends `initialize` with protocol version `2025-06-18`, waits for the matching JSON-RPC response, validates the legacy `InitializeResult` shape and negotiated protocol version, sends `notifications/initialized`, and then terminates the disposable target process tree itself. A normal long-lived MCP server is therefore not expected to exit after initialization. + +The v1 profile is intentionally legacy-only. Servers that require a newer/stateless MCP protocol revision are outside this action profile and must not be interpreted as unsafe merely because this profile cannot validate them. ## Result The workflow uploads `mcp-runtime-result/result.json` for three days. Execution states are evidence states only: `COMPLETED`, `TARGET_FAILED`, `TIMEOUT`, `STOPPED`, `RUNTIME_UNSUPPORTED`, or `HARNESS_ERROR`. +`COMPLETED` means the selected bounded action profile completed according to its implemented contract; it is not a security verdict. + The result records request scope, environment/isolation assumptions, exact commit, Node/npm/lockfile provenance, collectors and limitations, bounded observations, stop-condition state, and errors. It never emits a security verdict. +Filesystem observations are phase-separated: install-time changes are reported as `INSTALL`, while target runtime changes are reported as `EXERCISE`. Each list remains bounded and records its limitation. + ## Controlled fixtures CI validates the harness against this repository's exact commit using `fixtures/safe/server.js`, `fixtures/noisy/server.js`, and `fixtures/failure/server.js`. -The fixture job verifies the persistent MCP initialize lifecycle, process cleanup, trusted-checkout isolation, filesystem observations, process/network traces, and timeout behavior before changes are accepted on `main`. +The fixture job verifies the persistent MCP initialize lifecycle, receipt of `notifications/initialized`, process cleanup, trusted-checkout isolation, phase-separated filesystem observations, process/network traces, and timeout behavior before changes are accepted on `main`. ## Development diff --git a/fixtures/safe/server.js b/fixtures/safe/server.js index bb1e038..bc58d6d 100644 --- a/fixtures/safe/server.js +++ b/fixtures/safe/server.js @@ -6,7 +6,6 @@ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity rl.on('line', (line) => { const message = JSON.parse(line); if (message.method === 'initialize') { - fs.writeFileSync('safe-fixture-output.txt', 'initialized\n'); process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, @@ -17,4 +16,7 @@ rl.on('line', (line) => { } }) + '\n'); } + if (message.method === 'notifications/initialized') { + fs.writeFileSync('safe-fixture-initialized.txt', 'initialized notification received\n'); + } }); diff --git a/runner/run_review.py b/runner/run_review.py index 7825b04..0037d28 100644 --- a/runner/run_review.py +++ b/runner/run_review.py @@ -31,6 +31,7 @@ OUTPUT_LIMIT = 256 * 1024 PHASE_LIMITS = {"ACQUIRE": 120, "INSTALL": 180, "START": 60, "EXERCISE": 120, "STOP": 30} CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x1b]") +SUPPORTED_PROTOCOL_VERSION = "2025-06-18" class PhaseTimeout(RuntimeError): @@ -57,6 +58,27 @@ def sanitize(text: str, limit: int = 4096) -> str: return text[:limit] +def validate_initialize_response(response: dict) -> dict: + result = response.get("result") + if not isinstance(result, dict): + raise TargetFailure("MCP initialize result must be an object") + if result.get("protocolVersion") != SUPPORTED_PROTOCOL_VERSION: + raise TargetFailure( + "MCP initialize negotiated unsupported protocolVersion: " + + sanitize(str(result.get("protocolVersion"))) + ) + if not isinstance(result.get("capabilities"), dict): + raise TargetFailure("MCP initialize capabilities must be an object") + server_info = result.get("serverInfo") + if not isinstance(server_info, dict): + raise TargetFailure("MCP initialize serverInfo must be an object") + if not isinstance(server_info.get("name"), str) or not server_info["name"].strip(): + raise TargetFailure("MCP initialize serverInfo.name must be a non-empty string") + if not isinstance(server_info.get("version"), str) or not server_info["version"].strip(): + raise TargetFailure("MCP initialize serverInfo.version must be a non-empty string") + return result + + def target_path() -> str: directories = [] for name in ("git", "node", "npm"): @@ -307,7 +329,7 @@ def stderr_pump() -> None: "id": 1, "method": "initialize", "params": { - "protocolVersion": "2025-06-18", + "protocolVersion": SUPPORTED_PROTOCOL_VERSION, "capabilities": {}, "clientInfo": {"name": "mcp-security-runner", "version": "1"}, }, @@ -345,6 +367,7 @@ def stderr_pump() -> None: "MCP initialize returned JSON-RPC error: " + sanitize(json.dumps(response["error"], ensure_ascii=False)) ) + validate_initialize_response(response) try: proc.stdin.write((json.dumps(initialized, separators=(",", ":")) + "\n").encode()) @@ -442,6 +465,22 @@ def snapshot(root: Path) -> dict[str, tuple[int, int]]: return result +def filesystem_observation( + before: dict[str, tuple[int, int]], + after: dict[str, tuple[int, int]], + phase: str, +) -> dict: + changed = sorted(key for key in set(before) | set(after) if before.get(key) != after.get(key))[:1000] + return { + "phase": phase, + "type": "filesystem_changes", + "data": { + "paths": changed, + "limitation": "workspace metadata only; content not captured; first 1000 changed paths", + }, + } + + def parse_traces(phases: Iterable[str], evidence: set[str]) -> list[dict]: observations = [] for phase in phases: @@ -509,12 +548,12 @@ def main() -> int: { "name": "filesystem_snapshot", "categories": sorted(requested & {"filesystem"}), - "limitation": "workspace metadata only; .git excluded", + "limitation": "workspace metadata only; .git excluded; install and exercise changes are separated", }, { "name": "protocol_capture", "categories": sorted(requested & {"protocol"}), - "limitation": "bounded newline-delimited JSON-RPC capture for mcp_initialize only", + "limitation": "bounded newline-delimited JSON-RPC capture for legacy mcp_initialize only", }, ] phases.append("ACQUIRE") @@ -524,7 +563,7 @@ def main() -> int: if not lockfile.is_file(): raise Unsupported("node_stdio requires package-lock.json") result["provenance"]["lockfile_sha256"] = sha256(lockfile) - before = snapshot(WORKSPACE) if "filesystem" in requested else {} + after_acquire = snapshot(WORKSPACE) if "filesystem" in requested else {} rc, node_version, _ = run_bounded(["node", "--version"], "INSTALL", 10) if rc: raise Unsupported("Node.js is unavailable") @@ -549,6 +588,9 @@ def main() -> int: if rc: result["errors"].append({"phase": "INSTALL", "message": sanitize(err or out)}) raise TargetFailure("Target dependency installation failed") + after_install = snapshot(WORKSPACE) if "filesystem" in requested else {} + if "filesystem" in requested: + result["observations"].append(filesystem_observation(after_acquire, after_install, "INSTALL")) entrypoint = contained_entrypoint(req) phases.extend(["START", "EXERCISE"]) out, err, response = run_mcp_initialize( @@ -572,15 +614,8 @@ def main() -> int: status = "COMPLETED" phases.extend(["STOP", "COLLECT"]) if "filesystem" in requested: - after = snapshot(WORKSPACE) - changed = sorted(key for key in set(before) | set(after) if before.get(key) != after.get(key))[:1000] - result["observations"].append( - { - "phase": "COLLECT", - "type": "filesystem_changes", - "data": {"paths": changed, "limitation": "workspace metadata only; content not captured"}, - } - ) + after_exercise = snapshot(WORKSPACE) + result["observations"].append(filesystem_observation(after_install, after_exercise, "EXERCISE")) result["observations"].extend(parse_traces(phases, requested)) except RequestError as exc: status = "RUNTIME_UNSUPPORTED" diff --git a/tests/runtime_fixture_check.py b/tests/runtime_fixture_check.py index 449aa29..33bd9ab 100644 --- a/tests/runtime_fixture_check.py +++ b/tests/runtime_fixture_check.py @@ -93,23 +93,32 @@ def run_fixture(sha: str, name: str, entrypoint: str, timeout: int) -> dict: return result -def observation(result: dict, observation_type: str) -> list[dict]: - return [item for item in result.get("observations", []) if item.get("type") == observation_type] +def observation(result: dict, observation_type: str, phase: str | None = None) -> list[dict]: + items = [item for item in result.get("observations", []) if item.get("type") == observation_type] + if phase is not None: + items = [item for item in items if item.get("phase") == phase] + return items def assert_safe(result: dict) -> None: assert result["execution"]["status"] == "COMPLETED", result - protocol = observation(result, "protocol_output") + protocol = observation(result, "protocol_output", "EXERCISE") assert protocol, result - server_info = protocol[0]["data"]["initialize_response"]["result"]["serverInfo"] - assert server_info["name"] == "safe-fixture", result - filesystem = observation(result, "filesystem_changes") - assert filesystem and "safe-fixture-output.txt" in filesystem[0]["data"]["paths"], result + initialize_result = protocol[0]["data"]["initialize_response"]["result"] + assert initialize_result["protocolVersion"] == "2025-06-18", result + assert initialize_result["capabilities"] == {}, result + assert initialize_result["serverInfo"]["name"] == "safe-fixture", result + install_fs = observation(result, "filesystem_changes", "INSTALL") + exercise_fs = observation(result, "filesystem_changes", "EXERCISE") + assert install_fs, result + assert exercise_fs, result + assert "safe-fixture-initialized.txt" in exercise_fs[0]["data"]["paths"], result + assert "safe-fixture-initialized.txt" not in install_fs[0]["data"]["paths"], result def assert_noisy(result: dict) -> None: assert result["execution"]["status"] == "COMPLETED", result - filesystem = observation(result, "filesystem_changes") + filesystem = observation(result, "filesystem_changes", "EXERCISE") assert filesystem and "noisy-fixture-output.txt" in filesystem[0]["data"]["paths"], result assert observation(result, "process_trace"), result assert observation(result, "network_trace"), result diff --git a/tests/test_validation.py b/tests/test_validation.py index c3b2df3..c3be14b 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -3,7 +3,7 @@ import shutil import unittest -from runner.run_review import sanitize, target_env +from runner.run_review import TargetFailure, sanitize, target_env, validate_initialize_response class ValidationTests(unittest.TestCase): @@ -27,6 +27,62 @@ def test_target_path_contains_trusted_node_directory(self): self.skipTest("node is not installed") self.assertIn(str(Path(node).parent), target_env()["PATH"].split(os.pathsep)) + def test_accepts_valid_legacy_initialize_result(self): + response = { + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "serverInfo": {"name": "fixture", "version": "1"}, + }, + } + result = validate_initialize_response(response) + self.assertEqual(result["protocolVersion"], "2025-06-18") + + def test_rejects_missing_initialize_result_shape(self): + with self.assertRaises(TargetFailure): + validate_initialize_response({"jsonrpc": "2.0", "id": 1, "result": {}}) + + def test_rejects_wrong_negotiated_protocol_version(self): + response = { + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2025-11-25", + "capabilities": {}, + "serverInfo": {"name": "fixture", "version": "1"}, + }, + } + with self.assertRaises(TargetFailure): + validate_initialize_response(response) + + def test_rejects_invalid_capabilities_and_server_info(self): + with self.assertRaises(TargetFailure): + validate_initialize_response( + { + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2025-06-18", + "capabilities": [], + "serverInfo": {"name": "fixture", "version": "1"}, + }, + } + ) + with self.assertRaises(TargetFailure): + validate_initialize_response( + { + "jsonrpc": "2.0", + "id": 1, + "result": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "serverInfo": {}, + }, + } + ) + if __name__ == "__main__": unittest.main()