Files
mnovak 8125949db2 [domistream] Tests: mutation pass, 24 of 24 caught
docs/MUTATION.md: each mandatory area's bug put back into src and caught by
its tests (parser caps off by one or removed for XML, RTSP, ENet, input,
video, audio; lying lengths; the ENet 0xFFFF wrap; the control replay
check; the nonce direction byte; ignored GCM tags, control and video; a
video parity index off by one; a rebuilt video shard's header trusted;
audio parity keyed by RTP sequence; a skipped pairing step; unchecked host
signatures; Instant::now and getrandom in src). No mutation survived, so no
test was added.

tools/mutation/mutate.py: the exact edits, so the pass can be rerun
through the resource gate.

Also: pairing_session fuzzed 10 min, 574 761 runs, no crash.
2026-11-26 03:59:58 +01:00

189 lines
11 KiB
Python

"""Mutation pass for DomiStream (QA, 2026-11-26); results in docs/MUTATION.md.
For each mutation: apply exact edits to src (and Cargo files), run the guarding test binary through the resource gate,
record which tests failed (caught) or whether it did not compile, then revert with `git checkout`. Writes
results.json and one log per mutation to DOMISTREAM_QA_DIR (default target/mutation). Run it only on a clean tree:
the revert checks out the touched src files and Cargo.lock.
python tools/mutation/mutate.py [ID ...]
"""
import json
import os
import re
import subprocess
import sys
import time
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Logs and results.json; the gate is a PowerShell script taking the command, exiting 75 while the PC is busy.
QA = os.environ.get("DOMISTREAM_QA_DIR", os.path.join(REPO, "target", "mutation"))
GATE = os.environ.get("DOMISTREAM_GATE", os.path.join(QA, "gate.ps1"))
os.makedirs(QA, exist_ok=True)
SRC = "crates/domistream/src/"
M = []
def mut(id_, area, what, test, edits):
M.append({"id": id_, "area": area, "what": what, "test": test, "edits": edits})
# ---- parser caps
mut("M1", "xml cap", "size cap off by one (refuses exactly MAX_XML_BYTES)", "http",
[(SRC + "http/xml.rs", 'cap("xml document", MAX_XML_BYTES, body.len())?;',
'cap("xml document", MAX_XML_BYTES - 1, body.len())?;')])
mut("M2", "xml cap", "depth cap off by one (allows depth 9)", "http",
[(SRC + "http/xml.rs", 'cap("xml depth", MAX_XML_DEPTH, stack.len() + 1)?;',
'cap("xml depth", MAX_XML_DEPTH + 1, stack.len() + 1)?;')])
mut("M3", "rtsp cap", "header cap off by one (allows 65 headers)", "rtsp",
[(SRC + "rtsp/mod.rs", 'cap("rtsp headers", MAX_RTSP_HEADERS, headers.len())?;',
'cap("rtsp headers", MAX_RTSP_HEADERS + 1, headers.len())?;')])
mut("M4", "enet cap", "command cap off by one (allows 33 commands)", "enet",
[(SRC + "enet/protocol.rs", 'cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, commands.len() + 1)?;',
'cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, commands.len())?;')])
mut("M5", "input cap", "message size cap removed", "input",
[(SRC + "input/mod.rs", " crate::util::cap(W, MAX_INPUT_MESSAGE_BYTES, message.len())?;\n",
" let _ = MAX_INPUT_MESSAGE_BYTES;\n")])
mut("M6", "video cap", "packet size cap off by one (accepts 4097 bytes)", "media",
[(SRC + "video/packet.rs", "crate::util::cap(W, MAX_VIDEO_PACKET_BYTES, packet.len())?;",
"crate::util::cap(W, MAX_VIDEO_PACKET_BYTES + 1, packet.len())?;")])
mut("M7", "audio cap", "packet size cap removed", "media",
[(SRC + "audio/packet.rs", " crate::util::cap(W, MAX_AUDIO_PACKET_BYTES, packet.len())?;\n",
" let _ = MAX_AUDIO_PACKET_BYTES;\n")])
# ---- lying lengths
mut("M8", "lying length", "control frame: a length field that claims less is accepted", "control",
[(SRC + "control/frame.rs", "if usize::from(u16_le(W, frame, 2)?) != frame.len() - 4 {",
"if usize::from(u16_le(W, frame, 2)?) > frame.len() - 4 {")])
mut("M9", "lying length", "RTSP: bytes after Content-Length are kept instead of refused", "rtsp",
[(SRC + "rtsp/mod.rs", 'Some(n) if rest.len() > n => return Err(malformed("rtsp: bytes after the payload")),',
"Some(n) if rest.len() > n => rest.get(..n).unwrap_or(rest).to_vec(),")])
mut("M10", "lying length", "INPUT_DATA: the big-endian size field is not checked", "input",
[(SRC + "input/mod.rs", "if usize::try_from(u32_be(W, message, 4)?).ok() != Some(message.len() - 8) {",
"if usize::try_from(u32_be(W, message, 4)?).is_err() {")])
# ---- sequence numbers and crypto
mut("M11", "enet wrap", "reliable delivery does not wrap at 0xFFFF (saturating next)", "enet",
[(SRC + "enet/mod.rs",
" let next = ch.in_reliable.wrapping_add(1);\n let Some(p) = ch.pending.remove(&next)",
" let next = ch.in_reliable.saturating_add(1);\n let Some(p) = ch.pending.remove(&next)")])
mut("M12", "control replay", "replay check accepts a repeated sequence number (seq < last instead of <=)", "control",
[(SRC + "control/mod.rs", "if self.last_host_sequence.is_some_and(|last| sequence <= last) {",
"if self.last_host_sequence.is_some_and(|last| sequence < last) {")])
mut("M13", "control replay", "replay check removed", "control",
[(SRC + "control/mod.rs", "if self.last_host_sequence.is_some_and(|last| sequence <= last) {",
"if self.last_host_sequence.is_some_and(|last| sequence <= last && false) {")])
mut("M14", "nonce", "direction bytes swapped ('H' client to host)", "control",
[(SRC + "control/frame.rs", " Direction::ClientToHost => b'C',\n Direction::HostToClient => b'H',",
" Direction::ClientToHost => b'H',\n Direction::HostToClient => b'C',")])
mut("M15", "GCM tag", "control open ignores a failed tag check", "control",
[(SRC + "control/frame.rs", " .map_err(|_| Error::Crypto)?;\n Ok((f.sequence, body))",
" .ok();\n Ok((f.sequence, body))")])
mut("M24", "GCM tag", "video decrypt ignores a failed tag check", "media",
[(SRC + "video/mod.rs", " .map_err(|_| Error::Crypto)?;\n Ok(body)",
" .ok();\n Ok(body)")])
# ---- FEC
mut("M16", "FEC index", "video parity shard stored one index too high", "video",
[(SRC + "video/mod.rs", "block.shards.insert(fec.shard_index, p.payload.to_vec());",
"block.shards.insert(if fec.shard_index >= fec.data_shards { fec.shard_index + 1 } else { fec.shard_index }, p.payload.to_vec());")])
mut("M17", "video header", "recovered shard's bytes 0-31 trusted (full-packet shards, SOF flag read from a rebuilt shard)", "video",
[(SRC + "video/mod.rs", "fn store(&mut self, frame: u32, p: &VideoPacket<'_>, now: Instant) -> bool {",
"fn store(&mut self, frame: u32, p: &VideoPacket<'_>, raw: &[u8], now: Instant) -> bool {"),
(SRC + "video/mod.rs", "let accepted = self.store(frame, &p, now);", "let accepted = self.store(frame, &p, bytes, now);"),
(SRC + "video/mod.rs", "block.shards.insert(fec.shard_index, p.payload.to_vec());",
"block.shards.insert(fec.shard_index, raw.to_vec());"),
(SRC + "video/mod.rs", " data.extend_from_slice(block.shards.get(&i)?);",
" data.extend_from_slice(block.shards.get(&i)?.get(packet::PAYLOAD_OFFSET..)?);"),
(SRC + "video/mod.rs",
" for s in shards.iter().take(k) {\n data.extend_from_slice(s.as_ref()?);\n }",
" if b == 0 && !block.shards.contains_key(&0) && shards.first()?.as_ref()?.get(24)? & 0x04 == 0 {\n"
" return None;\n }\n"
" for s in shards.iter().take(k) {\n data.extend_from_slice(s.as_ref()?.get(packet::PAYLOAD_OFFSET..)?);\n }")])
mut("M18", "audio parity", "parity keyed by its own RTP sequence, not the FEC header's base", "audio",
[(SRC + "audio/mod.rs", "AudioPacket::Parity { fec, parity, .. } => {\n let base = fec.base_sequence;",
"AudioPacket::Parity { rtp, fec, parity } => {\n let base = rtp.sequence & !3;")])
# ---- pairing
mut("M19", "pairing skip", "no pairingsecret: skip the proof and the signature, go to step 4", "pairing",
[(SRC + "pairing/mod.rs",
' let ps = answer.pairing_secret.ok_or_else(|| bad(malformed("pairing: no pairingsecret")))?;',
" let Some(ps) = answer.pairing_secret else {\n"
" self.state = PairingState::AwaitClientSecretAck;\n"
" return Ok(PairingStep::Send(self.request(Scheme::Http, &[], None)));\n"
" };")])
mut("M20", "signature", "the host's signature over its secret is not checked", "pairing",
[(SRC + "pairing/mod.rs",
" cert.verify(&secret, signature)\n .map_err(|_| (PairingFailure::BadHostSignature, Error::PairingRefused))?;",
" let _ = cert.verify(&secret, signature);")])
mut("M21", "signature", "ServerCert::verify accepts any signature", "pairing",
[(SRC + "pairing/identity.rs", "pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {",
"pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {\n if !data.is_empty() || signature.is_empty() { return Ok(()); }")])
# ---- sans-I/O
mut("M22", "sans-I/O", "a wall-clock read (std::time::Instant::now) in src/time.rs", "hygiene",
[(SRC + "time.rs", "APPEND",
"\n#[allow(dead_code)]\nfn wall_clock_probe() -> std::time::Instant {\n std::time::Instant::now()\n}\n")])
mut("M23", "OS randomness", "getrandom added as a dependency and used in src/entropy.rs", "hygiene",
[("crates/domistream/Cargo.toml", 'zeroize = "1.8" # wipe keys on drop',
'zeroize = "1.8" # wipe keys on drop\ngetrandom = "0.4"'),
(SRC + "entropy.rs", "APPEND",
"\n#[allow(dead_code)]\nfn os_fill(dest: &mut [u8]) {\n let _ = getrandom::fill(dest);\n}\n")])
def sh(args, **kw):
return subprocess.run(args, cwd=REPO, capture_output=True, text=True, encoding="utf-8", errors="replace", **kw)
def gated(cmd):
while True:
p = sh(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", GATE, cmd])
if p.returncode != 75:
return p
time.sleep(15)
def apply(edits):
for path, old, new in edits:
full = os.path.join(REPO, path)
with open(full, encoding="utf-8", newline="") as f:
s = f.read()
if old == "APPEND":
s = s + new
else:
if s.count(old) != 1:
raise SystemExit(f"{path}: anchor found {s.count(old)} times: {old[:60]!r}")
s = s.replace(old, new)
with open(full, "w", encoding="utf-8", newline="") as f:
f.write(s)
def revert(edits):
files = sorted({p for p, _, _ in edits} | {"Cargo.lock"})
sh(["git", "checkout", "--", *files])
if sh(["git", "diff", "--quiet", "--", "crates/domistream/src", "crates/domistream/Cargo.toml", "Cargo.lock"]).returncode != 0:
raise SystemExit("revert failed: src is not clean")
def main():
only = set(sys.argv[1:])
results_path = os.path.join(QA, "results.json")
results = json.load(open(results_path)) if os.path.exists(results_path) else {}
for m in M:
if only and m["id"] not in only:
continue
apply(m["edits"])
try:
cmd = f"cargo test -j 2 --offline --test {m['test']} -- --test-threads=2 2>&1 | Out-File -Encoding utf8 {QA}\\mut-{m['id']}.log"
gated(cmd)
log = open(os.path.join(QA, f"mut-{m['id']}.log"), encoding="utf-8-sig", errors="replace").read()
finally:
revert(m["edits"])
failed = re.findall(r"^test (\S+) \.\.\. FAILED", log, re.M)
compile_error = bool(re.search(r"^error(\[E\d+\])?:", log, re.M)) and not failed
summary = re.findall(r"^test result: .*$", log, re.M)
r = {**{k: m[k] for k in ("area", "what", "test")}, "failed": failed, "compile_error": compile_error,
"summary": summary[-1] if summary else "", "caught": bool(failed) or compile_error}
results[m["id"]] = r
print(m["id"], "CAUGHT" if failed else ("COMPILE ERROR" if compile_error else "NOT CAUGHT"), failed[:4], flush=True)
json.dump(results, open(results_path, "w"), indent=1)
main()