Files
lotherk ed4e326ed2 apex-twin 0.15.0: fuzz the MCP HTTP front
tests/fuzz_http.py drives the sanitizer build in --http mode with raw requests:

- valid initialize, wrong path, GET, garbage request line, missing head;
- Content-Length: negative, 999999999, 100000 (with body), duplicated, absent;
- chunked body, invalid UTF-8 body, 8.5 MiB body (refused from the header),
- a head split across two writes (exercises the partial-read loop),
- 40 mutated raw requests on top.

The HTTP face forks a child per connection, so liveness is not the judge: the
child inherits stderr and any ASan/UBSan report fails the run. A case also fails
if the connection does not close within 3 s. 200/202/400/404/405/413 are all
legitimate; a sanity counter requires at least one valid 200 so a server that
rejects everything cannot pass.

make fuzz-http: 40 cases, 18 valid 200 answers, no sanitizer report, no hang.
make fuzz-http-red builds with APEX_FUZZ_BUG_HTTP (heap overflow after a
complete head) and requires rejection: 2 failures including the exact
apex-twin.c UBSan line, 'caught the deliberate bug'. Normal builds never see the
macro.

239 checks + 240 file-fuzz + 60 proxy-fuzz + 40 HTTP-fuzz cases.
2026-11-21 07:37:43 +00:00

