From 054023a16d682f71d6c4d2e8ee7048dd2491b3fb Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 30 Sep 2026 09:28:20 -0500 Subject: [PATCH 1/5] fix(codex): forward inherited activity context to MCP [[tasks/harmony-1991]] --- .github/workflows/ci.yml | 7 ++ Makefile | 6 +- README.md | 16 +++ plugin/.codex-plugin/plugin.json | 2 +- plugin/.mcp.json | 10 ++ plugin/README.md | 20 +++- tests/mcp-contract.py | 40 ++++++++ tests/mcp-startup.py | 166 +++++++++++++++++++++++++++++++ 8 files changed, 264 insertions(+), 3 deletions(-) create mode 100644 tests/mcp-contract.py create mode 100644 tests/mcp-startup.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d64ebaa..1312dd4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,3 +15,10 @@ jobs: run: sudo apt-get update && sudo apt-get install -y jq - name: Run release checks run: make release-check + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Install Codex for MCP launch regression + run: npm install --prefix "$RUNNER_TEMP/codex" @openai/codex@0.159.2 + - name: Test packaged MCP launch through Codex + run: make test-integration CODEX_TEST_BINARY="$RUNNER_TEMP/codex/node_modules/.bin/codex" diff --git a/Makefile b/Makefile index c974bd3..15c217a 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,13 @@ -.PHONY: all test lint lint-json lint-policy lint-codex diff-check release-check clean +.PHONY: all test test-integration lint lint-json lint-policy lint-codex diff-check release-check clean all: lint test test: @tests/package-policy.sh + @python3 tests/mcp-contract.py plugin + +test-integration: + @python3 tests/mcp-startup.py --codex "$(CODEX_TEST_BINARY)" lint: lint-json lint-policy lint-codex @echo "All checks passed." diff --git a/README.md b/README.md index 458cc2e..940a46b 100644 --- a/README.md +++ b/README.md @@ -87,3 +87,19 @@ The plugin version is declared in: - `plugin/.codex-plugin/plugin.json` Keep the marketplace and plugin docs aligned when preparing a release. + +## MCP Launch Regression Tests + +`make test` checks the packaged environment allowlist and cache version. The +installation test exercises the actual Codex MCP launch boundary with synthetic +sessions, custom registry settings, paths with spaces and Unicode, and credential +canaries. It reuses an isolated plugin installation across two sessions and a +launch without activity context. It does not start a model turn or run an activity +sink, and it does not use your Codex home or credentials. + +```bash +make test-integration CODEX_TEST_BINARY=/absolute/path/to/provider/codex +``` + +Pass the provider binary, rather than an ATC shim. CI runs this test with Codex +`0.159.2`, in addition to the release checks. diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json index 6627a8c..feb0065 100644 --- a/plugin/.codex-plugin/plugin.json +++ b/plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "gitkb", - "version": "0.1.0", + "version": "0.1.2", "description": "Codex hooks, skills, and MCP config for GitKB code-intelligence guidance.", "author": { "name": "GitKB", diff --git a/plugin/.mcp.json b/plugin/.mcp.json index ca13ce0..6c0cc04 100644 --- a/plugin/.mcp.json +++ b/plugin/.mcp.json @@ -4,6 +4,16 @@ "command": "git-kb", "args": [ "mcp" + ], + "env_vars": [ + "SESSION_ACTIVITY_RESOURCE_ID", + "SESSION_ACTIVITY_RESOURCE_KIND", + "SESSION_ACTIVITY_PROVIDER", + "SESSION_ACTIVITY_CONTEXT_FILE", + "SESSION_ACTIVITY_SINK_COMMAND", + "SESSION_ACTIVITY_SINK_ARGS_JSON", + "ATC_ROOT", + "ATC_CONFIG" ] } } diff --git a/plugin/README.md b/plugin/README.md index efe2468..1b0e7d7 100644 --- a/plugin/README.md +++ b/plugin/README.md @@ -54,9 +54,27 @@ git-kb init codex - one focused code-intelligence skill; - Codex lifecycle hooks that call `git-kb hook codex`; - MCP configuration for `git-kb mcp`; -- no external harness-specific behavior; +- inherited session activity context for the MCP process; - no vendored copy of the full canonical `git-kb init codex` skill set. +## ATC Session Activity + +When Codex runs through an ATC shim, the plugin forwards the parent's six +`SESSION_ACTIVITY_*` settings to `git-kb mcp`. It also forwards `ATC_ROOT` and +`ATC_CONFIG` when set, so the activity sink uses the same registry as the shim. +Codex filters the MCP environment; installing a newer `git-kb` or `atc` binary +alone does not update this plugin launch configuration. + +Install the updated plugin (`0.1.2`) from your marketplace and restart or resume +Codex through the ATC shim to start a new MCP process. Existing MCP processes keep +the environment with which they started. Previously omitted activity records +are not backfilled by this update. + +The configuration forwards variable names rather than fixed session values. +Without parent activity context, GitKB keeps its normal behavior. The plugin does +not forward API credentials, generic provider thread IDs, or a global ATC session +ID as a substitute for the activity contract. + ## Documentation - [Getting Started](https://gitkb.com/docs/getting-started/quick-start/) diff --git a/tests/mcp-contract.py b/tests/mcp-contract.py new file mode 100644 index 0000000..311e612 --- /dev/null +++ b/tests/mcp-contract.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Guard the packaged MCP launch contract, including its credential boundary.""" +import json +import sys +import unittest +from pathlib import Path + +FORWARDED = { + "SESSION_ACTIVITY_RESOURCE_ID", "SESSION_ACTIVITY_RESOURCE_KIND", + "SESSION_ACTIVITY_PROVIDER", "SESSION_ACTIVITY_CONTEXT_FILE", + "SESSION_ACTIVITY_SINK_COMMAND", "SESSION_ACTIVITY_SINK_ARGS_JSON", + "ATC_ROOT", "ATC_CONFIG", +} +PLUGIN_ROOT = Path(sys.argv.pop(1)) + + +class LaunchContract(unittest.TestCase): + def test_parent_context_is_forwarded_by_name_only(self): + config = json.loads((PLUGIN_ROOT / ".mcp.json").read_text()) + self.assertEqual(set(config["mcpServers"]), {"gitkb"}) + server = config["mcpServers"]["gitkb"] + names = server["env_vars"] + self.assertIsInstance(names, list) + self.assertTrue(all(isinstance(name, str) for name in names)) + self.assertEqual(set(names), FORWARDED) + self.assertEqual(len(names), len(FORWARDED), "duplicate forwarding names") + self.assertNotIn("env", server, "do not bake session identity into the plugin") + self.assertEqual(server["command"], "git-kb") + self.assertEqual(server["args"], ["mcp"]) + + def test_cache_version_changes_with_launch_contract(self): + manifest = json.loads((PLUGIN_ROOT / ".codex-plugin/plugin.json").read_text()) + version = tuple(int(part) for part in manifest["version"].split(".")) + self.assertEqual(len(version), 3) + self.assertGreaterEqual(version, (0, 1, 2), "old cache versions lack this contract") + self.assertEqual(manifest["mcpServers"], "./.mcp.json") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/mcp-startup.py b/tests/mcp-startup.py new file mode 100644 index 0000000..142fe1d --- /dev/null +++ b/tests/mcp-startup.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Install the real package in an isolated Codex home and inspect its MCP child. + +Uses only initialize and mcpServerStatus/list; never starts a thread or model turn. +The fake GitKB server captures synthetic context without running an activity sink. +""" +import argparse +import json +import os +import selectors +import shlex +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +NAMES = ( + "SESSION_ACTIVITY_RESOURCE_ID", "SESSION_ACTIVITY_RESOURCE_KIND", + "SESSION_ACTIVITY_PROVIDER", "SESSION_ACTIVITY_CONTEXT_FILE", + "SESSION_ACTIVITY_SINK_COMMAND", "SESSION_ACTIVITY_SINK_ARGS_JSON", + "ATC_ROOT", "ATC_CONFIG", +) +FORBIDDEN = ("MCP_ENV_UNRELATED_SECRET", "OPENAI_API_KEY", "ATC_SESSION_ID", "CODEX_THREAD_ID") + + +def run(codex, args, env, cwd): + result = subprocess.run([codex, *args], env=env, cwd=cwd, + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30) + if result.returncode: + raise AssertionError(f"Codex {args} failed: {result.stdout} {result.stderr}") + + +def inspect_child(codex, env, root, capture): + capture.unlink(missing_ok=True) + with (root / "stderr.log").open("w+") as stderr: + process = subprocess.Popen([codex, "app-server"], env=env, cwd=root, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=stderr, start_new_session=True) + selector = selectors.DefaultSelector() + selector.register(process.stdout, selectors.EVENT_READ) + pending = bytearray() + + def send(message): + process.stdin.write((json.dumps(message) + "\n").encode()) + process.stdin.flush() + + def response(request_id): + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + while b"\n" in pending: + line, _, rest = pending.partition(b"\n") + pending[:] = rest + message = json.loads(line) + if message.get("id") == request_id: + if "error" in message: + raise AssertionError(message["error"]) + return message["result"] + if selector.select(timeout=0.1): + chunk = os.read(process.stdout.fileno(), 65536) + if not chunk: + break + pending.extend(chunk) + stderr.flush() + stderr.seek(0) + raise AssertionError(f"No response to {request_id}: {stderr.read()[-4000:]}") + + try: + send({"id": 1, "method": "initialize", "params": { + "clientInfo": {"name": "gitkb-package-test", "version": "1"}, + "capabilities": {"experimentalApi": True}}}) + response(1) + send({"method": "initialized"}) + send({"id": 2, "method": "mcpServerStatus/list", "params": {}}) + servers = response(2)["data"] + server = next(item for item in servers if item["name"] == "gitkb") + assert server["pluginId"] == "gitkb@gitkb", server + assert "context_probe" in server["tools"], server + assert capture.exists(), "packaged MCP child did not start" + return json.loads(capture.read_text()) + finally: + selector.close() + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=5) + process.stdin.close() + process.stdout.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--codex", required=True, help="Provider Codex binary, not an ATC shim") + parser.add_argument("--marketplace", default=".") + args = parser.parse_args() + codex = shutil.which(args.codex) + if not codex: + parser.error("Codex binary not found") + codex = str(Path(codex).resolve()) + marketplace = str(Path(args.marketplace).resolve()) + with tempfile.TemporaryDirectory(prefix="gitkb-mcp-context-") as directory: + root = Path(directory) + (root / "bin").mkdir() + (root / "codex").mkdir() + capture = root / "context.json" + fixture = root / "mcp_fixture.py" + fixture.write_text('''import json, os, sys +if sys.argv[1:] != ["mcp"]: + sys.exit(0) +''' + f"names = {NAMES + FORBIDDEN!r}\n" + + f"with open({str(capture)!r}, 'w') as output:\n" + + " json.dump({name: os.environ[name] for name in names if name in os.environ}, output)\n" + '''for line in sys.stdin: + message = json.loads(line) + if "id" not in message: + continue + method = message["method"] + if method == "initialize": + result = {"protocolVersion": message["params"]["protocolVersion"], + "capabilities": {"tools": {}}, "serverInfo": {"name": "gitkb-fixture", "version": "1"}} + elif method == "tools/list": + result = {"tools": [{"name": "context_probe", "description": "Launch boundary probe", + "inputSchema": {"type": "object", "properties": {}}}]} + elif method == "resources/list": + result = {"resources": []} + elif method == "resources/templates/list": + result = {"resourceTemplates": []} + else: + print(json.dumps({"jsonrpc": "2.0", "id": message["id"], + "error": {"code": -32601, "message": "Method not found"}}), flush=True) + continue + print(json.dumps({"jsonrpc": "2.0", "id": message["id"], "result": result}), flush=True) +''') + shim = root / "bin/git-kb" + shim.write_text(f"#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(fixture))} \"$@\"\n") + shim.chmod(0o755) + # Construct the environment: never inherit the developer's keys, session or home. + base_env = {"HOME": directory, "CODEX_HOME": str(root / "codex"), + "PATH": str(root / "bin") + os.pathsep + os.defpath, + "TMPDIR": directory} + node = shutil.which("node") + if node: + # npm Codex launchers use /usr/bin/env node; keep that interpreter reachable. + base_env["PATH"] += os.pathsep + str(Path(node).parent) + run(codex, ["plugin", "marketplace", "add", marketplace, "--json"], base_env, root) + run(codex, ["plugin", "add", "gitkb@gitkb", "--json"], base_env, root) + for session in ("alpha", "beta", None): + expected = {} if session is None else dict(zip(NAMES, ( + f"xses-{session}", "external", "codex", + str(root / f"{session} path 'quoted' ΓΌ.json"), + str(root / "sink path"), json.dumps(["activity", "record", "--json"]), + str(root / f"{session} registry"), str(root / f"{session} config.toml")))) + env = dict(base_env, **expected, **{name: "synthetic-canary" for name in FORBIDDEN}) + observed = inspect_child(codex, env, root, capture) + assert observed == expected, f"{session or 'unshimmed'}: expected {expected}, got {observed}" + print(f"PASS: {session or 'unshimmed'} MCP context and credential isolation") + + +if __name__ == "__main__": + main() From 073fc6afc1502f186885fe96bc77d67db27d872b Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 30 Sep 2026 09:35:11 -0500 Subject: [PATCH 2/5] test(codex): document MCP launch regression helpers [[tasks/harmony-1991]] --- tests/mcp-contract.py | 2 ++ tests/mcp-startup.py | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/tests/mcp-contract.py b/tests/mcp-contract.py index 311e612..02f70d4 100644 --- a/tests/mcp-contract.py +++ b/tests/mcp-contract.py @@ -16,6 +16,7 @@ class LaunchContract(unittest.TestCase): def test_parent_context_is_forwarded_by_name_only(self): + """Require the activity/registry allowlist while rejecting fixed environment values.""" config = json.loads((PLUGIN_ROOT / ".mcp.json").read_text()) self.assertEqual(set(config["mcpServers"]), {"gitkb"}) server = config["mcpServers"]["gitkb"] @@ -29,6 +30,7 @@ def test_parent_context_is_forwarded_by_name_only(self): self.assertEqual(server["args"], ["mcp"]) def test_cache_version_changes_with_launch_contract(self): + """Ensure the installable version cannot reuse either pre-fix cache entry.""" manifest = json.loads((PLUGIN_ROOT / ".codex-plugin/plugin.json").read_text()) version = tuple(int(part) for part in manifest["version"].split(".")) self.assertEqual(len(version), 3) diff --git a/tests/mcp-startup.py b/tests/mcp-startup.py index 142fe1d..e04426a 100644 --- a/tests/mcp-startup.py +++ b/tests/mcp-startup.py @@ -27,6 +27,7 @@ def run(codex, args, env, cwd): + """Run a bounded plugin installation command with only the fixture environment.""" result = subprocess.run([codex, *args], env=env, cwd=cwd, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30) if result.returncode: @@ -34,6 +35,7 @@ def run(codex, args, env, cwd): def inspect_child(codex, env, root, capture): + """Negotiate packaged MCP tools, capture context, and clean up the owned process group.""" capture.unlink(missing_ok=True) with (root / "stderr.log").open("w+") as stderr: process = subprocess.Popen([codex, "app-server"], env=env, cwd=root, @@ -44,10 +46,12 @@ def inspect_child(codex, env, root, capture): pending = bytearray() def send(message): + """Write one newline-delimited app-server request or notification.""" process.stdin.write((json.dumps(message) + "\n").encode()) process.stdin.flush() def response(request_id): + """Read the matching reply with a deadline, ignoring asynchronous notifications.""" deadline = time.monotonic() + 15 while time.monotonic() < deadline: while b"\n" in pending: @@ -96,6 +100,7 @@ def response(request_id): def main(): + """Verify session isolation and the credential boundary through a real package install.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--codex", required=True, help="Provider Codex binary, not an ATC shim") parser.add_argument("--marketplace", default=".") From 3c30820e97bcb3f6eb4f9648c8d07b8784bbb930 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 30 Sep 2026 10:06:08 -0500 Subject: [PATCH 3/5] test(codex): verify canonical plugin installation [[tasks/harmony-2016]] --- README.md | 6 +++++- tests/mcp-startup.py | 23 ++++++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 940a46b..e4930a6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ # GitKB Codex Plugin -This repository contains the GitKB marketplace plugin for Codex. +This repository is the authoritative source for the GitKB Codex plugin payload +and its package/MCP regression tests. The `gitkb/codex-plugins` marketplace references +`./plugin` here through a Git-backed source; it does not maintain a plugin copy. +Plugin behavior changes belong in this repository. Catalog release promotion only +updates the marketplace's approved commit selector. GitKB gives Codex local code intelligence first: symbols, callers, callees, impact analysis, dead-code detection, semantic search, and service-edge queries through the `git-kb` CLI and MCP tools. Full GitKB setup adds the persistent knowledge graph for tasks, specs, decisions, architecture, and team sync. diff --git a/tests/mcp-startup.py b/tests/mcp-startup.py index e04426a..328478a 100644 --- a/tests/mcp-startup.py +++ b/tests/mcp-startup.py @@ -5,6 +5,7 @@ The fake GitKB server captures synthetic context without running an activity sink. """ import argparse +import hashlib import json import os import selectors @@ -32,6 +33,7 @@ def run(codex, args, env, cwd): stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30) if result.returncode: raise AssertionError(f"Codex {args} failed: {result.stdout} {result.stderr}") + return result.stdout def inspect_child(codex, env, root, capture): @@ -99,11 +101,20 @@ def response(request_id): process.stdout.close() +def payload_fingerprint(root): + """Hash the package tree so source resolution cannot silently install another payload.""" + return {str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest() + for path in root.rglob("*") if path.is_file()} + + def main(): """Verify session isolation and the credential boundary through a real package install.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--codex", required=True, help="Provider Codex binary, not an ATC shim") parser.add_argument("--marketplace", default=".") + parser.add_argument("--expected-plugin-root", type=Path, + default=Path(__file__).resolve().parents[1] / "plugin", + help="Canonical package to compare with the installed cache") args = parser.parse_args() codex = shutil.which(args.codex) if not codex: @@ -154,7 +165,17 @@ def main(): # npm Codex launchers use /usr/bin/env node; keep that interpreter reachable. base_env["PATH"] += os.pathsep + str(Path(node).parent) run(codex, ["plugin", "marketplace", "add", marketplace, "--json"], base_env, root) - run(codex, ["plugin", "add", "gitkb@gitkb", "--json"], base_env, root) + receipt = json.loads(run(codex, ["plugin", "add", "gitkb@gitkb", "--json"], base_env, root)) + expected_root = args.expected_plugin_root.resolve() + if not (expected_root / ".codex-plugin/plugin.json").is_file(): + raise AssertionError(f"Missing canonical package: {expected_root}") + expected_payload = payload_fingerprint(expected_root) + actual_payload = payload_fingerprint(Path(receipt["installedPath"])) + if actual_payload != expected_payload: + changed = sorted(path for path in actual_payload.keys() | expected_payload.keys() + if actual_payload.get(path) != expected_payload.get(path)) + raise AssertionError(f"Installed payload differs from canonical source: {changed}") + print(f"PASS: installed canonical payload ({len(actual_payload)} files)") for session in ("alpha", "beta", None): expected = {} if session is None else dict(zip(NAMES, ( f"xses-{session}", "external", "codex", From 3a6c6ecc6fa6e79a5170151209f565dda5e153d8 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 30 Sep 2026 11:03:50 -0500 Subject: [PATCH 4/5] test: harden plugin launch and legacy upgrade verification [[tasks/harmony-2016]] --- .github/workflows/ci.yml | 6 ++ Makefile | 11 ++- README.md | 12 ++- tests/mcp-startup-unit.py | 186 ++++++++++++++++++++++++++++++++++++++ tests/mcp-startup.py | 128 +++++++++++++++++++++----- 5 files changed, 315 insertions(+), 28 deletions(-) create mode 100644 tests/mcp-startup-unit.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1312dd4..acbee9f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,11 +6,17 @@ on: branches: - main +permissions: + contents: read + jobs: validate: runs-on: ubuntu-latest + timeout-minutes: 10 steps: - uses: actions/checkout@v4 + with: + persist-credentials: false - name: Install jq run: sudo apt-get update && sudo apt-get install -y jq - name: Run release checks diff --git a/Makefile b/Makefile index 15c217a..fecd416 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,12 @@ all: lint test test: @tests/package-policy.sh - @python3 tests/mcp-contract.py plugin + @python3 -B tests/mcp-contract.py plugin + @python3 -B tests/mcp-startup-unit.py test-integration: - @python3 tests/mcp-startup.py --codex "$(CODEX_TEST_BINARY)" + @python3 -B tests/mcp-startup.py --codex "$(CODEX_TEST_BINARY)" + @python3 -B tests/mcp-startup.py --codex "$(CODEX_TEST_BINARY)" --legacy-first lint: lint-json lint-policy lint-codex @echo "All checks passed." @@ -27,8 +29,9 @@ lint-policy: @tests/package-policy.sh lint-codex: - @if command -v codex >/dev/null 2>&1; then \ - echo "Checking Codex CLI is available for marketplace install testing"; \ + @if [ -n "$(CODEX_TEST_BINARY)" ]; then \ + "$(CODEX_TEST_BINARY)" plugin --help >/dev/null; \ + elif command -v codex >/dev/null 2>&1; then \ codex plugin --help >/dev/null; \ else \ echo "Skipping Codex CLI check (codex not available)"; \ diff --git a/README.md b/README.md index e4930a6..fce3ffd 100644 --- a/README.md +++ b/README.md @@ -94,12 +94,18 @@ Keep the marketplace and plugin docs aligned when preparing a release. ## MCP Launch Regression Tests -`make test` checks the packaged environment allowlist and cache version. The +`make test` checks the packaged environment allowlist and cache version, and +runs negative controls for cache symlinks, special files, executable modes, +receipt path escapes, optimized Python, protocol failures, output limits, and +process cleanup. Python 3.11 or newer is required for these test tools. The installation test exercises the actual Codex MCP launch boundary with synthetic sessions, custom registry settings, paths with spaces and Unicode, and credential canaries. It reuses an isolated plugin installation across two sessions and a -launch without activity context. It does not start a model turn or run an activity -sink, and it does not use your Codex home or credentials. +launch without activity context. A second isolated run first installs a bundled +`0.1.0` fixture, reproduces its missing context, then upgrades the same +`gitkb@gitkb` installation and repeats those checks. The harness bounds protocol +buffers and diagnostic reads, and terminates its own app-server process group. +It does not start a model turn or run an activity sink, and it does not use your Codex home or credentials. ```bash make test-integration CODEX_TEST_BINARY=/absolute/path/to/provider/codex diff --git a/tests/mcp-startup-unit.py b/tests/mcp-startup-unit.py new file mode 100644 index 0000000..9632bdd --- /dev/null +++ b/tests/mcp-startup-unit.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""Negative controls for the shared real-Codex launch harness.""" +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).with_name('mcp-startup.py') +spec = importlib.util.spec_from_file_location('startup', SCRIPT) +startup = importlib.util.module_from_spec(spec) +spec.loader.exec_module(startup) + + +class PayloadTests(unittest.TestCase): + def test_payload_rejects_links_and_special_files(self): + """Never follow external links or block reading FIFOs in a package cache.""" + for kind in ('file', 'directory', 'dangling', 'fifo'): + with self.subTest(kind=kind), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + payload = root / 'plugin' + payload.mkdir() + (payload / 'manifest').write_text('approved') + if kind == 'fifo': + os.mkfifo(payload / 'escape') + else: + target = root / 'outside' + if kind == 'file': + target.write_text('outside') + elif kind == 'directory': + target.mkdir() + (target / 'secret').write_text('outside') + (payload / 'escape').symlink_to(target) + with self.assertRaisesRegex(AssertionError, 'regular|symlink'): + startup.payload_fingerprint(payload) + + def test_payload_includes_executable_mode(self): + """Cache equality must detect a lost hook executable bit as well as changed bytes.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + path = root / 'hook' + path.write_text('hook') + path.chmod(0o644) + before = startup.payload_fingerprint(root) + path.chmod(0o755) + self.assertNotEqual(before, startup.payload_fingerprint(root)) + + def test_missing_or_empty_payload_is_not_valid(self): + """Two absent trees must not pass as matching installations.""" + with tempfile.TemporaryDirectory() as directory: + for root in (Path(directory), Path(directory) / 'missing'): + with self.subTest(root=root), self.assertRaises(AssertionError): + startup.payload_fingerprint(root) + + def test_receipt_must_stay_inside_isolated_cache(self): + """Reject external paths, relative paths, and symlink escapes before reading a cache.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + outside = root / "outside" + outside.mkdir() + (outside / "payload").write_text("external") + cache = root / "codex/plugins/cache" + cache.mkdir(parents=True) + (cache / "link").symlink_to(outside, target_is_directory=True) + for path in (outside, Path("outside"), cache / "link"): + with self.subTest(path=path), self.assertRaisesRegex(AssertionError, "escapes"): + startup.installed_payload({"installedPath": str(path)}, root) + valid = cache / "gitkb/gitkb/0.1.2" + valid.mkdir(parents=True) + (valid / "payload").write_text("approved") + self.assertEqual(startup.installed_payload({"installedPath": str(valid)}, root), + startup.payload_fingerprint(valid)) + + def test_optimized_context_check_rejects_missing_or_leaked_values(self): + """Exercise context mismatch and secret leakage checks in an actual -O interpreter.""" + for observed, expected in (({}, {"SESSION_ACTIVITY_RESOURCE_ID": "alpha"}), + ({"OPENAI_API_KEY": "synthetic-canary"}, {})): + with self.subTest(observed=observed): + code = ("import importlib.util; " + f"s=importlib.util.spec_from_file_location('startup', {str(SCRIPT)!r}); " + "m=importlib.util.module_from_spec(s); s.loader.exec_module(m); " + f"m.check_context({observed!r}, {expected!r}, 'negative control')") + result = subprocess.run([sys.executable, "-O", "-B", "-c", code], + capture_output=True, text=True, timeout=10) + self.assertNotEqual(result.returncode, 0) + self.assertIn("AssertionError", result.stderr) + + +class ProtocolTests(unittest.TestCase): + def exercise(self, mode, optimized=False): + """Exercise faults in an owned fake app-server; its PID must be gone on return.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + fake = root / 'fake-codex' + capture = root / 'context.json' + fake.write_text('#!' + sys.executable + '\n' + '''import json, os, signal, subprocess, sys, time +from pathlib import Path +root = Path(__file__).parent +(root / 'pid').write_text(str(os.getpid())) +mode = ''' + repr(mode) + ''' +if mode == 'descendant': + code = 'import os, signal, time; from pathlib import Path; signal.signal(signal.SIGTERM, signal.SIG_IGN); Path(' + repr(str(root / 'child-pid')) + ').write_text(str(os.getpid())); time.sleep(30)' + subprocess.Popen([sys.executable, '-c', code]) + deadline = time.monotonic() + 5 + while not (root / 'child-pid').exists() and time.monotonic() < deadline: + time.sleep(0.01) + print('{invalid json', flush=True) + time.sleep(30) +elif mode == 'timeout': + time.sleep(30) +elif mode == 'eof': + sys.stderr.write('synthetic diagnostic\\n') + sys.exit(0) +elif mode == 'flood': + sys.stdout.write('x' * (2 * 1024 * 1024)) + sys.stdout.flush() + time.sleep(30) +elif mode == 'malformed': + print('{invalid json', flush=True) + time.sleep(30) +else: + for line in sys.stdin: + request = json.loads(line) + if 'id' not in request: + continue + result = {} if request['id'] == 1 else {'data': [ + {'name': 'gitkb', 'pluginId': 'wrong' if mode == 'identity' else 'gitkb@gitkb', + 'tools': {} if mode == 'tools' else {'context_probe': {}}}]} + if mode != 'capture': + (root / 'context.json').write_text('{}') + print(json.dumps({'id': request['id'], 'result': result}), flush=True) +''') + fake.chmod(0o755) + env = {'PATH': os.defpath, 'HOME': directory} + if optimized: + probe = root / 'probe.py' + probe.write_text('import importlib.util\nfrom pathlib import Path\n' + f'spec = importlib.util.spec_from_file_location("startup", {str(SCRIPT)!r})\n' + 'module = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(module)\n' + f'module.inspect_child({str(fake)!r}, {env!r}, Path({directory!r}), ' + f'Path({str(capture)!r}), response_timeout=1)\n') + result = subprocess.run([sys.executable, '-O', '-B', str(probe)], + env=env, capture_output=True, text=True, timeout=10) + self.assertNotEqual(result.returncode, 0, 'optimized Python accepted invalid MCP state') + self.assertIn('AssertionError', result.stderr) + else: + with self.assertRaises(AssertionError) as failure: + startup.inspect_child(str(fake), env, root, capture, response_timeout=1) + if mode == 'eof': + self.assertIn('synthetic diagnostic', str(failure.exception)) + if mode == 'flood': + self.assertIn('limit', str(failure.exception)) + pid = int((root / 'pid').read_text()) + with self.assertRaises(ProcessLookupError): + os.kill(pid, 0) + if mode == 'descendant': + child = int((root / 'child-pid').read_text()) + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + state = subprocess.run(['ps', '-p', str(child), '-o', 'stat='], + capture_output=True, text=True, timeout=5).stdout.strip() + if not state or state.startswith('Z'): + break # A zombie is stopped; the host's init process owns its reaping. + time.sleep(0.05) + else: + self.fail('TERM-resistant owned descendant survived cleanup') + + def test_faults_fail_and_reap_the_app_server(self): + """Fail closed on timeout, EOF, malformed/flooding output, wrong identity/tools, or no child.""" + for mode in ('timeout', 'eof', 'flood', 'malformed', 'identity', 'tools', 'capture', 'descendant'): + with self.subTest(mode=mode): + self.exercise(mode) + + def test_optimized_python_keeps_security_checks(self): + """Python -O must not disable installed identity/tool/child checks.""" + for mode in ('identity', 'tools', 'capture'): + with self.subTest(mode=mode): + self.exercise(mode, optimized=True) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/mcp-startup.py b/tests/mcp-startup.py index 328478a..d3acce4 100644 --- a/tests/mcp-startup.py +++ b/tests/mcp-startup.py @@ -12,6 +12,7 @@ import shlex import shutil import signal +import stat import subprocess import sys import tempfile @@ -36,10 +37,10 @@ def run(codex, args, env, cwd): return result.stdout -def inspect_child(codex, env, root, capture): +def inspect_child(codex, env, root, capture, *, response_timeout=15): """Negotiate packaged MCP tools, capture context, and clean up the owned process group.""" capture.unlink(missing_ok=True) - with (root / "stderr.log").open("w+") as stderr: + with (root / "stderr.log").open("w+b") as stderr: process = subprocess.Popen([codex, "app-server"], env=env, cwd=root, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, start_new_session=True) @@ -49,29 +50,43 @@ def inspect_child(codex, env, root, capture): def send(message): """Write one newline-delimited app-server request or notification.""" - process.stdin.write((json.dumps(message) + "\n").encode()) - process.stdin.flush() + try: + process.stdin.write((json.dumps(message) + "\n").encode()) + process.stdin.flush() + except BrokenPipeError as error: + raise AssertionError(f"App-server closed stdin during {message['method']}") from error def response(request_id): """Read the matching reply with a deadline, ignoring asynchronous notifications.""" - deadline = time.monotonic() + 15 + deadline = time.monotonic() + response_timeout while time.monotonic() < deadline: - while b"\n" in pending: + while b"\n" in pending and time.monotonic() < deadline: line, _, rest = pending.partition(b"\n") pending[:] = rest - message = json.loads(line) + try: + message = json.loads(line) + except (ValueError, UnicodeDecodeError) as error: + raise AssertionError(f"Invalid app-server JSON while waiting for {request_id}") from error + if not isinstance(message, dict): + raise AssertionError(f"Invalid app-server message while waiting for {request_id}") if message.get("id") == request_id: if "error" in message: raise AssertionError(message["error"]) + if "result" not in message: + raise AssertionError(f"App-server response {request_id} has no result") return message["result"] if selector.select(timeout=0.1): chunk = os.read(process.stdout.fileno(), 65536) if not chunk: break pending.extend(chunk) + if len(pending) > 1024 * 1024: + raise AssertionError(f"App-server output exceeds 1 MiB limit for {request_id}") stderr.flush() - stderr.seek(0) - raise AssertionError(f"No response to {request_id}: {stderr.read()[-4000:]}") + stderr.seek(0, os.SEEK_END) + stderr.seek(max(0, stderr.tell() - 4000)) + diagnostic = stderr.read(4000).decode("utf-8", errors="replace") + raise AssertionError(f"No response to {request_id} (timeout or EOF): {diagnostic}") try: send({"id": 1, "method": "initialize", "params": { @@ -81,30 +96,68 @@ def response(request_id): send({"method": "initialized"}) send({"id": 2, "method": "mcpServerStatus/list", "params": {}}) servers = response(2)["data"] - server = next(item for item in servers if item["name"] == "gitkb") - assert server["pluginId"] == "gitkb@gitkb", server - assert "context_probe" in server["tools"], server - assert capture.exists(), "packaged MCP child did not start" + matches = [item for item in servers if item.get("name") == "gitkb"] + if len(matches) != 1 or matches[0].get("pluginId") != "gitkb@gitkb": + raise AssertionError(f"Expected one packaged gitkb@gitkb server: {matches}") + if "context_probe" not in matches[0].get("tools", {}): + raise AssertionError(f"Packaged MCP probe tool missing: {matches[0]}") + if not capture.is_file(): + raise AssertionError("Packaged MCP child did not start") return json.loads(capture.read_text()) finally: selector.close() try: os.killpg(process.pid, signal.SIGTERM) - except ProcessLookupError: - pass + except (ProcessLookupError, PermissionError): + if process.poll() is None: + raise try: process.wait(timeout=5) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait(timeout=5) + # A descendant may ignore TERM even if the app-server itself exits promptly. + try: + os.killpg(process.pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + if process.poll() is None: + raise process.stdin.close() process.stdout.close() def payload_fingerprint(root): """Hash the package tree so source resolution cannot silently install another payload.""" - return {str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest() - for path in root.rglob("*") if path.is_file()} + if root.is_symlink() or not root.is_dir(): + raise AssertionError(f"Missing package directory or symlink: {root}") + fingerprint = {} + for path in root.rglob("*"): + mode = path.lstat().st_mode + if stat.S_ISDIR(mode): + continue + if not stat.S_ISREG(mode): + raise AssertionError(f"Package entry must be a regular file, not a symlink or special file: {path}") + with path.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + fingerprint[str(path.relative_to(root))] = (bool(mode & 0o111), digest) + if not fingerprint: + raise AssertionError(f"Empty package: {root}") + return fingerprint + + +def installed_payload(receipt, root): + """Read only an installed cache beneath the fixture's isolated Codex home.""" + installed = Path(receipt["installedPath"]) + cache = (root / "codex/plugins/cache").resolve() + if not installed.is_absolute() or not installed.resolve().is_relative_to(cache): + raise AssertionError(f"Installed path escapes isolated plugin cache: {installed}") + return payload_fingerprint(installed) + + +def check_context(observed, expected, label): + """Keep exact context and credential checks active even under optimized Python.""" + if observed != expected: + raise AssertionError(f"{label}: expected {expected}, got {observed}") def main(): @@ -112,6 +165,8 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--codex", required=True, help="Provider Codex binary, not an ATC shim") parser.add_argument("--marketplace", default=".") + parser.add_argument("--legacy-first", action="store_true", + help="Upgrade an installed bundled 0.1.0 package in the same Codex home") parser.add_argument("--expected-plugin-root", type=Path, default=Path(__file__).resolve().parents[1] / "plugin", help="Canonical package to compare with the installed cache") @@ -164,13 +219,44 @@ def main(): if node: # npm Codex launchers use /usr/bin/env node; keep that interpreter reachable. base_env["PATH"] += os.pathsep + str(Path(node).parent) - run(codex, ["plugin", "marketplace", "add", marketplace, "--json"], base_env, root) - receipt = json.loads(run(codex, ["plugin", "add", "gitkb@gitkb", "--json"], base_env, root)) expected_root = args.expected_plugin_root.resolve() if not (expected_root / ".codex-plugin/plugin.json").is_file(): raise AssertionError(f"Missing canonical package: {expected_root}") expected_payload = payload_fingerprint(expected_root) - actual_payload = payload_fingerprint(Path(receipt["installedPath"])) + if args.legacy_first: + # A temporary old catalog/package is a test fixture, never another maintained source. + old_catalog = root / "legacy-marketplace" + catalog_path = old_catalog / ".agents/plugins/marketplace.json" + catalog_path.parent.mkdir(parents=True) + old_plugin = old_catalog / "plugin" + shutil.copytree(expected_root, old_plugin) + manifest_path = old_plugin / ".codex-plugin/plugin.json" + manifest = json.loads(manifest_path.read_text()) + manifest["version"] = "0.1.0" + manifest_path.write_text(json.dumps(manifest)) + mcp_path = old_plugin / ".mcp.json" + mcp = json.loads(mcp_path.read_text()) + mcp["mcpServers"]["gitkb"].pop("env_vars", None) + mcp_path.write_text(json.dumps(mcp)) + target_catalog = Path(marketplace) / ".agents/plugins/marketplace.json" + legacy_catalog = json.loads(target_catalog.read_text()) + legacy_catalog["plugins"][0]["source"] = {"source": "local", "path": "./plugin"} + catalog_path.write_text(json.dumps(legacy_catalog)) + run(codex, ["plugin", "marketplace", "add", str(old_catalog), "--json"], base_env, root) + legacy = json.loads(run(codex, ["plugin", "add", "gitkb@gitkb", "--json"], base_env, root)) + if legacy.get("version") != "0.1.0" or installed_payload(legacy, root) != payload_fingerprint(old_plugin): + raise AssertionError("Legacy fixture was not installed") + legacy_env = dict(base_env, **{name: "synthetic-canary" for name in NAMES + FORBIDDEN}) + check_context(inspect_child(codex, legacy_env, root, capture), {}, "legacy missing-context control") + # Publish the target catalog into that same registered directory, retaining installation identity. + shutil.rmtree(old_plugin) + shutil.copytree(expected_root, old_plugin) + catalog_path.write_text(target_catalog.read_text()) + print("PASS: legacy 0.1.0 missing-context control; upgrading existing installation") + else: + run(codex, ["plugin", "marketplace", "add", marketplace, "--json"], base_env, root) + receipt = json.loads(run(codex, ["plugin", "add", "gitkb@gitkb", "--json"], base_env, root)) + actual_payload = installed_payload(receipt, root) if actual_payload != expected_payload: changed = sorted(path for path in actual_payload.keys() | expected_payload.keys() if actual_payload.get(path) != expected_payload.get(path)) @@ -184,7 +270,7 @@ def main(): str(root / f"{session} registry"), str(root / f"{session} config.toml")))) env = dict(base_env, **expected, **{name: "synthetic-canary" for name in FORBIDDEN}) observed = inspect_child(codex, env, root, capture) - assert observed == expected, f"{session or 'unshimmed'}: expected {expected}, got {observed}" + check_context(observed, expected, session or "unshimmed") print(f"PASS: {session or 'unshimmed'} MCP context and credential isolation") From d6b67ba8b244a9072996d63636bb8bf614ffc207 Mon Sep 17 00:00:00 2001 From: Matt Walters Date: Wed, 30 Sep 2026 11:10:52 -0500 Subject: [PATCH 5/5] test: select legacy fixture plugin by identity [[tasks/harmony-2016]] --- tests/mcp-startup-unit.py | 12 +++++++++++- tests/mcp-startup.py | 10 +++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/tests/mcp-startup-unit.py b/tests/mcp-startup-unit.py index 9632bdd..1839064 100644 --- a/tests/mcp-startup-unit.py +++ b/tests/mcp-startup-unit.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 """Negative controls for the shared real-Codex launch harness.""" import importlib.util -import json import os import subprocess import sys @@ -89,6 +88,17 @@ def test_optimized_context_check_rejects_missing_or_leaked_values(self): self.assertNotEqual(result.returncode, 0) self.assertIn("AssertionError", result.stderr) + def test_legacy_fixture_selects_one_entry_by_name(self): + """Adding another catalog entry must not silently change the upgrade control's target.""" + other = {"name": "other", "source": {"source": "local", "path": "./other"}} + catalog = {"plugins": [other, {"name": "gitkb", "source": {"source": "git-subdir"}}]} + startup.use_legacy_source(catalog) + self.assertEqual(catalog["plugins"][0]["source"], {"source": "local", "path": "./other"}) + self.assertEqual(catalog["plugins"][1]["source"], {"source": "local", "path": "./plugin"}) + for entries in ([], [other], [{"name": "gitkb"}, {"name": "gitkb"}]): + with self.subTest(entries=entries), self.assertRaises(AssertionError): + startup.use_legacy_source({"plugins": entries}) + class ProtocolTests(unittest.TestCase): def exercise(self, mode, optimized=False): diff --git a/tests/mcp-startup.py b/tests/mcp-startup.py index d3acce4..3e25993 100644 --- a/tests/mcp-startup.py +++ b/tests/mcp-startup.py @@ -160,6 +160,14 @@ def check_context(observed, expected, label): raise AssertionError(f"{label}: expected {expected}, got {observed}") +def use_legacy_source(catalog): + """Point exactly one named GitKB entry at the temporary legacy fixture.""" + entries = [entry for entry in catalog["plugins"] if entry.get("name") == "gitkb"] + if len(entries) != 1: + raise AssertionError(f"Expected one gitkb catalog entry: {entries}") + entries[0]["source"] = {"source": "local", "path": "./plugin"} + + def main(): """Verify session isolation and the credential boundary through a real package install.""" parser = argparse.ArgumentParser(description=__doc__) @@ -240,7 +248,7 @@ def main(): mcp_path.write_text(json.dumps(mcp)) target_catalog = Path(marketplace) / ".agents/plugins/marketplace.json" legacy_catalog = json.loads(target_catalog.read_text()) - legacy_catalog["plugins"][0]["source"] = {"source": "local", "path": "./plugin"} + use_legacy_source(legacy_catalog) catalog_path.write_text(json.dumps(legacy_catalog)) run(codex, ["plugin", "marketplace", "add", str(old_catalog), "--json"], base_env, root) legacy = json.loads(run(codex, ["plugin", "add", "gitkb@gitkb", "--json"], base_env, root))