diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bb0c13c..8949a64 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,28 @@ jobs: with: persist-credentials: false - name: Compile harness - run: python3 -m py_compile runner/*.py + run: python3 -m py_compile runner/*.py tests/runtime_fixture_check.py - name: Run deterministic tests - run: python3 -m unittest discover -s tests -v + run: python3 -m unittest discover -s tests -p "test_*.py" -v + + runtime-fixtures: + needs: deterministic-tests + runs-on: ubuntu-latest + timeout-minutes: 10 + env: + TARGET_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + steps: + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + - name: Install observation dependency + run: | + sudo apt-get update + sudo apt-get install --yes --no-install-recommends strace + - name: Restrict trusted runner workspace + run: | + sudo chmod 700 /home/runner + sudo chmod 700 "$GITHUB_WORKSPACE" + - name: Run controlled runtime fixtures + run: sudo python3 tests/runtime_fixture_check.py --sha "$TARGET_SHA" diff --git a/.github/workflows/runtime-review.yml b/.github/workflows/runtime-review.yml index 55b3bce..18101cf 100644 --- a/.github/workflows/runtime-review.yml +++ b/.github/workflows/runtime-review.yml @@ -38,9 +38,13 @@ jobs: path.chmod(0o600) PY - - name: Run bounded harness + - name: Restrict trusted runner workspace run: | sudo chmod 700 /home/runner + sudo chmod 700 "$GITHUB_WORKSPACE" + + - name: Run bounded harness + run: | sudo python3 runner/run_review.py \ --request-file "$RUNNER_TEMP/request.json" \ --result-file "$RUNNER_TEMP/result.json" diff --git a/README.md b/README.md index cdd1db4..84a9c31 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,8 @@ It executes a bounded request on a disposable GitHub-hosted Ubuntu runner and re - Credentials: `NONE`; public/synthetic data only. - Target acquisition, install hooks, and runtime execute as a dedicated unprivileged OS user. - Target environment is rebuilt from an allowlist and does not inherit GitHub/Actions credentials. -- Target workspace is separate from the trusted harness/result paths. +- The allowlisted PATH includes only trusted runner tool directories required for Git, Node.js, npm, and standard system tools. +- Target workspace is separate from the trusted harness/result paths, and the runtime workflow removes target-user read access to the trusted checkout. - Entrypoints are resolved and checked for workspace containment before execution. - Target stdout/stderr is captured as untrusted data, bounded, and sanitized before inclusion in results. - Process, open-file, file-size, CPU-time, output-volume, phase, and job time limits bound execution. @@ -30,6 +31,8 @@ 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. + ## 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`. @@ -38,15 +41,17 @@ The result records request scope, environment/isolation assumptions, exact commi ## Controlled fixtures -Before using third-party runtime output as security evidence, validate the harness against this repository's exact merged commit using `fixtures/safe/server.js`, `fixtures/noisy/server.js`, and `fixtures/failure/server.js`. All three use the repository-root `package-lock.json`. +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`. ## Development -Deterministic CI compiles the harness and runs standard-library unit tests. It never dispatches arbitrary third-party targets. +Deterministic CI compiles the harness and runs standard-library unit tests. A separate CI job executes only repository-controlled runtime fixtures; it never accepts an arbitrary external target from PR data. ```bash -python3 -m py_compile runner/*.py -python3 -m unittest discover -s tests -v +python3 -m py_compile runner/*.py tests/runtime_fixture_check.py +python3 -m unittest discover -s tests -p "test_*.py" -v ``` Do not add real credentials, private source, customer data, automatic security verdicts, self-hosted runners, or a general arbitrary-command interface. diff --git a/fixtures/noisy/server.js b/fixtures/noisy/server.js index edab960..cffb4f5 100644 --- a/fixtures/noisy/server.js +++ b/fixtures/noisy/server.js @@ -2,12 +2,25 @@ const fs = require('fs'); const https = require('https'); const { spawn } = require('child_process'); const readline = require('readline'); + const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); + rl.on('line', (line) => { - const request = JSON.parse(line); - fs.writeFileSync('noisy-fixture-output.txt', 'unexpected write\n'); - spawn(process.execPath, ['-e', 'setTimeout(()=>{}, 250)'], {stdio:'ignore'}); - https.get('https://example.com/', (res) => res.resume()).on('error', () => {}); - process.stdout.write(JSON.stringify({jsonrpc:'2.0', id:request.id, result:{protocolVersion:'2025-06-18', capabilities:{}, serverInfo:{name:'noisy-fixture', version:'1'}}}) + '\n'); - setTimeout(() => rl.close(), 500); + const message = JSON.parse(line); + if (message.method === 'initialize') { + fs.writeFileSync('noisy-fixture-output.txt', 'unexpected write\n'); + spawn(process.execPath, ['-e', 'setTimeout(()=>{}, 250)'], { stdio: 'ignore' }); + https.get('https://example.com/', (res) => res.resume()).on('error', () => {}); + setTimeout(() => { + process.stdout.write(JSON.stringify({ + jsonrpc: '2.0', + id: message.id, + result: { + protocolVersion: '2025-06-18', + capabilities: {}, + serverInfo: { name: 'noisy-fixture', version: '1' } + } + }) + '\n'); + }, 500); + } }); diff --git a/fixtures/safe/server.js b/fixtures/safe/server.js index c6a294b..bb1e038 100644 --- a/fixtures/safe/server.js +++ b/fixtures/safe/server.js @@ -1,9 +1,20 @@ const fs = require('fs'); const readline = require('readline'); + const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); + rl.on('line', (line) => { - const request = JSON.parse(line); - fs.writeFileSync('safe-fixture-output.txt', 'initialized\n'); - process.stdout.write(JSON.stringify({jsonrpc:'2.0', id:request.id, result:{protocolVersion:'2025-06-18', capabilities:{}, serverInfo:{name:'safe-fixture', version:'1'}}}) + '\n'); - rl.close(); + 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, + result: { + protocolVersion: '2025-06-18', + capabilities: {}, + serverInfo: { name: 'safe-fixture', version: '1' } + } + }) + '\n'); + } }); diff --git a/runner/run_review.py b/runner/run_review.py index 487a0a4..7825b04 100644 --- a/runner/run_review.py +++ b/runner/run_review.py @@ -8,6 +8,7 @@ import pwd import re import signal +import shutil import subprocess import threading import time @@ -31,30 +32,46 @@ 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]") + class PhaseTimeout(RuntimeError): pass + class Unsupported(RuntimeError): pass + class TargetFailure(RuntimeError): pass + class StopTriggered(RuntimeError): def __init__(self, condition: str): super().__init__(condition) self.condition = condition + def sanitize(text: str, limit: int = 4096) -> str: text = CONTROL_RE.sub("?", text) text = text.replace("::", ": :") return text[:limit] + +def target_path() -> str: + directories = [] + for name in ("git", "node", "npm"): + resolved = shutil.which(name) + if resolved: + directories.append(str(Path(resolved).parent)) + directories.extend(["/usr/local/bin", "/usr/bin", "/bin"]) + return ":".join(dict.fromkeys(directories)) + + def target_env() -> dict[str, str]: return { "HOME": str(TARGET_HOME), "TMPDIR": str(TARGET_TMP), - "PATH": "/usr/local/bin:/usr/bin:/bin", + "PATH": target_path(), "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8", "GIT_CONFIG_NOSYSTEM": "1", @@ -64,13 +81,17 @@ def target_env() -> dict[str, str]: "CI": "true", } + def ensure_target_user() -> None: if os.geteuid() != 0: raise RuntimeError("Harness must run as root on the disposable runner") try: pwd.getpwnam(TARGET_USER) except KeyError: - subprocess.run(["useradd", "--system", "--no-create-home", "--shell", "/usr/sbin/nologin", TARGET_USER], check=True) + subprocess.run( + ["useradd", "--system", "--no-create-home", "--shell", "/usr/sbin/nologin", TARGET_USER], + check=True, + ) pw = pwd.getpwnam(TARGET_USER) for path in (TARGET_ROOT, WORKSPACE, TARGET_HOME, TARGET_TMP): path.mkdir(parents=True, exist_ok=True) @@ -83,21 +104,82 @@ def ensure_target_user() -> None: os.chmod(TRUSTED_ROOT, 0o700) os.chmod(TRACE_ROOT, 0o700) -def run_bounded(command: list[str], phase: str, timeout: int, trace: bool = False, stdin_data: bytes | None = None, stop_on_output_limit: bool = False) -> tuple[int, str, str]: - if timeout <= 0: - raise PhaseTimeout(phase) - base = ["runuser", "-u", TARGET_USER, "--", "env", "-i"] + [f"{k}={v}" for k, v in target_env().items()] - limited = ["prlimit", "--nproc=128", "--nofile=256", "--fsize=67108864", f"--cpu={max(5, timeout)}", "--"] + command + +def target_command(command: list[str], phase: str, timeout: int, trace: bool = False) -> list[str]: + base = ["runuser", "-u", TARGET_USER, "--", "env", "-i"] + [ + f"{key}={value}" for key, value in target_env().items() + ] + limited = [ + "prlimit", + "--nproc=128", + "--nofile=256", + "--fsize=67108864", + f"--cpu={max(5, timeout)}", + "--", + ] + command full = base + limited if trace: trace_file = TRACE_ROOT / phase.lower() - full = ["strace", "-ff", "-qq", "-e", "trace=network,process,file", "-o", str(trace_file)] + full - proc = subprocess.Popen(full, cwd=WORKSPACE, stdin=subprocess.PIPE if stdin_data is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True) + full = [ + "strace", + "-ff", + "-qq", + "-e", + "trace=network,process,file", + "-o", + str(trace_file), + ] + full + return full + + +def terminate_process_group(proc: subprocess.Popen[bytes], graceful: bool = False) -> None: + if proc.poll() is not None: + return + try: + os.killpg(proc.pid, signal.SIGTERM if graceful else signal.SIGKILL) + except ProcessLookupError: + return + if graceful: + try: + proc.wait(timeout=2) + return + except subprocess.TimeoutExpired: + pass + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + pass + + +def run_bounded( + command: list[str], + phase: str, + timeout: int, + trace: bool = False, + stdin_data: bytes | None = None, + stop_on_output_limit: bool = False, +) -> tuple[int, str, str]: + if timeout <= 0: + raise PhaseTimeout(phase) + full = target_command(command, phase, timeout, trace) + proc = subprocess.Popen( + full, + cwd=WORKSPACE, + stdin=subprocess.PIPE if stdin_data is not None else subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=True, + ) captured = {"out": bytearray(), "err": bytearray()} output_limit_hit = threading.Event() + def pump(stream, key): while True: - chunk = stream.read(8192) + chunk = os.read(stream.fileno(), 8192) if not chunk: break remaining = OUTPUT_LIMIT - len(captured[key]) @@ -105,7 +187,11 @@ def pump(stream, key): captured[key].extend(chunk[:remaining]) if len(chunk) > max(remaining, 0): output_limit_hit.set() - threads = [threading.Thread(target=pump, args=(proc.stdout, "out"), daemon=True), threading.Thread(target=pump, args=(proc.stderr, "err"), daemon=True)] + + threads = [ + threading.Thread(target=pump, args=(proc.stdout, "out"), daemon=True), + threading.Thread(target=pump, args=(proc.stderr, "err"), daemon=True), + ] for thread in threads: thread.start() if stdin_data is not None and proc.stdin is not None: @@ -120,26 +206,171 @@ def pump(stream, key): deadline = time.monotonic() + timeout while proc.poll() is None: if stop_on_output_limit and output_limit_hit.is_set(): - try: - os.killpg(proc.pid, signal.SIGKILL) - except ProcessLookupError: - pass - proc.wait(timeout=10) + terminate_process_group(proc) raise StopTriggered("output_capture_limit") if time.monotonic() >= deadline: raise subprocess.TimeoutExpired(full, timeout) time.sleep(0.05) except subprocess.TimeoutExpired as exc: + terminate_process_group(proc) + raise PhaseTimeout(phase) from exc + finally: + for thread in threads: + thread.join(timeout=5) + return ( + proc.returncode, + captured["out"].decode("utf-8", "replace"), + captured["err"].decode("utf-8", "replace"), + ) + + +def run_mcp_initialize( + command: list[str], + timeout: int, + trace: bool, + stop_on_output_limit: bool, +) -> tuple[str, str, dict]: + if timeout <= 0: + raise PhaseTimeout("EXERCISE") + + full = target_command(command, "EXERCISE", timeout, trace) + proc = subprocess.Popen( + full, + cwd=WORKSPACE, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + start_new_session=True, + ) + captured = {"out": bytearray(), "err": bytearray()} + output_limit_hit = threading.Event() + response_event = threading.Event() + response_holder: dict[str, dict] = {} + + def append_bounded(key: str, chunk: bytes) -> None: + remaining = OUTPUT_LIMIT - len(captured[key]) + if remaining > 0: + captured[key].extend(chunk[:remaining]) + if len(chunk) > max(remaining, 0): + output_limit_hit.set() + + def inspect_line(line: bytes) -> None: + if response_event.is_set(): + return + try: + message = json.loads(line.decode("utf-8", "replace")) + except (json.JSONDecodeError, UnicodeError): + return + if not isinstance(message, dict): + return + if message.get("jsonrpc") != "2.0" or message.get("id") != 1: + return + if "result" not in message and "error" not in message: + return + response_holder["message"] = message + response_event.set() + + def stdout_pump() -> None: + pending = bytearray() + while True: + chunk = os.read(proc.stdout.fileno(), 8192) + if not chunk: + break + append_bounded("out", chunk) + pending.extend(chunk) + while b"\n" in pending: + line, _, rest = pending.partition(b"\n") + pending = bytearray(rest) + inspect_line(line) + if len(pending) > OUTPUT_LIMIT: + output_limit_hit.set() + pending = pending[-OUTPUT_LIMIT:] + if pending: + inspect_line(bytes(pending)) + + def stderr_pump() -> None: + while True: + chunk = os.read(proc.stderr.fileno(), 8192) + if not chunk: + break + append_bounded("err", chunk) + + threads = [ + threading.Thread(target=stdout_pump, daemon=True), + threading.Thread(target=stderr_pump, daemon=True), + ] + for thread in threads: + thread.start() + + initialize = { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "mcp-security-runner", "version": "1"}, + }, + } + initialized = {"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}} + + try: + if proc.stdin is None: + raise TargetFailure("Target stdin is unavailable") + proc.stdin.write((json.dumps(initialize, separators=(",", ":")) + "\n").encode()) + proc.stdin.flush() + + deadline = time.monotonic() + timeout + while not response_event.is_set(): + if stop_on_output_limit and output_limit_hit.is_set(): + terminate_process_group(proc) + raise StopTriggered("output_capture_limit") + if proc.poll() is not None: + for thread in threads: + thread.join(timeout=2) + out = captured["out"].decode("utf-8", "replace") + err = captured["err"].decode("utf-8", "replace") + detail = sanitize(err or out) + raise TargetFailure( + f"Target exited before initialize response with code {proc.returncode}: {detail}" + ) + if time.monotonic() >= deadline: + terminate_process_group(proc) + raise PhaseTimeout("EXERCISE") + time.sleep(0.02) + + response = response_holder["message"] + if "error" in response: + raise TargetFailure( + "MCP initialize returned JSON-RPC error: " + + sanitize(json.dumps(response["error"], ensure_ascii=False)) + ) + try: - os.killpg(proc.pid, signal.SIGKILL) - except ProcessLookupError: + proc.stdin.write((json.dumps(initialized, separators=(",", ":")) + "\n").encode()) + proc.stdin.flush() + time.sleep(0.05) + except BrokenPipeError: pass - proc.wait(timeout=10) - raise PhaseTimeout(phase) from exc + finally: + try: + proc.stdin.close() + except OSError: + pass + + terminate_process_group(proc, graceful=True) + for thread in threads: + thread.join(timeout=5) + return ( + captured["out"].decode("utf-8", "replace"), + captured["err"].decode("utf-8", "replace"), + response, + ) finally: + terminate_process_group(proc) for thread in threads: thread.join(timeout=5) - return proc.returncode, captured["out"].decode("utf-8", "replace"), captured["err"].decode("utf-8", "replace") + def acquire(req: RuntimeRequest) -> None: repo_url = f"https://github.com/{req.repository}.git" @@ -148,19 +379,33 @@ def acquire(req: RuntimeRequest) -> None: rc, _, err = run_bounded(["git", "-c", "core.hooksPath=/dev/null", "init", "."], "ACQUIRE", 30) if rc: raise TargetFailure(f"git init failed: {sanitize(err)}") - rc, _, err = run_bounded(["git", "-c", "core.hooksPath=/dev/null", "remote", "add", "origin", repo_url], "ACQUIRE", 10) + rc, _, err = run_bounded( + ["git", "-c", "core.hooksPath=/dev/null", "remote", "add", "origin", repo_url], + "ACQUIRE", + 10, + ) if rc: raise TargetFailure(f"git remote add failed: {sanitize(err)}") - rc, _, err = run_bounded(["git", "-c", "core.hooksPath=/dev/null", "fetch", "--no-tags", "--depth=1", "origin", req.ref], "ACQUIRE", PHASE_LIMITS["ACQUIRE"], trace="network" in req.evidence or "process" in req.evidence) + rc, _, err = run_bounded( + ["git", "-c", "core.hooksPath=/dev/null", "fetch", "--no-tags", "--depth=1", "origin", req.ref], + "ACQUIRE", + PHASE_LIMITS["ACQUIRE"], + trace="network" in req.evidence or "process" in req.evidence, + ) if rc: raise TargetFailure(f"git fetch failed: {sanitize(err)}") - rc, _, err = run_bounded(["git", "-c", "core.hooksPath=/dev/null", "checkout", "--detach", "FETCH_HEAD"], "ACQUIRE", 30) + rc, _, err = run_bounded( + ["git", "-c", "core.hooksPath=/dev/null", "checkout", "--detach", "FETCH_HEAD"], + "ACQUIRE", + 30, + ) if rc: raise TargetFailure(f"git checkout failed: {sanitize(err)}") rc, out, _ = run_bounded(["git", "rev-parse", "HEAD"], "ACQUIRE", 10) if rc or out.strip().lower() != req.ref: raise TargetFailure("Resolved HEAD does not match requested commit") + def contained_entrypoint(req: RuntimeRequest) -> Path: candidate = WORKSPACE / req.entrypoint resolved = candidate.resolve(strict=True) @@ -173,6 +418,7 @@ def contained_entrypoint(req: RuntimeRequest) -> Path: raise Unsupported("Entrypoint is not a regular file") return resolved + def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: @@ -180,20 +426,22 @@ def sha256(path: Path) -> str: digest.update(chunk) return digest.hexdigest() + def snapshot(root: Path) -> dict[str, tuple[int, int]]: result = {} for current, dirs, files in os.walk(root, followlinks=False): - dirs[:] = [d for d in dirs if d != ".git"] + dirs[:] = [directory for directory in dirs if directory != ".git"] for name in files: path = Path(current) / name try: - st = path.lstat() + stat = path.lstat() rel = str(path.relative_to(root)) - result[rel] = (st.st_size, st.st_mtime_ns) + result[rel] = (stat.st_size, stat.st_mtime_ns) except OSError: continue return result + def parse_traces(phases: Iterable[str], evidence: set[str]) -> list[dict]: observations = [] for phase in phases: @@ -204,20 +452,33 @@ def parse_traces(phases: Iterable[str], evidence: set[str]) -> list[dict]: continue for line in lines[:5000]: if "network" in evidence and ("connect(" in line or "sendto(" in line): - observations.append({"phase": phase, "type": "network_trace", "data": {"excerpt": sanitize(line, 1000)}}) - if "process" in evidence and ("execve(" in line or "clone(" in line or "clone3(" in line or "vfork(" in line): - observations.append({"phase": phase, "type": "process_trace", "data": {"excerpt": sanitize(line, 1000)}}) + observations.append( + {"phase": phase, "type": "network_trace", "data": {"excerpt": sanitize(line, 1000)}} + ) + if "process" in evidence and ( + "execve(" in line or "clone(" in line or "clone3(" in line or "vfork(" in line + ): + observations.append( + {"phase": phase, "type": "process_trace", "data": {"excerpt": sanitize(line, 1000)}} + ) if len(observations) >= 1000: return observations return observations + def cleanup_target() -> None: try: pw = pwd.getpwnam(TARGET_USER) - subprocess.run(["pkill", "-KILL", "-u", str(pw.pw_uid)], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run( + ["pkill", "-KILL", "-u", str(pw.pw_uid)], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) except KeyError: pass + def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--request-file", required=True, type=Path) @@ -233,12 +494,28 @@ def main() -> int: raw = req.raw result = new_result(raw) ensure_target_user() - result["environment"] = {"runner_os": "ubuntu", "isolation": "dedicated_unprivileged_user", "network_mode": "OPEN"} + result["environment"] = { + "runner_os": "ubuntu", + "isolation": "dedicated_unprivileged_user", + "network_mode": "OPEN", + } requested = set(req.evidence) result["collectors"] = [ - {"name": "strace", "categories": sorted(requested & {"network", "process"}), "limitation": "same hosted VM; syscall excerpts are bounded and not tamper-resistant"}, - {"name": "filesystem_snapshot", "categories": sorted(requested & {"filesystem"}), "limitation": "workspace metadata only; .git excluded"}, - {"name": "protocol_capture", "categories": sorted(requested & {"protocol"}), "limitation": "bounded stdout capture for mcp_initialize only"}, + { + "name": "strace", + "categories": sorted(requested & {"network", "process"}), + "limitation": "same hosted VM; syscall excerpts are bounded and not tamper-resistant", + }, + { + "name": "filesystem_snapshot", + "categories": sorted(requested & {"filesystem"}), + "limitation": "workspace metadata only; .git excluded", + }, + { + "name": "protocol_capture", + "categories": sorted(requested & {"protocol"}), + "limitation": "bounded newline-delimited JSON-RPC capture for mcp_initialize only", + }, ] phases.append("ACQUIRE") acquire(req) @@ -254,54 +531,97 @@ def main() -> int: rc, npm_version, _ = run_bounded(["npm", "--version"], "INSTALL", 10) if rc: raise Unsupported("npm is unavailable") - result["provenance"].update({"runtime_version": node_version.strip(), "package_manager": "npm", "package_manager_version": npm_version.strip(), "install_mode": "npm ci"}) + result["provenance"].update( + { + "runtime_version": node_version.strip(), + "package_manager": "npm", + "package_manager_version": npm_version.strip(), + "install_mode": "npm ci", + } + ) phases.append("INSTALL") - rc, out, err = run_bounded(["npm", "ci", "--no-audit", "--no-fund"], "INSTALL", PHASE_LIMITS["INSTALL"], trace=bool(requested & {"network", "process"})) + rc, out, err = run_bounded( + ["npm", "ci", "--no-audit", "--no-fund"], + "INSTALL", + PHASE_LIMITS["INSTALL"], + trace=bool(requested & {"network", "process"}), + ) if rc: result["errors"].append({"phase": "INSTALL", "message": sanitize(err or out)}) raise TargetFailure("Target dependency installation failed") entrypoint = contained_entrypoint(req) phases.extend(["START", "EXERCISE"]) - initialize = {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-security-runner","version":"1"}}} - payload = (json.dumps(initialize, separators=(",", ":")) + "\n").encode() - rc, out, err = run_bounded(["node", str(entrypoint), *req.argv], "EXERCISE", req.timeout_seconds, trace=bool(requested & {"network", "process"}), stdin_data=payload, stop_on_output_limit="output_capture_limit" in req.stop_conditions) + out, err, response = run_mcp_initialize( + ["node", str(entrypoint), *req.argv], + req.timeout_seconds, + trace=bool(requested & {"network", "process"}), + stop_on_output_limit="output_capture_limit" in req.stop_conditions, + ) if "protocol" in requested: - result["observations"].append({"phase":"EXERCISE","type":"protocol_output","data":{"stdout_excerpt":sanitize(out),"stderr_excerpt":sanitize(err)}}) - if rc: - result["errors"].append({"phase":"EXERCISE","message":f"Target exited with code {rc}"}) - status = "TARGET_FAILED" - else: - status = "COMPLETED" + result["observations"].append( + { + "phase": "EXERCISE", + "type": "protocol_output", + "data": { + "initialize_response": response, + "stdout_excerpt": sanitize(out), + "stderr_excerpt": sanitize(err), + }, + } + ) + status = "COMPLETED" phases.extend(["STOP", "COLLECT"]) if "filesystem" in requested: after = snapshot(WORKSPACE) - changed = sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k))[:1000] - result["observations"].append({"phase":"COLLECT","type":"filesystem_changes","data":{"paths":changed,"limitation":"workspace metadata only; content not captured"}}) + 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"}, + } + ) result["observations"].extend(parse_traces(phases, requested)) except RequestError as exc: status = "RUNTIME_UNSUPPORTED" - result["errors"].append({"phase":"VALIDATE","message":sanitize(str(exc))}) + result["errors"].append({"phase": "VALIDATE", "message": sanitize(str(exc))}) except Unsupported as exc: status = "RUNTIME_UNSUPPORTED" - result["errors"].append({"phase":phases[-1] if phases else "VALIDATE","message":sanitize(str(exc))}) + result["errors"].append( + {"phase": phases[-1] if phases else "VALIDATE", "message": sanitize(str(exc))} + ) except StopTriggered as exc: status = "STOPPED" result["stop_condition_triggered"] = exc.condition - result["observations"].append({"phase": phases[-1] if phases else "UNKNOWN", "type": "stop_condition", "data": {"condition": exc.condition}}) + result["observations"].append( + { + "phase": phases[-1] if phases else "UNKNOWN", + "type": "stop_condition", + "data": {"condition": exc.condition}, + } + ) except PhaseTimeout as exc: status = "TIMEOUT" - result["errors"].append({"phase":str(exc),"message":"Phase timeout"}) + result["errors"].append({"phase": str(exc), "message": "Phase timeout"}) except TargetFailure as exc: status = "TARGET_FAILED" - result["errors"].append({"phase":phases[-1] if phases else "UNKNOWN","message":sanitize(str(exc))}) + result["errors"].append( + {"phase": phases[-1] if phases else "UNKNOWN", "message": sanitize(str(exc))} + ) except Exception as exc: status = "HARNESS_ERROR" - result["errors"].append({"phase":phases[-1] if phases else "HARNESS","message":sanitize(f"{type(exc).__name__}: {exc}")}) + result["errors"].append( + { + "phase": phases[-1] if phases else "HARNESS", + "message": sanitize(f"{type(exc).__name__}: {exc}"), + } + ) finally: cleanup_target() finish(result, status) write_result(args.result_file, result) return 0 if status in {"COMPLETED", "TARGET_FAILED", "TIMEOUT", "STOPPED", "RUNTIME_UNSUPPORTED"} else 1 + if __name__ == "__main__": raise SystemExit(main()) diff --git a/tests/runtime_fixture_check.py b/tests/runtime_fixture_check.py new file mode 100644 index 0000000..449aa29 --- /dev/null +++ b/tests/runtime_fixture_check.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import pwd +import shutil +import subprocess +import sys + +TARGET_ROOT = Path("/tmp/mcp-security-target") +TRUSTED_ROOT = Path("/tmp/mcp-security-trusted") +TMP_ROOT = Path("/tmp/mcp-security-fixture-check") + + +def reset_runtime() -> None: + shutil.rmtree(TARGET_ROOT, ignore_errors=True) + shutil.rmtree(TRUSTED_ROOT, ignore_errors=True) + shutil.rmtree(TMP_ROOT, ignore_errors=True) + TMP_ROOT.mkdir(parents=True, exist_ok=True) + + +def request(sha: str, entrypoint: str, timeout: int) -> dict: + return { + "schema_version": 1, + "target": { + "kind": "git", + "repository": "AXTRACK/mcp-security-runner", + "ref": sha, + }, + "question": "Controlled fixture validation", + "adapter": "node_stdio", + "entrypoint": entrypoint, + "argv": [], + "action_profile": "mcp_initialize", + "network_mode": "OPEN", + "evidence": ["network", "process", "filesystem", "protocol"], + "credentials": "NONE", + "timeout_seconds": timeout, + "stop_conditions": ["output_capture_limit"], + } + + +def assert_workspace_isolation(target_uid: int) -> None: + workspace = os.environ.get("GITHUB_WORKSPACE") + if not workspace: + return + trusted_file = str(Path(workspace) / "runner" / "run_review.py") + readable = subprocess.run( + ["runuser", "-u", "mcp_target", "--", "test", "-r", trusted_file], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) + if readable.returncode == 0: + raise AssertionError(f"target uid {target_uid} can read the trusted harness checkout") + + +def run_fixture(sha: str, name: str, entrypoint: str, timeout: int) -> dict: + reset_runtime() + request_file = TMP_ROOT / f"{name}-request.json" + result_file = TMP_ROOT / f"{name}-result.json" + request_file.write_text(json.dumps(request(sha, entrypoint, timeout)), encoding="utf-8") + completed = subprocess.run( + [ + sys.executable, + "runner/run_review.py", + "--request-file", + str(request_file), + "--result-file", + str(result_file), + ], + check=False, + ) + if completed.returncode not in (0, 1): + raise AssertionError(f"{name}: unexpected harness exit {completed.returncode}") + result = json.loads(result_file.read_text(encoding="utf-8")) + try: + target = pwd.getpwnam("mcp_target") + except KeyError as exc: + raise AssertionError("target account was not created") from exc + assert_workspace_isolation(target.pw_uid) + lingering = subprocess.run( + ["pgrep", "-u", str(target.pw_uid)], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + check=False, + ) + if lingering.returncode == 0 and lingering.stdout.strip(): + raise AssertionError(f"{name}: target processes survived cleanup: {lingering.stdout.strip()}") + 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 assert_safe(result: dict) -> None: + assert result["execution"]["status"] == "COMPLETED", result + protocol = observation(result, "protocol_output") + 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 + + +def assert_noisy(result: dict) -> None: + assert result["execution"]["status"] == "COMPLETED", result + filesystem = observation(result, "filesystem_changes") + 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 + + +def assert_failure(result: dict) -> None: + assert result["execution"]["status"] == "TIMEOUT", result + assert any(error.get("phase") == "EXERCISE" for error in result.get("errors", [])), result + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--sha", required=True) + args = parser.parse_args() + if len(args.sha) != 40: + raise SystemExit("--sha must be a 40-character commit SHA") + + safe = run_fixture(args.sha, "safe", "fixtures/safe/server.js", 15) + assert_safe(safe) + noisy = run_fixture(args.sha, "noisy", "fixtures/noisy/server.js", 15) + assert_noisy(noisy) + failure = run_fixture(args.sha, "failure", "fixtures/failure/server.js", 5) + assert_failure(failure) + print("Controlled runtime fixtures passed") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_validation.py b/tests/test_validation.py index 9efc23e..c3b2df3 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1,12 +1,32 @@ +import os +from pathlib import Path +import shutil import unittest -from runner.run_review import sanitize + +from runner.run_review import sanitize, target_env + class ValidationTests(unittest.TestCase): def test_neutralizes_workflow_command_delimiter(self): value = sanitize("::error::spoof") self.assertNotIn("::", value) + def test_removes_terminal_control_sequences(self): value = sanitize("safe\x1b[31mred") self.assertNotIn("\x1b", value) -if __name__ == "__main__": unittest.main() + def test_target_environment_is_allowlisted(self): + environment = target_env() + self.assertFalse(any(name.startswith("GITHUB_") for name in environment)) + self.assertFalse(any(name.startswith("ACTIONS_") for name in environment)) + self.assertEqual(environment["HOME"], "/tmp/mcp-security-target/home") + + def test_target_path_contains_trusted_node_directory(self): + node = shutil.which("node") + if node is None: + self.skipTest("node is not installed") + self.assertIn(str(Path(node).parent), target_env()["PATH"].split(os.pathsep)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_workflow.py b/tests/test_workflow.py index d24eca3..8551504 100644 --- a/tests/test_workflow.py +++ b/tests/test_workflow.py @@ -1,23 +1,35 @@ import unittest from pathlib import Path + class WorkflowTests(unittest.TestCase): def test_request_expression_is_data_only(self): text = Path('.github/workflows/runtime-review.yml').read_text(encoding='utf-8') expression = '${{ inputs.request_json }}' self.assertEqual(text.count(expression), 1) self.assertIn(f'REQUEST_JSON: {expression}', text) + def test_runtime_is_manual_only(self): text = Path('.github/workflows/runtime-review.yml').read_text(encoding='utf-8') self.assertIn('workflow_dispatch:', text) self.assertNotIn('pull_request:', text) self.assertNotIn('pull_request_target:', text) + def test_actions_are_pinned(self): text = Path('.github/workflows/runtime-review.yml').read_text(encoding='utf-8') self.assertNotIn('actions/checkout@v', text) self.assertNotIn('actions/upload-artifact@v', text) - def test_target_cannot_traverse_runner_home(self): + + def test_target_cannot_traverse_trusted_workspace(self): text = Path('.github/workflows/runtime-review.yml').read_text(encoding='utf-8') self.assertIn('sudo chmod 700 /home/runner', text) + self.assertIn('sudo chmod 700 "$GITHUB_WORKSPACE"', text) + + def test_ci_runs_controlled_runtime_fixtures(self): + text = Path('.github/workflows/ci.yml').read_text(encoding='utf-8') + self.assertIn('runtime-fixtures:', text) + self.assertIn('tests/runtime_fixture_check.py', text) + -if __name__ == '__main__': unittest.main() +if __name__ == '__main__': + unittest.main()