Repository navigation
feat(fuzz): hunt crashes in everything Bite reads, fix the 3 it found #325
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+385
−7
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e0ce95d
feat(fuzz): hunt crashes in everything Bite reads, fix the 3 it found
connabyss 66d6610
fix(live): keep the turn start when a broken record follows it; fuzz …
connabyss c1969ea
fix(live): skip an empty-string or zero message too, not only non-emp…
connabyss 16a8aac
test(fuzz): prove the crash hunt drops an outside BITE_CONFIG
connabyss File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,221 @@ | ||
| """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 json | ||
| import os | ||
| 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 | ||
|
|
||
| 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} | ||
|
|
||
| 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)", "<!-- ` -->", "<a title=\"`\">", "**", "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 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 = [(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() | ||
| 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(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: | ||
| 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() | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.