diff --git a/docs/MUTATION.md b/docs/MUTATION.md new file mode 100644 index 0000000..8c3ff29 --- /dev/null +++ b/docs/MUTATION.md @@ -0,0 +1,46 @@ +# Mutation pass + +Each row puts back one bug a test is meant to guard against (an exact edit to `crates/domistream/src`), runs the +test binary that should catch it, and reverts the edit. "Caught by" lists the tests that failed. All 24 rows were +caught; none failed to compile, so every row is a real behaviour change the tests saw. + +- **When:** 2026-11-26, QA, on `feature/client` at `d62aa8f`. The baseline was 242/242 tests passing. +- **Driver:** [`tools/mutation/mutate.py`](../tools/mutation/mutate.py) holds the exact edits, so the pass can be + rerun: `python tools/mutation/mutate.py [M1 ...]`. Every cargo run goes through the resource gate (CPU, RAM and + drives below 90 %, `-j 2`). + +| # | Area | Mutation | Test binary | Caught by | Result | +| :-- | :-- | :-- | :-- | :-- | :-- | +| M1 | XML cap | size cap off by one (refuses exactly `MAX_XML_BYTES`) | http | `xml_size_boundaries`, `applist_caps` | caught | +| M2 | XML cap | depth cap off by one (allows depth 9) | http | `xml_depth_cap`, `xml_depth_bomb_does_not_recurse` | caught | +| M3 | RTSP cap | header cap off by one (allows 65 headers) | rtsp | `response_header_flood` | caught | +| M4 | ENet cap | command cap off by one (allows 33 commands) | enet | `hostile_sizes` | caught | +| M5 | Input cap | message size cap removed | input | `hostile_sizes` | caught | +| M6 | Video cap | packet size cap off by one (accepts 4097 bytes) | media | `video_packet_hostile_sizes` | caught | +| M7 | Audio cap | packet size cap removed | media | `audio_packet_hostile` | caught | +| M8 | Lying length | control frame: a length field that claims less is accepted | control | `frame_parser_lying_lengths` | caught | +| M9 | Lying length | RTSP: bytes after `Content-Length` kept instead of refused | rtsp | `response_lying_content_length` | caught | +| M10 | Lying length | INPUT_DATA: the big-endian size field not checked | input | `lying_length_and_size_fields` | caught | +| M11 | ENet wrap | reliable delivery does not wrap at 0xFFFF (saturating "next") | enet | `reliable_sequence_wraps_at_0xffff` | caught | +| M12 | Control replay | a repeated sequence number accepted (`<` instead of `<=`) | control | `replayed_and_old_host_frames_are_dropped` | caught | +| M13 | Control replay | the replay check removed | control | `replayed_and_old_host_frames_are_dropped`, `host_sequence_at_u32_wrap` | caught | +| M14 | Nonce | direction bytes swapped (`'H'` client to host) | control | `nonce_layout`, `nonce_matches_the_definition`, `seal_matches_dotnet_vectors`, `wrong_direction_and_wrong_key_are_refused` | caught | +| M15 | GCM tag | control `open` ignores a failed tag check | control | `tampering_is_refused`, `tampered_and_reflected_frames_are_dropped`, `open_never_accepts_random_frames`, `wrong_direction_and_wrong_key_are_refused` | caught | +| M24 | GCM tag | video `decrypt` ignores a failed tag check | media | `video_decrypt_refuses` | caught | +| M16 | FEC index | a video parity shard stored one index too high | video | 12 tests, e.g. `random_loss`, `all_data_lost_but_recoverable`, `recovered_shard_headers_are_not_trusted`, `generated_patterns` | caught | +| M17 | Video header | bytes 0-31 of a rebuilt shard trusted (whole-packet shards, start-of-frame flag read from a rebuilt shard) | video | 9 tests, e.g. `recovered_shard_headers_are_not_trusted`, `all_data_lost_but_recoverable`, `random_loss` | caught | +| M18 | Audio parity | parity keyed by its own RTP sequence instead of the FEC header's base | audio | 9 tests, e.g. `every_loss_pattern_of_a_block`, `sequence_wraps`, `hostile_parity_never_corrupts` | caught | +| M19 | Pairing skip | no `pairingsecret`: proof and signature skipped, straight to step 4 | pairing | `a_bare_paired_answer_cannot_skip_any_step`, `out_of_order_answers_fail`, `replaying_the_same_answer_twice_fails` | caught | +| M20 | Signature | the host's signature over its secret not checked | pairing | `bad_host_signatures` | caught | +| M21 | Signature | `ServerCert::verify` accepts any signature | pairing | `bad_host_signatures`, `server_cert_verify_refuses` | caught | +| M22 | Sans-I/O | `std::time::Instant::now()` added in `src/time.rs` | hygiene | `src_is_sans_io` | caught | +| M23 | OS randomness | `getrandom` added as a dependency and used in `src/entropy.rs` | hygiene | `src_is_sans_io` | caught | + +## Notes +- **M17.** The video receiver keeps only the payloads (bytes 32 on) of each shard and rebuilds from those, so as + written it cannot read a rebuilt shard's header. The mutation therefore first switches it to whole-packet shards, + then makes it trust one header field of a rebuilt shard. `recovered_shard_headers_are_not_trusted` and the other + loss tests catch it. +- **M23.** The mutation compiled, against the cached getrandom 0.4.3, and the guard caught the source use. Since + 27b26a9 the dependency tree has no getrandom at all. +- **Missing tests.** No mutation got through, so none were added. diff --git a/tools/mutation/mutate.py b/tools/mutation/mutate.py new file mode 100644 index 0000000..f796d5e --- /dev/null +++ b/tools/mutation/mutate.py @@ -0,0 +1,188 @@ +"""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()