Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/requirements/atheris.txt
Original file line number Diff line number Diff line change
@@ -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 \
Expand Down
33 changes: 32 additions & 1 deletion .github/workflows/fuzz.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: {}
Expand Down Expand Up @@ -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"
16 changes: 13 additions & 3 deletions bite_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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}
Expand All @@ -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()
Expand Down
6 changes: 5 additions & 1 deletion docs/security-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
9 changes: 8 additions & 1 deletion live.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,14 @@ 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")
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")
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)
Expand Down
3 changes: 3 additions & 0 deletions repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
221 changes: 221 additions & 0 deletions tests/fuzz_parsers.py
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)
Comment thread
connabyss marked this conversation as resolved.
Resolved
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()
Loading
Loading