Files

275 lines
18 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")])
# ---- host side (Lumen, stream-v0.2.0, 2026-12-04). `test` may name several test binaries, space-separated.
HP = SRC + "host/pairing.rs"
mut("M25", "host pairing phase", "phase 4 accepted while phase 3 is expected (a skipped step)", "host_pairing session",
[(HP, "(HostPairingState::AwaitClientPairingSecret, PairPhase::ClientPairingSecret(value)) => {",
"(HostPairingState::AwaitClientPairingSecret | HostPairingState::AwaitServerChallengeResp, "
"PairPhase::ClientPairingSecret(value)) => {")])
mut("M26", "host pairing proof", "the client's proof H_c is not compared (any PIN pairs)", "host_pairing",
[(HP, "if !ct_eq(&expected, &self.client_proof) {", "if false && !ct_eq(&expected, &self.client_proof) {")])
mut("M27", "host pairing phase 5", "phase 5 accepts any HTTPS client certificate", "host_pairing",
[(HP, "if !ct_eq(client_cert_der, &pending.cert_der) {", "if false && !ct_eq(client_cert_der, &pending.cert_der) {")])
HH = SRC + "host/http/mod.rs"
mut("M28", "host HTTP cap", "query parameter cap off by one (allows 33)", "host_http",
[(HH, 'cap("http query parameters", MAX_PARAMS, count)?;', 'cap("http query parameters", MAX_PARAMS + 1, count)?;')])
mut("M29", "host HTTP body", "a GET with Content-Length other than 0 accepted", "host_http",
[(HH, 'if content_length || value != "0" {', "if content_length {")])
mut("M30", "host HTTP answer", "PairStatus 1 over plain HTTP too", "host_http session",
[(SRC + "host/http/answer.rs", "let paired = scheme == Scheme::Https && client_paired;",
"let paired = client_paired;")])
RS = SRC + "rtsp/server/mod.rs"
mut("M31", "RTSP order", "PLAY accepted before ANNOUNCE", "rtsp_server",
[(RS, 'self.expect(RtspServerState::Play, "PLAY after ANNOUNCE").map_err(|e| refuse(455, e))?;',
'let _ = self.expect(RtspServerState::Play, "PLAY after ANNOUNCE");')])
mut("M32", "RTSP order", "a second SETUP of the same stream accepted", "rtsp_server",
[(RS, " if *slot {\n", " if *slot && false {\n")])
mut("M33", "RTSP session", "a Session header with another id accepted once issued", "rtsp_server",
[(RS, "Some(id) if !self.session_issued || id != self.session_id => {", "Some(id) if !self.session_issued => {")])
mut("M34", "ANNOUNCE", "a known attribute given twice accepted (the first value kept)", "rtsp_server",
[(SRC + "rtsp/server/announce.rs", 'Some(Some(_)) => return Err(malformed("announce: an attribute given twice")),',
"Some(Some(_)) => {}")])
mut("M35", "DESCRIBE", "the refPicInvalidation line written exactly when not offered", "rtsp_server session",
[(SRC + "rtsp/server/describe.rs", "if offer.reference_frame_invalidation {",
"if !offer.reference_frame_invalidation {")])
EH = SRC + "enet/host.rs"
mut("M36", "ENet host ack", "pings acknowledged before the verify is acknowledged", "enet_host",
[(EH, " CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => {\n"
" if c.acknowledge && connected {",
" CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => {\n"
" if c.acknowledge {")])
mut("M37", "ENet host ack", "a datagram without sent time goes on after an acknowledged command", "enet_host",
[(EH, "if wants_ack && sent_time.is_none() {", "if false && wants_ack && sent_time.is_none() {")])
mut("M38", "ENet host session id", "host session ids taken from the wrong offered field", "enet_host",
[(EH, "let out_session = next_session(p.incoming_session_id, FRESH_SESSION);\n"
" let in_session = next_session(p.outgoing_session_id, FRESH_SESSION);",
"let out_session = next_session(p.outgoing_session_id, FRESH_SESSION);\n"
" let in_session = next_session(p.incoming_session_id, FRESH_SESSION);")])
mut("M39", "ENet host session id", "the slot's previous session id not skipped", "enet_host",
[(EH, " if s == current {\n", " if false && s == current {\n")])
mut("M40", "ENet client session id", "verify's session ids swapped again (the bug fixed for v0.2.0)", "enet",
[(SRC + "enet/mod.rs", "self.in_session = p.incoming_session_id & 0x3;\n self.out_session = p.outgoing_session_id & 0x3;",
"self.in_session = p.outgoing_session_id & 0x3;\n self.out_session = p.incoming_session_id & 0x3;")])
CH = SRC + "control/host.rs"
mut("M41", "control host replay", "a repeated client sequence number accepted (< instead of <=)", "control_host",
[(CH, "if self.last_client_sequence.is_some_and(|last| sequence <= last) {",
"if self.last_client_sequence.is_some_and(|last| sequence < last) {")])
mut("M42", "control host replay", "the client replay check removed", "control_host",
[(CH, "if self.last_client_sequence.is_some_and(|last| sequence <= last) {",
"if self.last_client_sequence.is_some_and(|last| sequence <= last && false) {")])
mut("M43", "control host message", "extended termination code written little-endian", "control_host session",
[(CH, "framed(MessageType::TerminationExtended, &code.to_be_bytes())",
"framed(MessageType::TerminationExtended, &code.to_le_bytes())")])
mut("M44", "control host stop", "a PERIODIC_PING does not move the stop deadline", "control_host session",
[(CH, "self.deadline = self.deadline.max(now.saturating_add(self.timeout));", "self.deadline = self.deadline.max(now);")])
VP = SRC + "video/packetizer.rs"
mut("M45", "video parity order", "parity computed after the parity headers are written (headers become parity)",
"video_packetizer session",
[(VP, " ReedSolomon::new(k, m)?.encode(&mut shards)?;\n", ""),
(VP, " parity_packets += m as u64;",
" ReedSolomon::new(k, m)?.encode(&mut shards)?;\n parity_packets += m as u64;")])
mut("M46", "video parity", "the client's minimum parity count ignored", "video_packetizer",
[(VP, "if m < usize::from(min) { usize::from(min) } else { m }", "if m < usize::from(min) { m } else { m }")])
mut("M47", "video parity", "parity shard index written one too high", "video_packetizer",
[(VP, "let h = next_header(0, block, u16::try_from(k + j).unwrap_or(u16::MAX), b);",
"let h = next_header(0, block, u16::try_from(k + j + 1).unwrap_or(u16::MAX), b);")])
mut("M48", "video nonce", "the GCM nonce counter does not advance per datagram (nonce reuse)", "video_packetizer",
[(VP, " nonce += 1;\n", " nonce += 0;\n")])
mut("M49", "audio IV", "the host encrypts with the IV of the next sequence number", "audio_packetizer session",
[(SRC + "audio/mod.rs", "plaintext.len())?;\n let iv = self.iv(sequence)?;",
"plaintext.len())?;\n let iv = self.iv(sequence.wrapping_add(1))?;")])
mut("M50", "audio IV", "IV counter written little-endian (both sides)", "media audio_packetizer",
[(SRC + "audio/mod.rs", "self.rikeyid.wrapping_add(u32::from(sequence)).to_be_bytes();",
"self.rikeyid.wrapping_add(u32::from(sequence)).to_le_bytes();")])
mut("M51", "audio block start", "a first sequence number that is not a block start accepted", "audio_packetizer",
[(SRC + "audio/packetizer.rs", "if !config.first_sequence.is_multiple_of(4) {", "if false {")])
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:
tests = " ".join(f"--test {t}" for t in m["test"].split())
cmd = f"cargo test -j 2 --offline --no-fail-fast {tests} -- --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()