242 lines
8.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Fuzz the MCP HTTP front (`apex-twin --http`).
The HTTP face forks a child per connection, so "the process is still alive" is
not enough: a child crash would leave the listener running and the client with a
closed socket. The judge here is stderr - the child inherits the pipe, so any
AddressSanitizer/UBSan report reaches the parent's stderr and fails the run.
make asan && make fuzz-http
make fuzz-http-red # deliberate child crash must be caught
"""
import errno
import os
import random
import socket
import subprocess
import sys
import tempfile
import time
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEFAULT_BIN = os.path.join(HERE, "apex-twin-asan")
if not os.path.isfile(DEFAULT_BIN):
DEFAULT_BIN = os.path.join(HERE, "apex-twin")
BIN = os.environ.get("APEX_BIN") or DEFAULT_BIN
CASES = int(os.environ.get("FUZZ_CASES", "40"))
SEED = int(os.environ.get("FUZZ_SEED", "1234"))
MARKERS = (
"ERROR: AddressSanitizer",
"AddressSanitizer:DEADLYSIGNAL",
"SUMMARY: UndefinedBehaviorSanitizer",
"runtime error:",
)
def free_port():
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
return port
def marker_line(err):
for line in err.splitlines():
for marker in MARKERS:
if marker in line:
return line.strip()[:160]
return None
def wait_listening(port, proc, deadline=10.0):
end = time.time() + deadline
while time.time() < end:
if proc.poll() is not None:
return False
s = socket.socket()
try:
s.settimeout(0.2)
s.connect(("127.0.0.1", port))
s.close()
return True
except OSError:
s.close()
time.sleep(0.05)
return False
def probe(port, chunks, timeout=3.0):
"""chunks is a list of byte strings, sent with a short gap between them."""
try:
s = socket.create_connection(("127.0.0.1", port), timeout=timeout)
except OSError as e:
return "cannot connect: %s" % e, b""
s.settimeout(timeout)
try:
for chunk in chunks:
s.sendall(chunk)
if len(chunks) > 1:
time.sleep(0.05)
except OSError:
pass
try:
s.shutdown(socket.SHUT_WR)
except OSError:
pass
resp = b""
reason = None
try:
while len(resp) < (1 << 20):
chunk = s.recv(65536)
if not chunk:
break
resp += chunk
except socket.timeout:
reason = "connection did not close within %.1fs" % timeout
except OSError as e:
if e.errno not in (errno.ECONNRESET, errno.EPIPE):
reason = "socket error: %s" % e
finally:
s.close()
return reason, resp
def post(headers, body, path="/mcp"):
head = ("POST %s HTTP/1.1\r\nHost: fuzz\r\n" % path) + headers + \
"Connection: close\r\n\r\n"
return head.encode() + body
def mutate(chunks, rng):
data = b"".join(chunks)
b = bytearray(data)
op = rng.randrange(8)
if op == 0 and b:
pos = rng.randrange(len(b))
b[pos] ^= 1 << rng.randrange(8)
elif op == 1:
b = b[:rng.randrange(len(b) + 1)]
elif op == 2 and b:
pos = rng.randrange(len(b))
b[pos:pos] = b[pos:pos + rng.randrange(1, 60)]
elif op == 3 and len(b) > 8:
pos = rng.randrange(len(b) - 4)
del b[pos:pos + rng.randrange(1, 60)]
elif op == 4:
b += rng.choice([b"\xff\xfe", b"\x00", b"\r\nX-Dup: 1",
b"\r\n\r\n", b"Z" * 5000])
elif op == 5:
# duplicate an existing header line
lines = bytes(b).split(b"\r\n")
if len(lines) > 1:
i = rng.randrange(1, len(lines))
lines.insert(i, lines[i])
b = bytearray(b"\r\n".join(lines))
elif op == 6:
# deep JSON body, if there is a body separator
marker = b"\r\n\r\n"
if marker in b:
head, _, _ = bytes(b).partition(marker)
depth = rng.choice([256, 4096])
b = bytearray(head + marker + b"{" * depth + b"\r\n")
else:
b = bytearray(b) + bytes(rng.randrange(1, 2000))
return [bytes(b)]
def main():
if not os.path.isfile(BIN):
print("fuzz-http: no binary at %s (run make asan)" % BIN)
return 1
rng = random.Random(SEED)
home = tempfile.mkdtemp(prefix="apex-fuzz-http-")
with open(os.path.join(home, "scope.json"), "w") as f:
f.write('{"label":"fuzz","expires":"2099-12-31T23:59:59Z",'
'"allow_ip":["203.0.113.0/24"],"allow_port":["80"]}')
port = free_port()
env = dict(os.environ)
env["APEX_HOME"] = home
env["ASAN_OPTIONS"] = "detect_leaks=0:halt_on_error=1"
env["UBSAN_OPTIONS"] = "halt_on_error=1:print_stacktrace=1"
proc = subprocess.Popen([BIN, "--http", str(port)], env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True)
failures = []
ok200 = 0
try:
if not wait_listening(port, proc):
out, err = proc.communicate(timeout=5)
print("fuzz-http: server did not start\n%s" % err[:800])
return 1
init = (b'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}')
seeds = [
[post("Content-Type: application/json\r\nContent-Length: %d\r\n" %
len(init), init)],
[post("Content-Length: 2\r\n", b"{}", path="/")],
[post("Content-Length: 2\r\n", b"{}", path="/nope")],
[b"POST /mcp HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked"
b"\r\n\r\n2\r\n{}\r\n0\r\n\r\n"],
[post("Content-Length: 8\r\nContent-Length: 4\r\n", b"{}")],
[post("Content-Length: -5\r\n", b"")],
[post("Content-Length: 999999999\r\n", b"")],
[post("Content-Length: 100000\r\n", b"{" * 100000)],
[post("Content-Length: 20\r\n", b"\xff" * 20)],
# 8.5 MiB is over MAX_BODY and must be refused on the header alone
[post("Content-Length: 8912896\r\n", b"")],
# a head split across two writes exercises the partial-read loop
[b"POST /mcp HTTP/1.1\r\nHost: x\r\n",
b"Content-Length: 2\r\n\r\n{}"],
[b"GARBAGE\r\n\r\n"],
[b"POST /mcp HTTP/1.1\r\nHost: x\r\n\r\n"],
[b"GET /mcp HTTP/1.1\r\nHost: x\r\n\r\n"],
[post("Content-Length: 2\r\n", b"{}", path="/mcp?x=y")],
]
suite = seeds + [[]]
for i in range(CASES + len(seeds)):
chunks = suite[i] if i < len(suite) else mutate(
seeds[i % len(seeds)], rng)
reason, resp = probe(port, chunks)
if resp.startswith(b"HTTP/1.") and b" 200 " in resp.split(b"\r\n")[0]:
ok200 += 1
if reason is None and proc.poll() is not None:
out, err = proc.communicate(timeout=5)
line = marker_line(err)
reason = "server died (%s)" % (line or "no marker")
if reason is not None:
failures.append(("case/%d" % i, reason))
if proc.poll() is not None:
break
if proc.poll() is None:
proc.terminate()
out, err = proc.communicate(timeout=10)
line = marker_line(err)
if line is not None:
failures.append(("stderr", line))
if ok200 == 0:
failures.append(("sanity", "no valid request got a 200"))
finally:
if proc.poll() is None:
proc.kill()
try:
os.unlink(os.path.join(home, "scope.json"))
except OSError:
pass
try:
os.rmdir(home)
except OSError:
pass
if failures:
for case, why in failures[:20]:
print("FAIL %-10s %s" % (case, why))
print("%d failure(s) of %d case(s)" % (len(failures), CASES))
return 1
print("%d cases, %d valid 200 answers, no sanitizer report, no hang"
% (CASES, ok200))
return 0
if __name__ == "__main__":
sys.exit(main())