From e0ce95d62bf61506aada1bad11bb4e12fa51a486 Mon Sep 17 00:00:00 2001 From: CH <340279802+connabyss@users.noreply.github.com> Date: Sat, 5 Dec 2026 18:30:19 +0000 Subject: [PATCH 1/4] feat(fuzz): hunt crashes in everything Bite reads, fix the 3 it found A second Atheris harness (tests/fuzz_parsers.py) feeds random and structured input to the MCP server, the live hook's transcript reader, test-output, commit-title, source and diff readers, and .bite.ini. It found: - one MCP message with params or arguments that aren't an object (or a tool name that's a list) killed bite mcp for the rest of the session - a transcript line that's JSON but not an object crashed the live hook's turn start - a .bite.ini folder no OS can open raised an OSError traceback instead of a ConfigError Each is fixed, with tests/test_fuzz_finds.py (11 of its 12 cases fail without the fixes). fuzz.yml gets a crashes job: 1 minute on PRs that touch these files, 10 minutes weekly. Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iFQY4M9menF61MoP2s --- .github/requirements/atheris.txt | 2 +- .github/workflows/fuzz.yml | 33 +++++- bite_mcp.py | 16 ++- docs/security-design.md | 6 +- live.py | 5 +- repo.py | 3 + tests/fuzz_parsers.py | 175 +++++++++++++++++++++++++++++++ tests/test_fuzz_finds.py | 71 +++++++++++++ 8 files changed, 304 insertions(+), 7 deletions(-) create mode 100644 tests/fuzz_parsers.py create mode 100644 tests/test_fuzz_finds.py diff --git a/.github/requirements/atheris.txt b/.github/requirements/atheris.txt index 9d5622a..8192e59 100644 --- a/.github/requirements/atheris.txt +++ b/.github/requirements/atheris.txt @@ -1,4 +1,4 @@ -# Atheris (coverage-guided fuzzing) for tests/fuzz_atheris.py (the worker command filter) in .github/workflows/fuzz.yml. +# Atheris (coverage-guided fuzzing) for tests/fuzz_atheris.py (security lines) and tests/fuzz_parsers.py (crashes) in .github/workflows/fuzz.yml. # Hash-pinned (Scorecard Pinned-Dependencies). Linux x86-64 wheels only; the fuzz job runs on ubuntu-latest. atheris==3.1.0 \ --hash=sha256:ec5e11f21a4c197fe91f7aea2b2de88e623c73a21fc07b105ac6329a1588457b \ diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 1f35873..4d9097c 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -7,11 +7,14 @@ name: fuzz # rerun name the shell would expand is a find. 10 minutes weekly, 1 minute on pull requests that touch that code. # A find fails the run, which emails the maintainer. It opens no public issue on purpose: a way past these lines is # a security hole, and SECURITY.md asks for those to stay private until fixed. +# A second job runs tests/fuzz_parsers.py, which hunts plain crashes in everything that reads text Bite didn't +# write (MCP messages, the live hook's transcript, test output, commit titles, source files, diffs, .bite.ini). +# A crash there is a bug, not a way past a security line, so its traceback is printed to help fix it. on: schedule: - cron: "29 6 * * 3" # Wednesdays 06:29 UTC pull_request: - paths: ["bite.py", "recent.py", "tests/fuzz_atheris.py", "tests/fuzz_oracle.py", ".github/requirements/atheris.txt", ".github/workflows/fuzz.yml"] + paths: ["bite.py", "recent.py", "repo.py", "live.py", "bite_mcp.py", "tests/fuzz_atheris.py", "tests/fuzz_parsers.py", "tests/fuzz_oracle.py", ".github/requirements/atheris.txt", ".github/workflows/fuzz.yml"] workflow_dispatch: permissions: {} @@ -48,3 +51,31 @@ jobs: echo "::error::The fuzzer found a problem in the command filter. Details are kept off this public log: rerun tests/fuzz_atheris.py locally." fi exit "$status" + + crashes: + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + - name: coverage-guided crash hunt (Atheris) + shell: bash + run: | + python -m pip install --require-hashes --no-deps -r .github/requirements/atheris.txt + secs=${{ github.event_name == 'pull_request' && 60 || 600 }} + mkdir -p corpus + status=0 + python tests/fuzz_parsers.py corpus -max_total_time="$secs" -timeout=30 -print_final_stats=1 > parsers.log 2>&1 || status=$? + grep -E '^stat::number_of_executed_units' parsers.log || true + if [ "$status" != 0 ]; then + # Not a security line: show the crash so it can be fixed (add the input to tests/test_fuzz_finds.py). + grep -v -E '^(#[0-9]+|INFO:|WARNING:)' parsers.log | tail -n 60 + echo "::error::The crash hunt found an input that makes Bite raise. The traceback is above." + fi + exit "$status" diff --git a/bite_mcp.py b/bite_mcp.py index 86a4143..1831b90 100644 --- a/bite_mcp.py +++ b/bite_mcp.py @@ -148,6 +148,8 @@ def answer(msg: dict): if "id" not in msg: return None # notifications (initialized, cancelled) need no reply params = msg.get("params") or {} + if not isinstance(params, dict): # a list, a string or a number from a broken client: say so, stay up + return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": "Invalid params: expected an object"}} if method == "initialize": from recent import _installed_version result = {"protocolVersion": params.get("protocolVersion") or PROTOCOL, @@ -160,12 +162,16 @@ def answer(msg: dict): elif method == "tools/list": result = {"tools": [TOOL, ASK]} elif method == "tools/call": - run = TOOLS.get(params.get("name")) + name, args = params.get("name"), params.get("arguments") or {} + run = TOOLS.get(name) if isinstance(name, str) else None + if run is not None and not isinstance(args, dict): + return {"jsonrpc": "2.0", "id": mid, + "error": {"code": -32602, "message": "Invalid params: arguments must be an object"}} if run is None: return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": f"Unknown tool: {params.get('name')}"}} try: - text, err = run(params.get("arguments") or {}) + text, err = run(args) except Exception as e: # a broken check is reported to the AI, never a dead server text, err = f"Bite's check stopped with an error: {type(e).__name__}: {e}", True result = {"content": [{"type": "text", "text": text}], "isError": err} @@ -185,7 +191,11 @@ def serve(inp, out) -> int: except ValueError: reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}} else: - reply = answer(msg) + try: + reply = answer(msg) + except Exception as e: # one odd message must never take the server down for the rest of the session + reply = {"jsonrpc": "2.0", "id": msg.get("id") if isinstance(msg, dict) else None, + "error": {"code": -32603, "message": f"Internal error: {type(e).__name__}"}} if reply is not None: out.write(json.dumps(reply, ensure_ascii=False).encode("utf-8") + b"\n") out.flush() diff --git a/docs/security-design.md b/docs/security-design.md index 5fd45d6..dafb6bd 100644 --- a/docs/security-design.md +++ b/docs/security-design.md @@ -90,5 +90,9 @@ What you can and can't expect from Bite in terms of security, and why we think t - About 670 offline tests on Linux, macOS and Windows, at least 80% statement coverage, enforced in CI. - [Atheris](https://github.com/google/atheris) fuzzing of the command filter, the worker's file access and the - rerun command: 1 minute on pull requests that touch them, 10 minutes every week (`.github/workflows/fuzz.yml`). + rerun command (`tests/fuzz_atheris.py`), and of every reader of text Bite didn't write: MCP messages, the + Claude Code hook's transcript, test output, commit titles, source files, diffs and `.bite.ini` + (`tests/fuzz_parsers.py`, which checks they never crash). 1 minute each on pull requests that touch them, + 10 minutes each every week (`.github/workflows/fuzz.yml`). Inputs it once crashed on stay fixed in + `tests/test_fuzz_finds.py`. - CodeQL and OpenSSF Scorecard on every merge to `main`; Dependabot for dependencies; ruff in CI. diff --git a/live.py b/live.py index 7d942c8..dc4314e 100644 --- a/live.py +++ b/live.py @@ -179,7 +179,10 @@ def turn_start(data: dict) -> float: rec = json.loads(line) except ValueError: continue - content = (rec.get("message") or {}).get("content") + if not isinstance(rec, dict): + continue # a line that's JSON but not a record ("x", 3, [...]) says nothing about who wrote + message = rec.get("message") + content = message.get("content") if isinstance(message, dict) else None blocks = content if isinstance(content, list) else [] if rec.get("type") == "user" and not any(isinstance(b, dict) and b.get("type") == "tool_result" for b in blocks): started = stamp(rec.get("timestamp")) # the person wrote (tool results are logged as "user" too) diff --git a/repo.py b/repo.py index 5a9ba9c..9e83c56 100644 --- a/repo.py +++ b/repo.py @@ -164,6 +164,9 @@ def load_cfg(root: Path): "a line isn't in the form name = value" if isinstance(e, configparser.ParsingError) else type(e).__name__) raise ConfigError(f"Bite can't read {ini.name}: {why}. Fix that line and run Bite again.") from None + except OSError as e: # a folder setting no system can look at (a name too long, a character it refuses) + raise ConfigError(f"Bite can't read {ini.name}: a folder in it can't be opened ({e.strerror or type(e).__name__}). " + "Fix that path, or take that line out to use the default.") from None except ValueError as e: # a number setting that isn't a number raise ConfigError(f"Bite can't read {ini.name}: a setting that needs a number has {str(e).split(': ', 1)[-1]}. " "Fix it, or take that line out to use the default.") from None diff --git a/tests/fuzz_parsers.py b/tests/fuzz_parsers.py new file mode 100644 index 0000000..c13e53c --- /dev/null +++ b/tests/fuzz_parsers.py @@ -0,0 +1,175 @@ +"""Coverage-guided fuzzer for the places where Bite reads text it didn't write (Atheris, Google's libFuzzer for Python). + +tests/fuzz_atheris.py attacks Bite's security lines. This one hunts plain crashes: a stack trace where Bite should +have said something or kept going. Each input picks one reader and feeds it random text, half raw and half built +from real pieces of what that reader sees, and checks it never raises: + +- the MCP server (bite_mcp.serve): any line an MCP client sends gets one JSON reply, never a dead server +- the Claude Code Stop hook (live.turn_start, live.stamp): any transcript line and any timestamp +- the project's test output (recent.failed_ids, caught_by, ran_nothing, all_skipped, repo.failure_excerpt, + bite.auto_count, bite.load_failure) +- commit titles and messages (recent.skip_reason, sounds, flat, short, no_pings, unping, inline_code) +- source files and diffs from the project (recent.py_tree, same_code, doc_lines, keep_docs, keep_rust_tests, + rust_code_same, lines_back, owner, bite.code_lines) +- the AI worker's reply (recent.last_json) +- test commands from .bite.ini (repo.runs_language, recent.one_process, own_workers, jobs_clash) and the + .bite.ini file itself (repo.load_cfg: any text is read, or refused with a one-line repo.ConfigError) + +Not run by pytest (the file name doesn't start with test_). Inputs that once crashed a reader live in +tests/test_fuzz_finds.py, so pytest keeps them fixed without Atheris. + + pip install atheris + python tests/fuzz_parsers.py -max_total_time=120 (any libFuzzer flag works; a crash exits non-zero) +""" +import io +import pathlib +import sys +import tempfile + +import atheris + +KIT = pathlib.Path(__file__).resolve().parent.parent +sys.path.insert(0, str(KIT)) + +with atheris.instrument_imports(): + import bite + import bite_mcp + import live + import recent + import repo + +# Tools stubbed out: a tools/call must reach the argument handling, not run git and the tests on this repo. +bite_mcp.TOOLS = {name: (lambda args: ("ok", False)) for name in bite_mcp.TOOLS} + +JSON_PIECES = ['{', '}', '[', ']', '"jsonrpc":"2.0"', '"id":1', '"id":null', '"id":[1]', '"method":', '"initialize"', + '"tools/call"', '"tools/list"', '"ping"', '"params":', '"name":', '"check_fix"', '"ask_bite"', + '"arguments":', '"folder":"."', '{}', '[]', '"x"', '1', 'null', 'true', ',', ':', '"protocolVersion":', + '"type":"user"', '"message":', '"content":', '"timestamp":', '"2026-12-05T10:00:00Z"', '"tool_result"', + '\\u0000', '\n', '1e999', '-0', '"\\ud800"'] +OUT_PIECES = ["FAILED ", "ERROR ", "tests/t.py::", "test_x", " - boom", "\n", "=== ", " passed", " failed", " skipped", + " in 0.1s", "OK (skipped=3)", "Ran 0 tests", "--- FAIL: TestA", "test result: FAILED.", "Tests: ", + " total", "ModuleNotFoundError", "ImportError while loading conftest", " Failed ", "[1 ms]", + "no tests ran", "collected 0 items", "# fail 1", "not ok 1 - x", "\x1b[31m", "\r", "\t", " ", "::"] +CODE_PIECES = ["def f(x):\n", " return x\n", "class A:\n", ' """doc"""\n', "#[cfg(test)]\n", "mod tests {\n", + "}\n", "{", "/// ```\n", "//! x\n", "fn f() {}\n", "x: int = 1\n", "# c\n", "\n", " ", "\t", + "'''", '"""', "(", ")", "[", "]", "\\\n", "\x00", "\ufeff", "@d\n", "async def g(): pass\n", + "if __name__ == '__main__':\n", "__doc__", "help(f)\n", "import sys\n"] +DIFF_PIECES = ["diff --git a/x b/x\n", "--- a/x\n", "+++ b/x\n", "@@ -1,3 +1,3 @@\n", "@@ -0,0 +1 @@\n", "-", + "+", " ", "removed line here\n", "}\n", "\n", "\\ No newline at end of file\n", "@@"] +CMD_PIECES = ["python -m pytest", " -n auto", " -n 4", " --dist loadfile", " -q", " -x", " -- ", "npm test", "cargo test", + "go test ./...", "dotnet test", "mvn test", "./gradlew test", "pytest", " tests/", '"', "'", " && ", + " ; ", "|", "cd sub", "env X=1", "uv run", "python -m unittest", "\\", " -n", "=", "-k 'a or b'"] +TITLE_PIECES = ["fix", "Fix ", "fixed ", "typo", "docs", "refactor", "speed up", "windows", "macOS", "python 3.8", + "@alice", "`code`", "``", "\\`", "[x](/a`b)", "", "", "**", "for real this time", + "hopefully", "Revert \"", "\n", " ", "\u2060", "#12", "http://x", "(", ")", "[", "]"] +INI_PIECES = ["[bite]\n", "[kit]\n", "[other]\n", "test_command = ", "pytest", "claim_command = ", "{file}", + "test_covers = ", "a/*, b/*", "allowed_programs = ", "python", "budget = ", "1.5", "-1", "nan", "x", + "max_turns = ", "jobs = ", "%(", "%", "\n", " ", "=", ":", "contain_command = ", "{project}", "{cmd}", + "review_only = ", "secrets = ", "key.txt", "timeout = ", "0", "99999999999999999999", "project_folder = "] + + +def pick(fdp, pieces, most): + return "".join(pieces[fdp.ConsumeIntInRange(0, len(pieces) - 1)] for _ in range(fdp.ConsumeIntInRange(1, most))) + + +def text(fdp, pieces, most=20, size=400): + return fdp.ConsumeUnicodeNoSurrogates(size) if fdp.ConsumeBool() else pick(fdp, pieces, most) + + +def mcp(fdp): + lines = [text(fdp, JSON_PIECES, 25).encode("utf-8", "surrogatepass") for _ in range(fdp.ConsumeIntInRange(1, 3))] + if fdp.ConsumeBool(): + lines.append(fdp.ConsumeBytes(200)) + out = io.BytesIO() + bite_mcp.serve(iter(lines), out) + + +def hook(fdp): + live.stamp(text(fdp, ["2026-12-05", "T", "10:00:00", "Z", "+05:00", "-", ":", ".123", "0001-01-01", "9999", + " ", "1", "24:00"], 8, 60)) + with tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False, encoding="utf-8") as f: + f.write("\n".join(text(fdp, JSON_PIECES, 25) for _ in range(fdp.ConsumeIntInRange(1, 3)))) + try: + live.turn_start({"transcript_path": f.name}) + finally: + pathlib.Path(f.name).unlink() + + +def test_output(fdp): + out = text(fdp, OUT_PIECES, 40, 600) + cmd = text(fdp, CMD_PIECES, 6, 80) + recent.failed_ids(out) + recent.caught_by(out) + recent.ran_nothing(cmd, out) + recent.all_skipped(out) + repo.failure_excerpt(out) + bite.auto_count(out) + bite.load_failure(out) + + +def titles(fdp): + subject = text(fdp, TITLE_PIECES, 12, 200) + said = text(fdp, TITLE_PIECES, 20, 400) + recent.skip_reason(subject, said, text(fdp, CODE_PIECES, 10, 200) if fdp.ConsumeBool() else None) + recent.sounds(subject, fdp.PickValueInList(["held", "unguarded", "blind"]), + fdp.PickValueInList(sorted(recent.NONE_NOTICED) + ["x"])) + recent.flat(said) + recent.short(subject, fdp.ConsumeIntInRange(1, 80)) + recent.unping(subject) + recent.inline_code(subject) + recent.no_pings(said.split("\n")) + + +def code(fdp): + old = text(fdp, CODE_PIECES, 25, 500).encode("utf-8", "surrogatepass") + new = text(fdp, CODE_PIECES, 25, 500).encode("utf-8", "surrogatepass") if fdp.ConsumeBool() else fdp.ConsumeBytes(300) + suf = fdp.PickValueInList([".py", ".rs", ".js", ".go", ".java", ".cs", ".txt", ""]) + recent.py_tree(old, fdp.ConsumeBool()) + recent.same_code(old, new, suf, fdp.ConsumeBool()) + recent.doc_lines(new) + recent.keep_docs(old, new) + recent.keep_rust_tests(old, new) + recent.rust_code_same(old, new) + lines = new.decode("utf-8", "replace").splitlines() + recent.owner(lines, fdp.ConsumeIntInRange(0, len(lines) + 2)) + bite.code_lines(old.decode("utf-8", "replace"), suf) + recent.lines_back(text(fdp, DIFF_PIECES, 30, 500).encode("utf-8", "surrogatepass")) + + +def commands(fdp): + cmd = text(fdp, CMD_PIECES, 10, 200) + repo.runs_language(cmd) + recent.one_process(cmd) + recent.own_workers(cmd) + recent.jobs_clash(cmd) + recent.last_json(text(fdp, JSON_PIECES, 30, 500)) + + +def config(fdp): + folder = pathlib.Path(tempfile.mkdtemp(prefix="bite_fuzz_ini_")) + ini = folder / ".bite.ini" + ini.write_text(text(fdp, INI_PIECES, 30, 500), encoding="utf-8", errors="surrogatepass") + try: + repo.load_cfg(folder) + except repo.ConfigError: + pass # refused with a reason the CLI prints in one line + finally: + ini.unlink() + folder.rmdir() + + +TARGETS = [mcp, hook, test_output, titles, code, commands, config] + + +def one_input(data): + fdp = atheris.FuzzedDataProvider(data) + TARGETS[fdp.ConsumeIntInRange(0, len(TARGETS) - 1)](fdp) + + +def main(): + atheris.Setup(sys.argv, one_input) + atheris.Fuzz() + + +if __name__ == "__main__": + main() diff --git a/tests/test_fuzz_finds.py b/tests/test_fuzz_finds.py new file mode 100644 index 0000000..e2b4e21 --- /dev/null +++ b/tests/test_fuzz_finds.py @@ -0,0 +1,71 @@ +"""Inputs the fuzzer (tests/fuzz_parsers.py) once crashed Bite with, kept here so pytest holds them fixed without +Atheris. Each one was a stack trace where Bite should have answered or carried on.""" + +import io +import json +import sys +from pathlib import Path + +import pytest + +KIT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(KIT)) +import bite_mcp # noqa: E402 +import live # noqa: E402 +import repo # noqa: E402 + + +def serve(*msgs): + out = io.BytesIO() + bite_mcp.serve([json.dumps(m).encode() for m in msgs], out) + return [json.loads(line) for line in out.getvalue().splitlines()] + + +@pytest.mark.parametrize("params", ["x", [1], 3, True]) +def test_mcp_params_that_arent_an_object_get_an_error_not_a_dead_server(params): + replies = serve({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params}, + {"jsonrpc": "2.0", "id": 2, "method": "ping"}) + assert replies[0]["error"]["code"] == -32602 and replies[0]["id"] == 1 + assert replies[1] == {"jsonrpc": "2.0", "id": 2, "result": {}} # still serving + + +def test_mcp_initialize_with_list_params_gets_an_error(): + reply, = serve({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": [1]}) + assert reply["error"]["code"] == -32602 + + +@pytest.mark.parametrize("name", [[1], {"a": 1}, 5]) +def test_mcp_a_tool_name_that_isnt_text_is_an_unknown_tool(name): + reply, = serve({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name}}) + assert reply["error"]["code"] == -32602 and "Unknown tool" in reply["error"]["message"] + + +def test_mcp_arguments_that_arent_an_object_get_an_error(): + reply, = serve({"jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": "check_fix", "arguments": [1]}}) + assert reply["error"]["code"] == -32602 and "arguments" in reply["error"]["message"] + + +def test_mcp_an_unexpected_error_is_answered_and_the_server_stays_up(monkeypatch): + def broken(msg): + raise KeyError("x") + monkeypatch.setattr(bite_mcp, "answer", broken) + reply, = serve({"jsonrpc": "2.0", "id": 9, "method": "ping"}) + assert reply["id"] == 9 and reply["error"]["code"] == -32603 + + +def test_live_hook_skips_transcript_lines_that_arent_records(tmp_path): + t = tmp_path / "t.jsonl" + lines = ['"x"', "3", "[1]", "null", '{"type": "user", "message": "hi"}', + '{"type": "user", "message": {"content": "go"}, "timestamp": "2026-12-05T10:00:00Z"}'] + t.write_text("\n".join(lines), encoding="utf-8") + assert live.turn_start({"transcript_path": str(t)}) == live.stamp("2026-12-05T10:00:00Z") + + +def test_a_folder_setting_no_system_can_open_is_a_config_error_not_a_traceback(tmp_path, monkeypatch): + monkeypatch.delenv("BITE_CONFIG", raising=False) + (tmp_path / ".bite.ini").write_text("[bite]\nproject_folder = " + "x" * 300 + "\n", encoding="utf-8") + try: + repo.load_cfg(tmp_path) + except repo.ConfigError as e: + assert "can't be opened" in str(e) From 66d66104febf9ca2c84127cb3e726e171ca909bd Mon Sep 17 00:00:00 2001 From: CH <340279802+connabyss@users.noreply.github.com> Date: Sat, 5 Dec 2026 18:45:40 +0000 Subject: [PATCH 2/4] fix(live): keep the turn start when a broken record follows it; fuzz structured JSON - A user record whose message isn't an object is skipped instead of resetting the turn start to 0 (CodeRabbit). - The config fuzz target clears BITE_CONFIG so it always reads its own .bite.ini (CodeRabbit). - The MCP and transcript targets now also build JSON with any value type in any slot; that finds the non-object params crash against the old bite_mcp.py within seconds. Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iFQY4M9menF61MoP2s --- live.py | 6 +++-- tests/fuzz_parsers.py | 50 ++++++++++++++++++++++++++++++++++++++-- tests/test_fuzz_finds.py | 8 +++++++ 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/live.py b/live.py index dc4314e..1c174d0 100644 --- a/live.py +++ b/live.py @@ -181,8 +181,10 @@ def turn_start(data: dict) -> float: continue if not isinstance(rec, dict): continue # a line that's JSON but not a record ("x", 3, [...]) says nothing about who wrote - message = rec.get("message") - content = message.get("content") if isinstance(message, dict) else None + message = rec.get("message") or {} + if not isinstance(message, dict): + continue # a record whose message is a string or a list can't be told apart from a tool result + content = message.get("content") blocks = content if isinstance(content, list) else [] if rec.get("type") == "user" and not any(isinstance(b, dict) and b.get("type") == "tool_result" for b in blocks): started = stamp(rec.get("timestamp")) # the person wrote (tool results are logged as "user" too) diff --git a/tests/fuzz_parsers.py b/tests/fuzz_parsers.py index c13e53c..98b850c 100644 --- a/tests/fuzz_parsers.py +++ b/tests/fuzz_parsers.py @@ -22,6 +22,8 @@ python tests/fuzz_parsers.py -max_total_time=120 (any libFuzzer flag works; a crash exits non-zero) """ import io +import json +import os import pathlib import sys import tempfile @@ -38,6 +40,8 @@ import recent import repo +os.environ.pop("BITE_CONFIG", None) # the config target must read its own .bite.ini, not one named outside + # Tools stubbed out: a tools/call must reach the argument handling, not run git and the tests on this repo. bite_mcp.TOOLS = {name: (lambda args: ("ok", False)) for name in bite_mcp.TOOLS} @@ -76,8 +80,49 @@ def text(fdp, pieces, most=20, size=400): return fdp.ConsumeUnicodeNoSurrogates(size) if fdp.ConsumeBool() else pick(fdp, pieces, most) +def value(fdp, depth=0): + """Any JSON value: a broken client sends a list where an object goes, a number where a name goes.""" + kind = fdp.ConsumeIntInRange(0, 5 if depth < 3 else 3) + if kind == 0: + return None + if kind == 1: + return fdp.ConsumeBool() + if kind == 2: + return fdp.ConsumeInt(4) if fdp.ConsumeBool() else fdp.ConsumeRegularFloat() + if kind == 3: + return fdp.PickValueInList(WORDS) if fdp.ConsumeBool() else fdp.ConsumeUnicodeNoSurrogates(30) + if kind == 4: + return [value(fdp, depth + 1) for _ in range(fdp.ConsumeIntInRange(0, 3))] + return {fdp.PickValueInList(WORDS): value(fdp, depth + 1) for _ in range(fdp.ConsumeIntInRange(0, 4))} + + +WORDS = ["jsonrpc", "2.0", "id", "method", "params", "name", "arguments", "initialize", "ping", "tools/list", + "tools/call", "check_fix", "ask_bite", "folder", "since", "question", "last", "protocolVersion", "type", + "user", "message", "content", "timestamp", "tool_result", "2026-12-05T10:00:00Z", ""] + + +def message(fdp): + """A JSON-RPC message with the right keys and any values in them.""" + msg = {"jsonrpc": "2.0", "id": value(fdp), "method": fdp.PickValueInList(WORDS[7:11]), "params": value(fdp)} + if fdp.ConsumeBool(): + msg["params"] = {"name": fdp.PickValueInList(WORDS[11:13]) if fdp.ConsumeBool() else value(fdp), + "arguments": value(fdp), "protocolVersion": value(fdp)} + for key in list(msg): + if fdp.ConsumeIntInRange(0, 7) == 0: + del msg[key] + return json.dumps(msg) + + +def record(fdp): + """A transcript line shaped like Claude Code's, with any values in it.""" + rec = {"type": fdp.PickValueInList(["user", "assistant"]) if fdp.ConsumeBool() else value(fdp), + "message": {"content": value(fdp)} if fdp.ConsumeBool() else value(fdp), "timestamp": value(fdp)} + return json.dumps(rec if fdp.ConsumeBool() else value(fdp)) + + def mcp(fdp): - lines = [text(fdp, JSON_PIECES, 25).encode("utf-8", "surrogatepass") for _ in range(fdp.ConsumeIntInRange(1, 3))] + lines = [(message(fdp) if fdp.ConsumeBool() else text(fdp, JSON_PIECES, 25)).encode("utf-8", "surrogatepass") + for _ in range(fdp.ConsumeIntInRange(1, 3))] if fdp.ConsumeBool(): lines.append(fdp.ConsumeBytes(200)) out = io.BytesIO() @@ -88,7 +133,8 @@ def hook(fdp): live.stamp(text(fdp, ["2026-12-05", "T", "10:00:00", "Z", "+05:00", "-", ":", ".123", "0001-01-01", "9999", " ", "1", "24:00"], 8, 60)) with tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False, encoding="utf-8") as f: - f.write("\n".join(text(fdp, JSON_PIECES, 25) for _ in range(fdp.ConsumeIntInRange(1, 3)))) + f.write("\n".join(record(fdp) if fdp.ConsumeBool() else text(fdp, JSON_PIECES, 25) + for _ in range(fdp.ConsumeIntInRange(1, 3)))) try: live.turn_start({"transcript_path": f.name}) finally: diff --git a/tests/test_fuzz_finds.py b/tests/test_fuzz_finds.py index e2b4e21..da1f00c 100644 --- a/tests/test_fuzz_finds.py +++ b/tests/test_fuzz_finds.py @@ -62,6 +62,14 @@ def test_live_hook_skips_transcript_lines_that_arent_records(tmp_path): assert live.turn_start({"transcript_path": str(t)}) == live.stamp("2026-12-05T10:00:00Z") +def test_live_hook_keeps_the_turn_start_when_a_broken_record_comes_after_it(tmp_path): + t = tmp_path / "t.jsonl" + lines = ['{"type": "user", "message": {"content": "go"}, "timestamp": "2026-12-05T10:00:00Z"}', + '{"type": "user", "message": "hi"}', '{"type": "user", "message": [1], "timestamp": "nope"}'] + t.write_text("\n".join(lines), encoding="utf-8") + assert live.turn_start({"transcript_path": str(t)}) == live.stamp("2026-12-05T10:00:00Z") + + def test_a_folder_setting_no_system_can_open_is_a_config_error_not_a_traceback(tmp_path, monkeypatch): monkeypatch.delenv("BITE_CONFIG", raising=False) (tmp_path / ".bite.ini").write_text("[bite]\nproject_folder = " + "x" * 300 + "\n", encoding="utf-8") From c1969eacb7e7c11b7a05232ed91c16f0006968d0 Mon Sep 17 00:00:00 2001 From: CH <340279802+connabyss@users.noreply.github.com> Date: Sat, 5 Dec 2026 18:46:59 +0000 Subject: [PATCH 3/4] fix(live): skip an empty-string or zero message too, not only non-empty ones Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iFQY4M9menF61MoP2s --- live.py | 4 +++- tests/test_fuzz_finds.py | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/live.py b/live.py index 1c174d0..8452044 100644 --- a/live.py +++ b/live.py @@ -181,7 +181,9 @@ def turn_start(data: dict) -> float: continue if not isinstance(rec, dict): continue # a line that's JSON but not a record ("x", 3, [...]) says nothing about who wrote - message = rec.get("message") or {} + message = rec.get("message") + if message is None: + message = {} if not isinstance(message, dict): continue # a record whose message is a string or a list can't be told apart from a tool result content = message.get("content") diff --git a/tests/test_fuzz_finds.py b/tests/test_fuzz_finds.py index da1f00c..2aeacf1 100644 --- a/tests/test_fuzz_finds.py +++ b/tests/test_fuzz_finds.py @@ -65,7 +65,8 @@ def test_live_hook_skips_transcript_lines_that_arent_records(tmp_path): def test_live_hook_keeps_the_turn_start_when_a_broken_record_comes_after_it(tmp_path): t = tmp_path / "t.jsonl" lines = ['{"type": "user", "message": {"content": "go"}, "timestamp": "2026-12-05T10:00:00Z"}', - '{"type": "user", "message": "hi"}', '{"type": "user", "message": [1], "timestamp": "nope"}'] + '{"type": "user", "message": "hi"}', '{"type": "user", "message": [1], "timestamp": "nope"}', + '{"type": "user", "message": ""}', '{"type": "user", "message": 0}'] t.write_text("\n".join(lines), encoding="utf-8") assert live.turn_start({"transcript_path": str(t)}) == live.stamp("2026-12-05T10:00:00Z") From 16a8aac4af7b053d24e7f33cf0696263b1a6bcd1 Mon Sep 17 00:00:00 2001 From: CH <340279802+connabyss@users.noreply.github.com> Date: Sat, 5 Dec 2026 18:51:41 +0000 Subject: [PATCH 4/4] test(fuzz): prove the crash hunt drops an outside BITE_CONFIG Assisted-by: Claude Code Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175Q8iFQY4M9menF61MoP2s --- tests/test_fuzz_finds.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/test_fuzz_finds.py b/tests/test_fuzz_finds.py index 2aeacf1..10a620a 100644 --- a/tests/test_fuzz_finds.py +++ b/tests/test_fuzz_finds.py @@ -78,3 +78,25 @@ def test_a_folder_setting_no_system_can_open_is_a_config_error_not_a_traceback(t repo.load_cfg(tmp_path) except repo.ConfigError as e: assert "can't be opened" in str(e) + + +def test_the_crash_hunt_ignores_a_bite_config_set_outside(monkeypatch): + # The harness needs Atheris, which only the fuzz job installs: a stand-in lets pytest import it. + import contextlib + import importlib + import types + stub = types.ModuleType("atheris") + stub.instrument_imports = contextlib.nullcontext + monkeypatch.setitem(sys.modules, "atheris", stub) + monkeypatch.setenv("BITE_CONFIG", str(KIT / "no-such.ini")) + monkeypatch.syspath_prepend(str(KIT / "tests")) + monkeypatch.delitem(sys.modules, "fuzz_parsers", raising=False) + saved = dict(bite_mcp.TOOLS) + try: + importlib.import_module("fuzz_parsers") + import os + assert "BITE_CONFIG" not in os.environ # its config target reads its own .bite.ini + finally: + bite_mcp.TOOLS.clear() + bite_mcp.TOOLS.update(saved) # the harness stubs the tools out; put the real ones back + sys.modules.pop("fuzz_parsers", None)