Skip to main content

ruso_runtime/runtime/
binary.rs

1//! Binary serialization of `BytecodeProgram` (magic `RUSO`, version 1).
2//!
3//! **Versioning:** the header carries a one-byte `VERSION`; the decoder accepts
4//! only that exact value, rejecting anything else up front with `BadVersion`
5//! (never a cryptic mid-decode `Corrupt`). Any change to the wire format must
6//! bump `VERSION` — a coordinated step, since the registry has to deploy the
7//! new runtime and serve re-compiled bytecode. See the Bytecode chapter at
8//! <https://docs.ruso.hopeless-labs.com/internals/bytecode.html>.
9//!
10//! The current v1 layout encodes `CmpValue::Number` as `u64` (earlier revisions
11//! silently truncated to `u32`), assigns HTTP method tags 5 and 6 to `Head` and
12//! `Options`, and bounds every untrusted list/count against the remaining
13//! buffer so a malicious or corrupt `.rbc` file cannot trigger OOM allocations.
14//! After decoding, [`validate_program`] bounds-checks every instruction operand
15//! against its pool so out-of-range indices surface as `Corrupt` rather than
16//! panicking the executor that indexes those pools directly.
17
18use std::collections::HashMap;
19
20use thiserror::Error;
21
22use crate::contract::{
23    BodyValue, CmpOp, CmpValue, EvidenceKind, ExtractSource, FieldKind, HttpMethod, InlinePart,
24    InlinePartBody, MatchPredicate, ObjectBody, QualifiedField, QualifiedMatch, Severity,
25};
26use crate::runtime::bytecode::{BytecodeProgram, Instr};
27use crate::runtime::spec::{CheckMetadata, HttpRequestSpec, ProbeKind, ProgramSpec};
28
29/// The four magic bytes every `.rbc` file starts with.
30pub const MAGIC: &[u8; 4] = b"RUSO";
31/// The wire-format version this build reads and writes. The decoder accepts
32/// this value only; see the module docs before changing it.
33pub const VERSION: u8 = 1;
34
35/// Why a `.rbc` byte stream could not be decoded.
36#[derive(Debug, Error)]
37pub enum BytecodeError {
38    /// The stream ended before a field that the format requires.
39    #[error("bytecode too short")]
40    TooShort,
41    /// The stream does not start with [`MAGIC`] — not a `.rbc` file.
42    #[error("invalid magic")]
43    BadMagic,
44    #[error(
45        "unsupported bytecode version {found} (this build reads version {supported}); \
46         recompile the script or update ruso"
47    )]
48    /// The file is `.rbc` but was produced for a different wire-format
49    /// version. Rejected up front so the failure names the real problem
50    /// instead of surfacing as a mid-decode [`BytecodeError::Corrupt`].
51    BadVersion {
52        /// The version byte found in the header.
53        found: u8,
54        /// The version this build supports ([`VERSION`]).
55        supported: u8,
56    },
57    /// The header was fine but the body is inconsistent: a tag that maps to no
58    /// variant, a length that runs past the buffer, or an operand that points
59    /// outside its pool. The payload names the field that failed.
60    #[error("corrupt bytecode: {0}")]
61    Corrupt(&'static str),
62    /// A hex-encoded byte literal in the payload pool is not valid hex.
63    #[error("invalid hex: {0}")]
64    InvalidHex(String),
65}
66
67/// Serialize a program to the `.rbc` wire format: [`MAGIC`], [`VERSION`], then
68/// the metadata, probe table, pools, and instruction stream in the order given
69/// in the module docs.
70pub fn encode(program: &BytecodeProgram) -> Vec<u8> {
71    let mut w = Writer::default();
72    w.bytes(MAGIC);
73    w.u8(VERSION);
74    write_metadata(&mut w, &program.spec.metadata);
75    write_probes(&mut w, &program.spec.probes);
76    write_strings(&mut w, &program.strings);
77    write_payloads(&mut w, &program.payloads);
78    write_matchers(&mut w, &program.matchers);
79    write_extracts(&mut w, &program.extracts);
80    write_evidence(&mut w, &program.evidence);
81    write_code(&mut w, &program.code);
82    w.0
83}
84
85/// Parse a `.rbc` byte stream back into a program.
86///
87/// The input is untrusted: the version is checked before anything else, every
88/// length is bounded against the remaining buffer, and the decoded program is
89/// run through `validate_program` so that out-of-range operands surface as
90/// [`BytecodeError::Corrupt`] instead of panicking the executor later.
91///
92/// # Errors
93///
94/// Returns [`BytecodeError`] when the stream is truncated, carries the wrong
95/// magic or version, or fails validation.
96pub fn decode(bytes: &[u8]) -> Result<BytecodeProgram, BytecodeError> {
97    let mut r = Reader::new(bytes);
98    r.consume_magic()?;
99    let version = r.u8()?;
100    if version != VERSION {
101        return Err(BytecodeError::BadVersion {
102            found: version,
103            supported: VERSION,
104        });
105    }
106    let metadata = read_metadata(&mut r)?;
107    let probes = read_probes(&mut r)?;
108    let strings = read_strings(&mut r)?;
109    let payloads = read_payloads(&mut r)?;
110    let matchers = read_matchers(&mut r)?;
111    let extracts = read_extracts(&mut r)?;
112    let evidence = read_evidence(&mut r)?;
113    let code = read_code(&mut r)?;
114    if r.remaining() != 0 {
115        return Err(BytecodeError::Corrupt("trailing bytes"));
116    }
117    let program = BytecodeProgram {
118        spec: ProgramSpec { probes, metadata },
119        code,
120        strings,
121        payloads,
122        matchers,
123        extracts,
124        evidence,
125    };
126    validate_program(&program)?;
127    Ok(program)
128}
129
130/// Bounds-check every instruction operand against the pool it indexes.
131///
132/// The decode helpers above guarantee no out-of-buffer reads and no OOM
133/// allocations, but they do **not** check that an instruction's operand
134/// indices (`strings[name]`, `payloads[id]`, `matchers[start..start+len]`,
135/// …) actually fall within the decoded pools — those indices are plain
136/// `u32`s in the code stream. The executor indexes the pools directly, so
137/// an unchecked out-of-range index would panic the worker thread. A
138/// malicious or corrupt `.rbc` (e.g. `ruso exec evil.rbc`) must surface as a
139/// clean `Corrupt` error, not a panic. This pass closes that gap so the
140/// "untrusted bytecode is safe to decode" guarantee holds end to end.
141///
142/// Jump targets (`else_pc`, `end_pc`) are deliberately *not* rejected when
143/// they point past `code`: the executor's main loop halts once `pc >=
144/// code.len()`, so an out-of-range jump simply ends execution rather than
145/// reading out of bounds.
146fn validate_program(p: &BytecodeProgram) -> Result<(), BytecodeError> {
147    let strings = p.strings.len();
148    let payloads = p.payloads.len();
149    let matchers = p.matchers.len();
150    let extracts = p.extracts.len();
151    let evidence = p.evidence.len();
152
153    // `idx < bound` with the index widened to usize so a u32 operand can
154    // never wrap; `range` additionally rejects start+len overflow.
155    let one = |idx: u32, bound: usize| -> Result<(), BytecodeError> {
156        if (idx as usize) < bound {
157            Ok(())
158        } else {
159            Err(BytecodeError::Corrupt("operand index out of range"))
160        }
161    };
162    let range = |start: u32, len: u16, bound: usize| -> Result<(), BytecodeError> {
163        let end = (start as usize)
164            .checked_add(len as usize)
165            .ok_or(BytecodeError::Corrupt("operand range overflow"))?;
166        if end <= bound {
167            Ok(())
168        } else {
169            Err(BytecodeError::Corrupt("operand range out of bounds"))
170        }
171    };
172
173    for instr in &p.code {
174        match instr {
175            Instr::Set { name, value } => {
176                one(*name, strings)?;
177                one(*value, strings)?;
178            }
179            Instr::SetList { name, start, len } => {
180                one(*name, strings)?;
181                range(*start, *len, strings)?;
182            }
183            Instr::Send { probe, payload } => {
184                one(*probe, strings)?;
185                if let Some(id) = payload {
186                    one(*id, payloads)?;
187                }
188            }
189            Instr::Match(m) | Instr::Assert(m) => one(*m, matchers)?,
190            Instr::MatchAll { start, len } | Instr::MatchAny { start, len } => {
191                range(*start, *len, matchers)?;
192            }
193            Instr::Extract { name, source } => {
194                one(*name, strings)?;
195                one(*source, extracts)?;
196            }
197            Instr::IfMatch { matcher, .. } => one(*matcher, matchers)?,
198            Instr::ForList {
199                item, start, len, ..
200            } => {
201                one(*item, strings)?;
202                range(*start, *len, strings)?;
203            }
204            Instr::ForVar { item, list, .. } => {
205                one(*item, strings)?;
206                one(*list, strings)?;
207            }
208            Instr::Save { from, to } => {
209                one(*from, strings)?;
210                one(*to, strings)?;
211            }
212            Instr::Evidence(k) => one(*k, evidence)?,
213            Instr::Retry { probe, .. } => one(*probe, strings)?,
214            Instr::RetryDelay(v) | Instr::Sleep(v) => one(*v, strings)?,
215            // Operand-free / jump-only instructions: nothing to bound here.
216            Instr::LoopBack
217            | Instr::Break
218            | Instr::Stop
219            | Instr::Fail
220            | Instr::Continue
221            | Instr::Exit => {}
222        }
223    }
224    Ok(())
225}
226
227/// Lowercase hex encoding of `bytes`, with no separators — the inverse of
228/// [`hex_to_bytes`].
229pub fn bytes_to_hex(bytes: &[u8]) -> String {
230    use std::fmt::Write as _;
231    let mut out = String::with_capacity(bytes.len() * 2);
232    for b in bytes {
233        let _ = write!(out, "{b:02x}");
234    }
235    out
236}
237
238/// A classic 16-byte-per-line hex dump (offset, hex columns, ASCII gutter),
239/// used when showing a raw socket response to a human.
240pub fn bytes_to_hex_dump(bytes: &[u8]) -> String {
241    use std::fmt::Write as _;
242    let mut out = String::new();
243    for (offset, chunk) in bytes.chunks(16).enumerate() {
244        let off = offset * 16;
245        let _ = write!(out, "{off:08x}: ");
246        for b in chunk {
247            let _ = write!(out, "{b:02x} ");
248        }
249        for _ in chunk.len()..16 {
250            out.push_str("   ");
251        }
252        out.push_str(" |");
253        for &b in chunk {
254            if b.is_ascii_graphic() || b == b' ' {
255                out.push(b as char);
256            } else {
257                out.push('.');
258            }
259        }
260        out.push_str("|\n");
261    }
262    out
263}
264
265/// Decode a hex string into bytes, ignoring ASCII whitespace so a dump that
266/// has been wrapped across lines still decodes.
267///
268/// # Errors
269///
270/// Returns [`BytecodeError::InvalidHex`] when the input has an odd number of
271/// digits or contains a non-hex character.
272pub fn hex_to_bytes(input: &str) -> Result<Vec<u8>, BytecodeError> {
273    let mut compact = String::with_capacity(input.len());
274    for c in input.chars() {
275        if c.is_ascii_whitespace() {
276            continue;
277        }
278        if !c.is_ascii_hexdigit() {
279            return Err(BytecodeError::InvalidHex(format!("non-hex char: {c:?}")));
280        }
281        compact.push(c);
282    }
283    if !compact.len().is_multiple_of(2) {
284        return Err(BytecodeError::InvalidHex("odd length".into()));
285    }
286    let bytes = compact.as_bytes();
287    let mut out = Vec::with_capacity(bytes.len() / 2);
288    for chunk in bytes.chunks_exact(2) {
289        // SAFETY: validated above as ascii hex.
290        let pair = std::str::from_utf8(chunk).expect("ascii hex");
291        let byte = u8::from_str_radix(pair, 16)
292            .map_err(|err| BytecodeError::InvalidHex(err.to_string()))?;
293        out.push(byte);
294    }
295    Ok(out)
296}
297
298/// Decode a hex string into raw bytecode bytes.
299///
300/// Earlier revisions accepted an `@path` prefix that would read the file as
301/// raw bytecode. That alternate entry point conflated "hex-decoded input"
302/// with "file IO" and provided a path-traversal sink for any caller passing
303/// less-trusted input (env vars, CI parameters, scripted wrappers). File IO
304/// is now the CLI's responsibility — runtime callers pass bytes directly via
305/// [`decode`] or hex via this function.
306pub fn load_bytecode_input(input: &str) -> Result<Vec<u8>, BytecodeError> {
307    hex_to_bytes(input.trim())
308}
309
310#[derive(Default)]
311struct Writer(Vec<u8>);
312
313impl Writer {
314    fn u8(&mut self, v: u8) {
315        self.0.push(v);
316    }
317
318    fn u16(&mut self, v: u16) {
319        self.0.extend_from_slice(&v.to_le_bytes());
320    }
321
322    fn u32(&mut self, v: u32) {
323        self.0.extend_from_slice(&v.to_le_bytes());
324    }
325
326    fn u64(&mut self, v: u64) {
327        self.0.extend_from_slice(&v.to_le_bytes());
328    }
329
330    fn bytes(&mut self, data: &[u8]) {
331        self.0.extend_from_slice(data);
332    }
333
334    fn str(&mut self, s: &str) {
335        let b = s.as_bytes();
336        self.u32(b.len() as u32);
337        self.bytes(b);
338    }
339
340    fn opt_str(&mut self, value: &Option<String>) {
341        match value {
342            Some(s) => {
343                self.u8(1);
344                self.str(s);
345            }
346            None => self.u8(0),
347        }
348    }
349
350    fn opt_bytes(&mut self, value: &Option<Vec<u8>>) {
351        match value {
352            Some(data) => {
353                self.u8(1);
354                self.u32(data.len() as u32);
355                self.bytes(data);
356            }
357            None => self.u8(0),
358        }
359    }
360
361    fn opt_u16(&mut self, value: Option<u16>) {
362        match value {
363            Some(v) => {
364                self.u8(1);
365                self.u16(v);
366            }
367            None => self.u8(0),
368        }
369    }
370}
371
372struct Reader<'a> {
373    data: &'a [u8],
374    pos: usize,
375}
376
377impl<'a> Reader<'a> {
378    fn new(data: &'a [u8]) -> Self {
379        Self { data, pos: 0 }
380    }
381
382    fn remaining(&self) -> usize {
383        self.data.len().saturating_sub(self.pos)
384    }
385
386    fn consume_magic(&mut self) -> Result<(), BytecodeError> {
387        let magic = self.need(4)?;
388        if magic != MAGIC {
389            return Err(BytecodeError::BadMagic);
390        }
391        Ok(())
392    }
393
394    fn need(&mut self, n: usize) -> Result<&'a [u8], BytecodeError> {
395        if self.pos + n > self.data.len() {
396            return Err(BytecodeError::Corrupt("unexpected end"));
397        }
398        let slice = &self.data[self.pos..self.pos + n];
399        self.pos += n;
400        Ok(slice)
401    }
402
403    fn u8(&mut self) -> Result<u8, BytecodeError> {
404        Ok(self.need(1)?[0])
405    }
406
407    fn u16(&mut self) -> Result<u16, BytecodeError> {
408        Ok(u16::from_le_bytes(self.need(2)?.try_into().unwrap()))
409    }
410
411    fn u32(&mut self) -> Result<u32, BytecodeError> {
412        Ok(u32::from_le_bytes(self.need(4)?.try_into().unwrap()))
413    }
414
415    fn u64(&mut self) -> Result<u64, BytecodeError> {
416        Ok(u64::from_le_bytes(self.need(8)?.try_into().unwrap()))
417    }
418
419    fn str(&mut self) -> Result<String, BytecodeError> {
420        let len = self.u32()? as usize;
421        // Reject lengths that overrun the buffer before allocating.
422        if len > self.remaining() {
423            return Err(BytecodeError::Corrupt("string length exceeds buffer"));
424        }
425        let bytes = self.need(len)?;
426        String::from_utf8(bytes.to_vec()).map_err(|_| BytecodeError::Corrupt("utf8"))
427    }
428
429    fn opt_str(&mut self) -> Result<Option<String>, BytecodeError> {
430        if self.u8()? == 0 {
431            Ok(None)
432        } else {
433            Ok(Some(self.str()?))
434        }
435    }
436
437    fn opt_bytes(&mut self) -> Result<Option<Vec<u8>>, BytecodeError> {
438        if self.u8()? == 0 {
439            Ok(None)
440        } else {
441            let len = self.u32()? as usize;
442            if len > self.remaining() {
443                return Err(BytecodeError::Corrupt("bytes length exceeds buffer"));
444            }
445            Ok(Some(self.need(len)?.to_vec()))
446        }
447    }
448
449    fn opt_u16(&mut self) -> Result<Option<u16>, BytecodeError> {
450        if self.u8()? == 0 {
451            Ok(None)
452        } else {
453            Ok(Some(self.u16()?))
454        }
455    }
456
457    /// Convert an untrusted `u32` count into a `usize`, bounded against the
458    /// remaining buffer.
459    ///
460    /// Every list/pool length in the bytecode is followed by at least one
461    /// byte per element (an opcode tag, a u8 discriminant, or a 4-byte
462    /// length prefix). The strict lower bound is `1` byte per item, so any
463    /// `count > remaining()` is unambiguously corrupt — and this check runs
464    /// **before** `Vec::with_capacity(count)`, so an attacker-controlled
465    /// `count = u32::MAX` cannot trigger a multi-GB allocation.
466    fn bounded_count(&self, raw: u32) -> Result<usize, BytecodeError> {
467        let count = raw as usize;
468        if count > self.remaining() {
469            return Err(BytecodeError::Corrupt(
470                "list length exceeds remaining bytes",
471            ));
472        }
473        Ok(count)
474    }
475}
476
477fn write_metadata(w: &mut Writer, metadata: &CheckMetadata) {
478    w.opt_str(&metadata.name);
479    w.opt_str(&metadata.description);
480    w.opt_str(&metadata.impact);
481    match &metadata.severity {
482        Some(s) => {
483            w.u8(1);
484            w.u8(severity_tag(s));
485        }
486        None => w.u8(0),
487    }
488    w.opt_str(&metadata.author);
489    write_strings(w, &metadata.cve);
490    write_strings(w, &metadata.cwe);
491    write_strings(w, &metadata.references);
492    write_strings(w, &metadata.cvss);
493    write_strings(w, &metadata.cvss_score);
494    w.opt_str(&metadata.mitigation);
495    write_strings(w, &metadata.tags);
496    w.opt_str(&metadata.version);
497    // `family` is the last field of the metadata block. Any change to this
498    // layout must bump VERSION (the registry has to redeploy + recompile).
499    w.opt_str(&metadata.family);
500}
501
502fn read_metadata(r: &mut Reader<'_>) -> Result<CheckMetadata, BytecodeError> {
503    Ok(CheckMetadata {
504        name: r.opt_str()?,
505        description: r.opt_str()?,
506        impact: r.opt_str()?,
507        severity: if r.u8()? == 0 {
508            None
509        } else {
510            Some(read_severity(r)?)
511        },
512        author: r.opt_str()?,
513        cve: read_strings(r)?,
514        cwe: read_strings(r)?,
515        references: read_strings(r)?,
516        cvss: read_strings(r)?,
517        cvss_score: read_strings(r)?,
518        mitigation: r.opt_str()?,
519        tags: read_strings(r)?,
520        version: r.opt_str()?,
521        family: r.opt_str()?,
522    })
523}
524
525fn severity_tag(s: &Severity) -> u8 {
526    match s {
527        Severity::Low => 0,
528        Severity::Medium => 1,
529        Severity::High => 2,
530        Severity::Critical => 3,
531        Severity::Info => 4,
532    }
533}
534
535fn read_severity(r: &mut Reader<'_>) -> Result<Severity, BytecodeError> {
536    Ok(match r.u8()? {
537        0 => Severity::Low,
538        1 => Severity::Medium,
539        2 => Severity::High,
540        3 => Severity::Critical,
541        4 => Severity::Info,
542        _ => return Err(BytecodeError::Corrupt("severity")),
543    })
544}
545
546fn write_probes(w: &mut Writer, probes: &HashMap<String, ProbeKind>) {
547    let mut names: Vec<_> = probes.keys().cloned().collect();
548    names.sort();
549    w.u32(names.len() as u32);
550    for name in names {
551        w.str(&name);
552        write_probe_kind(w, probes.get(&name).expect("sorted key"));
553    }
554}
555
556fn read_probes(r: &mut Reader<'_>) -> Result<HashMap<String, ProbeKind>, BytecodeError> {
557    let raw = r.u32()?;
558    let count = r.bounded_count(raw)?;
559    let mut probes = HashMap::with_capacity(count);
560    for _ in 0..count {
561        let name = r.str()?;
562        let kind = read_probe_kind(r)?;
563        probes.insert(name, kind);
564    }
565    Ok(probes)
566}
567
568fn write_probe_kind(w: &mut Writer, kind: &ProbeKind) {
569    match kind {
570        ProbeKind::Http(spec) => {
571            w.u8(0);
572            write_http_spec(w, spec);
573        }
574        ProbeKind::Dns(spec) => {
575            w.u8(1);
576            write_socket_probe(w, spec);
577        }
578        ProbeKind::Tcp(spec) => {
579            w.u8(2);
580            write_socket_probe(w, spec);
581        }
582        ProbeKind::Udp(spec) => {
583            w.u8(3);
584            write_socket_probe(w, spec);
585        }
586    }
587}
588
589fn write_socket_probe(w: &mut Writer, spec: &crate::runtime::spec::SocketProbeSpec) {
590    w.str(&spec.host);
591    w.opt_u16(spec.port);
592    w.opt_bytes(&spec.payload);
593    w.u8(u8::from(spec.tls));
594    w.u8(u8::from(spec.session));
595    w.u32(spec.read_max);
596    w.u32(spec.read_idle_ms);
597}
598
599fn read_socket_probe(
600    r: &mut Reader<'_>,
601) -> Result<crate::runtime::spec::SocketProbeSpec, BytecodeError> {
602    Ok(crate::runtime::spec::SocketProbeSpec {
603        host: r.str()?,
604        port: r.opt_u16()?,
605        payload: r.opt_bytes()?,
606        tls: r.u8()? != 0,
607        session: r.u8()? != 0,
608        read_max: r.u32()?,
609        read_idle_ms: r.u32()?,
610    })
611}
612
613fn read_probe_kind(r: &mut Reader<'_>) -> Result<ProbeKind, BytecodeError> {
614    Ok(match r.u8()? {
615        0 => ProbeKind::Http(read_http_spec(r)?),
616        1 => ProbeKind::Dns(read_socket_probe(r)?),
617        2 => ProbeKind::Tcp(read_socket_probe(r)?),
618        3 => ProbeKind::Udp(read_socket_probe(r)?),
619        _ => return Err(BytecodeError::Corrupt("probe kind")),
620    })
621}
622
623fn write_http_spec(w: &mut Writer, spec: &HttpRequestSpec) {
624    w.u8(http_method_tag(&spec.method));
625    w.str(&spec.path);
626    w.opt_str(&spec.timeout);
627    write_opt_bool(w, &spec.follow_redirect);
628    write_opt_bool(w, &spec.verify_ssl);
629    w.opt_str(&spec.proxy);
630    w.opt_str(&spec.user_agent);
631    write_header_list(w, &spec.headers);
632    write_header_list(w, &spec.cookies);
633    write_header_list(w, &spec.queries);
634    write_opt_object(w, &spec.data_body);
635    write_opt_object(w, &spec.json_body);
636    w.opt_str(&spec.raw_body);
637    w.opt_str(&spec.body_bytes);
638    write_opt_object(w, &spec.multipart_body);
639}
640
641fn read_http_spec(r: &mut Reader<'_>) -> Result<HttpRequestSpec, BytecodeError> {
642    Ok(HttpRequestSpec {
643        method: read_http_method(r)?,
644        path: r.str()?,
645        timeout: r.opt_str()?,
646        follow_redirect: read_opt_bool(r)?,
647        verify_ssl: read_opt_bool(r)?,
648        proxy: r.opt_str()?,
649        user_agent: r.opt_str()?,
650        headers: read_header_list(r)?,
651        cookies: read_header_list(r)?,
652        queries: read_header_list(r)?,
653        data_body: read_opt_object(r)?,
654        json_body: read_opt_object(r)?,
655        raw_body: r.opt_str()?,
656        body_bytes: r.opt_str()?,
657        multipart_body: read_opt_object(r)?,
658    })
659}
660
661fn http_method_tag(m: &HttpMethod) -> u8 {
662    match m {
663        HttpMethod::Get => 0,
664        HttpMethod::Post => 1,
665        HttpMethod::Put => 2,
666        HttpMethod::Patch => 3,
667        HttpMethod::Delete => 4,
668        HttpMethod::Head => 5,
669        HttpMethod::Options => 6,
670    }
671}
672
673fn read_http_method(r: &mut Reader<'_>) -> Result<HttpMethod, BytecodeError> {
674    Ok(match r.u8()? {
675        0 => HttpMethod::Get,
676        1 => HttpMethod::Post,
677        2 => HttpMethod::Put,
678        3 => HttpMethod::Patch,
679        4 => HttpMethod::Delete,
680        5 => HttpMethod::Head,
681        6 => HttpMethod::Options,
682        _ => return Err(BytecodeError::Corrupt("http method")),
683    })
684}
685
686fn write_opt_bool(w: &mut Writer, value: &Option<bool>) {
687    match value {
688        Some(v) => {
689            w.u8(1);
690            w.u8(u8::from(*v));
691        }
692        None => w.u8(0),
693    }
694}
695
696fn read_opt_bool(r: &mut Reader<'_>) -> Result<Option<bool>, BytecodeError> {
697    if r.u8()? == 0 {
698        Ok(None)
699    } else {
700        Ok(Some(r.u8()? != 0))
701    }
702}
703
704fn write_header_list(w: &mut Writer, pairs: &[(String, String)]) {
705    w.u32(pairs.len() as u32);
706    for (k, v) in pairs {
707        w.str(k);
708        w.str(v);
709    }
710}
711
712fn read_header_list(r: &mut Reader<'_>) -> Result<Vec<(String, String)>, BytecodeError> {
713    let raw = r.u32()?;
714    let count = r.bounded_count(raw)?;
715    let mut pairs = Vec::with_capacity(count);
716    for _ in 0..count {
717        pairs.push((r.str()?, r.str()?));
718    }
719    Ok(pairs)
720}
721
722fn write_opt_object(w: &mut Writer, body: &Option<ObjectBody>) {
723    match body {
724        Some(obj) => {
725            w.u8(1);
726            write_object(w, obj);
727        }
728        None => w.u8(0),
729    }
730}
731
732fn read_opt_object(r: &mut Reader<'_>) -> Result<Option<ObjectBody>, BytecodeError> {
733    if r.u8()? == 0 {
734        Ok(None)
735    } else {
736        Ok(Some(read_object(r)?))
737    }
738}
739
740fn write_object(w: &mut Writer, obj: &ObjectBody) {
741    w.u32(obj.pairs.len() as u32);
742    for (key, value) in &obj.pairs {
743        w.str(key);
744        write_body_value(w, value);
745    }
746}
747
748fn read_object(r: &mut Reader<'_>) -> Result<ObjectBody, BytecodeError> {
749    let raw = r.u32()?;
750    let count = r.bounded_count(raw)?;
751    let mut pairs = Vec::with_capacity(count);
752    for _ in 0..count {
753        pairs.push((r.str()?, read_body_value(r)?));
754    }
755    Ok(ObjectBody { pairs })
756}
757
758fn write_body_value(w: &mut Writer, value: &BodyValue) {
759    match value {
760        BodyValue::String(s) => {
761            w.u8(0);
762            w.str(s);
763        }
764        BodyValue::Interpolation(s) => {
765            w.u8(1);
766            w.str(s);
767        }
768        BodyValue::Object(obj) => {
769            w.u8(2);
770            write_object(w, obj);
771        }
772        BodyValue::Bytes(hex) => {
773            w.u8(3);
774            w.str(hex);
775        }
776        BodyValue::Part(part) => {
777            w.u8(4);
778            w.opt_str(&part.filename);
779            match &part.body {
780                InlinePartBody::Text(t) => {
781                    w.u8(0);
782                    w.str(t);
783                }
784                InlinePartBody::Bytes(b) => {
785                    w.u8(1);
786                    w.str(b);
787                }
788            }
789        }
790    }
791}
792
793fn read_body_value(r: &mut Reader<'_>) -> Result<BodyValue, BytecodeError> {
794    Ok(match r.u8()? {
795        0 => BodyValue::String(r.str()?),
796        1 => BodyValue::Interpolation(r.str()?),
797        2 => BodyValue::Object(read_object(r)?),
798        3 => BodyValue::Bytes(r.str()?),
799        4 => BodyValue::Part(InlinePart {
800            filename: r.opt_str()?,
801            body: match r.u8()? {
802                1 => InlinePartBody::Bytes(r.str()?),
803                _ => InlinePartBody::Text(r.str()?),
804            },
805        }),
806        _ => return Err(BytecodeError::Corrupt("body value")),
807    })
808}
809
810fn write_strings(w: &mut Writer, strings: &[String]) {
811    w.u32(strings.len() as u32);
812    for s in strings {
813        w.str(s);
814    }
815}
816
817fn read_strings(r: &mut Reader<'_>) -> Result<Vec<String>, BytecodeError> {
818    let raw = r.u32()?;
819    let count = r.bounded_count(raw)?;
820    let mut strings = Vec::with_capacity(count);
821    for _ in 0..count {
822        strings.push(r.str()?);
823    }
824    Ok(strings)
825}
826
827fn write_payloads(w: &mut Writer, payloads: &[Vec<u8>]) {
828    w.u32(payloads.len() as u32);
829    for data in payloads {
830        w.u32(data.len() as u32);
831        w.bytes(data);
832    }
833}
834
835fn read_payloads(r: &mut Reader<'_>) -> Result<Vec<Vec<u8>>, BytecodeError> {
836    let raw = r.u32()?;
837    let count = r.bounded_count(raw)?;
838    let mut payloads = Vec::with_capacity(count);
839    for _ in 0..count {
840        let len = r.u32()? as usize;
841        if len > r.remaining() {
842            return Err(BytecodeError::Corrupt("payload length exceeds buffer"));
843        }
844        payloads.push(r.need(len)?.to_vec());
845    }
846    Ok(payloads)
847}
848
849fn write_matchers(w: &mut Writer, matchers: &[QualifiedMatch]) {
850    w.u32(matchers.len() as u32);
851    for m in matchers {
852        write_matcher(w, m);
853    }
854}
855
856fn read_matchers(r: &mut Reader<'_>) -> Result<Vec<QualifiedMatch>, BytecodeError> {
857    let raw = r.u32()?;
858    let count = r.bounded_count(raw)?;
859    let mut matchers = Vec::with_capacity(count);
860    for _ in 0..count {
861        matchers.push(read_matcher(r)?);
862    }
863    Ok(matchers)
864}
865
866fn write_matcher(w: &mut Writer, m: &QualifiedMatch) {
867    w.str(&m.field.target);
868    write_field_kind(w, &m.field.kind);
869    write_predicate(w, &m.predicate);
870}
871
872fn read_matcher(r: &mut Reader<'_>) -> Result<QualifiedMatch, BytecodeError> {
873    Ok(QualifiedMatch {
874        field: QualifiedField {
875            target: r.str()?,
876            kind: read_field_kind(r)?,
877        },
878        predicate: read_predicate(r)?,
879    })
880}
881
882fn write_field_kind(w: &mut Writer, kind: &FieldKind) {
883    match kind {
884        FieldKind::Status => w.u8(0),
885        FieldKind::Body => w.u8(1),
886        FieldKind::Header(name) => {
887            w.u8(2);
888            w.str(name);
889        }
890        FieldKind::ResponseTime => w.u8(3),
891        FieldKind::ResponseSize => w.u8(4),
892        FieldKind::Answer => w.u8(5),
893        FieldKind::Banner => w.u8(6),
894        FieldKind::Response => w.u8(7),
895    }
896}
897
898fn read_field_kind(r: &mut Reader<'_>) -> Result<FieldKind, BytecodeError> {
899    Ok(match r.u8()? {
900        0 => FieldKind::Status,
901        1 => FieldKind::Body,
902        2 => FieldKind::Header(r.str()?),
903        3 => FieldKind::ResponseTime,
904        4 => FieldKind::ResponseSize,
905        5 => FieldKind::Answer,
906        6 => FieldKind::Banner,
907        7 => FieldKind::Response,
908        _ => return Err(BytecodeError::Corrupt("field kind")),
909    })
910}
911
912fn write_predicate(w: &mut Writer, p: &MatchPredicate) {
913    match p {
914        MatchPredicate::Compare { op, value } => {
915            w.u8(0);
916            w.u8(cmp_op_tag(*op));
917            write_cmp_value(w, value);
918        }
919        MatchPredicate::Contains(s) => {
920            w.u8(1);
921            w.str(s);
922        }
923        MatchPredicate::NotContains(s) => {
924            w.u8(2);
925            w.str(s);
926        }
927        MatchPredicate::Regex(s) => {
928            w.u8(3);
929            w.str(s);
930        }
931    }
932}
933
934fn read_predicate(r: &mut Reader<'_>) -> Result<MatchPredicate, BytecodeError> {
935    Ok(match r.u8()? {
936        0 => MatchPredicate::Compare {
937            op: read_cmp_op(r)?,
938            value: read_cmp_value(r)?,
939        },
940        1 => MatchPredicate::Contains(r.str()?),
941        2 => MatchPredicate::NotContains(r.str()?),
942        3 => MatchPredicate::Regex(r.str()?),
943        _ => return Err(BytecodeError::Corrupt("predicate")),
944    })
945}
946
947fn cmp_op_tag(op: CmpOp) -> u8 {
948    match op {
949        CmpOp::Eq => 0,
950        CmpOp::Ne => 1,
951        CmpOp::Lt => 2,
952        CmpOp::Gt => 3,
953        CmpOp::Le => 4,
954        CmpOp::Ge => 5,
955    }
956}
957
958fn read_cmp_op(r: &mut Reader<'_>) -> Result<CmpOp, BytecodeError> {
959    Ok(match r.u8()? {
960        0 => CmpOp::Eq,
961        1 => CmpOp::Ne,
962        2 => CmpOp::Lt,
963        3 => CmpOp::Gt,
964        4 => CmpOp::Le,
965        5 => CmpOp::Ge,
966        _ => return Err(BytecodeError::Corrupt("cmp op")),
967    })
968}
969
970fn write_cmp_value(w: &mut Writer, value: &CmpValue) {
971    match value {
972        CmpValue::Number(n) => {
973            w.u8(0);
974            // Full u64 — earlier revisions truncated to u32, silently
975            // mangling comparisons against values above ~4.3 billion (e.g.
976            // `response_size > 5_000_000_000`).
977            w.u64(*n);
978        }
979        CmpValue::String(s) => {
980            w.u8(1);
981            w.str(s);
982        }
983        CmpValue::Duration(d) => {
984            w.u8(2);
985            w.str(d);
986        }
987    }
988}
989
990fn read_cmp_value(r: &mut Reader<'_>) -> Result<CmpValue, BytecodeError> {
991    Ok(match r.u8()? {
992        0 => CmpValue::Number(r.u64()?),
993        1 => CmpValue::String(r.str()?),
994        2 => CmpValue::Duration(r.str()?),
995        _ => return Err(BytecodeError::Corrupt("cmp value")),
996    })
997}
998
999fn write_extracts(w: &mut Writer, extracts: &[ExtractSource]) {
1000    w.u32(extracts.len() as u32);
1001    for e in extracts {
1002        write_extract(w, e);
1003    }
1004}
1005
1006fn read_extracts(r: &mut Reader<'_>) -> Result<Vec<ExtractSource>, BytecodeError> {
1007    let raw = r.u32()?;
1008    let count = r.bounded_count(raw)?;
1009    let mut extracts = Vec::with_capacity(count);
1010    for _ in 0..count {
1011        extracts.push(read_extract(r)?);
1012    }
1013    Ok(extracts)
1014}
1015
1016fn write_extract(w: &mut Writer, e: &ExtractSource) {
1017    match e {
1018        ExtractSource::Body { target, regex } => {
1019            w.u8(0);
1020            w.str(target);
1021            w.opt_str(regex);
1022        }
1023        ExtractSource::Header { target, name } => {
1024            w.u8(1);
1025            w.str(target);
1026            w.str(name);
1027        }
1028    }
1029}
1030
1031fn read_extract(r: &mut Reader<'_>) -> Result<ExtractSource, BytecodeError> {
1032    Ok(match r.u8()? {
1033        0 => ExtractSource::Body {
1034            target: r.str()?,
1035            regex: r.opt_str()?,
1036        },
1037        1 => ExtractSource::Header {
1038            target: r.str()?,
1039            name: r.str()?,
1040        },
1041        _ => return Err(BytecodeError::Corrupt("extract")),
1042    })
1043}
1044
1045fn write_evidence(w: &mut Writer, kinds: &[EvidenceKind]) {
1046    w.u32(kinds.len() as u32);
1047    for k in kinds {
1048        write_evidence_kind(w, k);
1049    }
1050}
1051
1052fn read_evidence(r: &mut Reader<'_>) -> Result<Vec<EvidenceKind>, BytecodeError> {
1053    let raw = r.u32()?;
1054    let count = r.bounded_count(raw)?;
1055    let mut kinds = Vec::with_capacity(count);
1056    for _ in 0..count {
1057        kinds.push(read_evidence_kind(r)?);
1058    }
1059    Ok(kinds)
1060}
1061
1062fn write_evidence_kind(w: &mut Writer, k: &EvidenceKind) {
1063    match k {
1064        EvidenceKind::Body { target, pattern } => {
1065            w.u8(0);
1066            w.str(target);
1067            w.opt_str(pattern);
1068        }
1069        EvidenceKind::Response { target, pattern } => {
1070            w.u8(1);
1071            w.str(target);
1072            w.opt_str(pattern);
1073        }
1074        EvidenceKind::Header {
1075            target,
1076            name,
1077            pattern,
1078        } => {
1079            w.u8(2);
1080            w.str(target);
1081            w.str(name);
1082            w.opt_str(pattern);
1083        }
1084    }
1085}
1086
1087fn read_evidence_kind(r: &mut Reader<'_>) -> Result<EvidenceKind, BytecodeError> {
1088    Ok(match r.u8()? {
1089        0 => EvidenceKind::Body {
1090            target: r.str()?,
1091            pattern: r.opt_str()?,
1092        },
1093        1 => EvidenceKind::Response {
1094            target: r.str()?,
1095            pattern: r.opt_str()?,
1096        },
1097        2 => EvidenceKind::Header {
1098            target: r.str()?,
1099            name: r.str()?,
1100            pattern: r.opt_str()?,
1101        },
1102        _ => return Err(BytecodeError::Corrupt("evidence")),
1103    })
1104}
1105
1106const OP_SET: u8 = 1;
1107const OP_SEND: u8 = 2;
1108const OP_MATCH: u8 = 3;
1109const OP_MATCH_ALL: u8 = 4;
1110const OP_MATCH_ANY: u8 = 5;
1111const OP_ASSERT: u8 = 6;
1112const OP_EXTRACT: u8 = 7;
1113const OP_IF_MATCH: u8 = 8;
1114const OP_SAVE: u8 = 9;
1115const OP_EVIDENCE: u8 = 10;
1116const OP_RETRY: u8 = 11;
1117const OP_RETRY_DELAY: u8 = 12;
1118const OP_SLEEP: u8 = 13;
1119const OP_STOP: u8 = 14;
1120const OP_FAIL: u8 = 15;
1121const OP_CONTINUE: u8 = 16;
1122const OP_EXIT: u8 = 17;
1123// 18 reserved: was `Repeat`, removed. Decoding it now yields an unknown-opcode
1124// error (no published bytecode uses it).
1125const OP_LOOP_BACK: u8 = 19;
1126const OP_BREAK: u8 = 20;
1127const OP_SET_LIST: u8 = 21;
1128const OP_FOR_LIST: u8 = 22;
1129const OP_FOR_VAR: u8 = 23;
1130
1131fn write_code(w: &mut Writer, code: &[Instr]) {
1132    w.u32(code.len() as u32);
1133    for instr in code {
1134        write_instr(w, instr);
1135    }
1136}
1137
1138fn read_code(r: &mut Reader<'_>) -> Result<Vec<Instr>, BytecodeError> {
1139    let raw = r.u32()?;
1140    let count = r.bounded_count(raw)?;
1141    let mut code = Vec::with_capacity(count);
1142    for _ in 0..count {
1143        code.push(read_instr(r)?);
1144    }
1145    Ok(code)
1146}
1147
1148fn write_instr(w: &mut Writer, instr: &Instr) {
1149    match instr {
1150        Instr::Set { name, value } => {
1151            w.u8(OP_SET);
1152            w.u32(*name);
1153            w.u32(*value);
1154        }
1155        Instr::SetList { name, start, len } => {
1156            w.u8(OP_SET_LIST);
1157            w.u32(*name);
1158            w.u32(*start);
1159            w.u16(*len);
1160        }
1161        Instr::Send { probe, payload } => {
1162            w.u8(OP_SEND);
1163            w.u32(*probe);
1164            match payload {
1165                Some(id) => {
1166                    w.u8(1);
1167                    w.u32(*id);
1168                }
1169                None => w.u8(0),
1170            }
1171        }
1172        Instr::Match(matcher) => {
1173            w.u8(OP_MATCH);
1174            w.u32(*matcher);
1175        }
1176        Instr::MatchAll { start, len } => {
1177            w.u8(OP_MATCH_ALL);
1178            w.u32(*start);
1179            w.u16(*len);
1180        }
1181        Instr::MatchAny { start, len } => {
1182            w.u8(OP_MATCH_ANY);
1183            w.u32(*start);
1184            w.u16(*len);
1185        }
1186        Instr::Assert(matcher) => {
1187            w.u8(OP_ASSERT);
1188            w.u32(*matcher);
1189        }
1190        Instr::Extract { name, source } => {
1191            w.u8(OP_EXTRACT);
1192            w.u32(*name);
1193            w.u32(*source);
1194        }
1195        Instr::IfMatch { matcher, else_pc } => {
1196            w.u8(OP_IF_MATCH);
1197            w.u32(*matcher);
1198            w.u32(*else_pc);
1199        }
1200        Instr::ForList {
1201            item,
1202            start,
1203            len,
1204            end_pc,
1205        } => {
1206            w.u8(OP_FOR_LIST);
1207            w.u32(*item);
1208            w.u32(*start);
1209            w.u16(*len);
1210            w.u32(*end_pc);
1211        }
1212        Instr::ForVar { item, list, end_pc } => {
1213            w.u8(OP_FOR_VAR);
1214            w.u32(*item);
1215            w.u32(*list);
1216            w.u32(*end_pc);
1217        }
1218        Instr::LoopBack => w.u8(OP_LOOP_BACK),
1219        Instr::Break => w.u8(OP_BREAK),
1220        Instr::Save { from, to } => {
1221            w.u8(OP_SAVE);
1222            w.u32(*from);
1223            w.u32(*to);
1224        }
1225        Instr::Evidence(kind) => {
1226            w.u8(OP_EVIDENCE);
1227            w.u32(*kind);
1228        }
1229        Instr::Retry { probe, count } => {
1230            w.u8(OP_RETRY);
1231            w.u32(*probe);
1232            w.u32(*count);
1233        }
1234        Instr::RetryDelay(value) => {
1235            w.u8(OP_RETRY_DELAY);
1236            w.u32(*value);
1237        }
1238        Instr::Sleep(value) => {
1239            w.u8(OP_SLEEP);
1240            w.u32(*value);
1241        }
1242        Instr::Stop => w.u8(OP_STOP),
1243        Instr::Fail => w.u8(OP_FAIL),
1244        Instr::Continue => w.u8(OP_CONTINUE),
1245        Instr::Exit => w.u8(OP_EXIT),
1246    }
1247}
1248
1249fn read_instr(r: &mut Reader<'_>) -> Result<Instr, BytecodeError> {
1250    Ok(match r.u8()? {
1251        OP_SET => Instr::Set {
1252            name: r.u32()?,
1253            value: r.u32()?,
1254        },
1255        OP_SET_LIST => Instr::SetList {
1256            name: r.u32()?,
1257            start: r.u32()?,
1258            len: r.u16()?,
1259        },
1260        OP_SEND => {
1261            let probe = r.u32()?;
1262            let payload = if r.u8()? == 0 { None } else { Some(r.u32()?) };
1263            Instr::Send { probe, payload }
1264        }
1265        OP_MATCH => Instr::Match(r.u32()?),
1266        OP_MATCH_ALL => Instr::MatchAll {
1267            start: r.u32()?,
1268            len: r.u16()?,
1269        },
1270        OP_MATCH_ANY => Instr::MatchAny {
1271            start: r.u32()?,
1272            len: r.u16()?,
1273        },
1274        OP_ASSERT => Instr::Assert(r.u32()?),
1275        OP_EXTRACT => Instr::Extract {
1276            name: r.u32()?,
1277            source: r.u32()?,
1278        },
1279        OP_IF_MATCH => Instr::IfMatch {
1280            matcher: r.u32()?,
1281            else_pc: r.u32()?,
1282        },
1283        OP_FOR_LIST => Instr::ForList {
1284            item: r.u32()?,
1285            start: r.u32()?,
1286            len: r.u16()?,
1287            end_pc: r.u32()?,
1288        },
1289        OP_FOR_VAR => Instr::ForVar {
1290            item: r.u32()?,
1291            list: r.u32()?,
1292            end_pc: r.u32()?,
1293        },
1294        OP_LOOP_BACK => Instr::LoopBack,
1295        OP_BREAK => Instr::Break,
1296        OP_SAVE => Instr::Save {
1297            from: r.u32()?,
1298            to: r.u32()?,
1299        },
1300        OP_EVIDENCE => Instr::Evidence(r.u32()?),
1301        OP_RETRY => Instr::Retry {
1302            probe: r.u32()?,
1303            count: r.u32()?,
1304        },
1305        OP_RETRY_DELAY => Instr::RetryDelay(r.u32()?),
1306        OP_SLEEP => Instr::Sleep(r.u32()?),
1307        OP_STOP => Instr::Stop,
1308        OP_FAIL => Instr::Fail,
1309        OP_CONTINUE => Instr::Continue,
1310        OP_EXIT => Instr::Exit,
1311        _ => return Err(BytecodeError::Corrupt("opcode")),
1312    })
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318
1319    #[test]
1320    fn hex_roundtrip() {
1321        let bytes = vec![0x52, 0x55, 0x53, 0x4f, 0x01, 0xff];
1322        let hex = bytes_to_hex(&bytes);
1323        assert_eq!(hex_to_bytes(&hex).unwrap(), bytes);
1324    }
1325
1326    #[test]
1327    fn hex_rejects_non_hex_chars() {
1328        match hex_to_bytes("zz") {
1329            Err(BytecodeError::InvalidHex(_)) => {}
1330            other => panic!("expected InvalidHex, got {other:?}"),
1331        }
1332    }
1333
1334    #[test]
1335    fn read_severity_rejects_unknown_byte() {
1336        let mut r = Reader::new(&[0x99]);
1337        match read_severity(&mut r) {
1338            Err(BytecodeError::Corrupt("severity")) => {}
1339            other => panic!("expected Corrupt(severity), got {other:?}"),
1340        }
1341    }
1342
1343    #[test]
1344    fn read_severity_accepts_known_bytes() {
1345        for (byte, expected) in [
1346            (0u8, Severity::Low),
1347            (1, Severity::Medium),
1348            (2, Severity::High),
1349            (3, Severity::Critical),
1350            (4, Severity::Info),
1351        ] {
1352            let data = [byte];
1353            let mut r = Reader::new(&data);
1354            assert_eq!(read_severity(&mut r).unwrap(), expected);
1355        }
1356    }
1357
1358    #[test]
1359    fn read_http_method_rejects_unknown_byte() {
1360        let mut r = Reader::new(&[0xff]);
1361        assert!(matches!(
1362            read_http_method(&mut r),
1363            Err(BytecodeError::Corrupt("http method"))
1364        ));
1365    }
1366
1367    #[test]
1368    fn read_http_method_accepts_head_and_options() {
1369        for (byte, expected) in [(5u8, HttpMethod::Head), (6, HttpMethod::Options)] {
1370            let data = [byte];
1371            let mut r = Reader::new(&data);
1372            assert_eq!(read_http_method(&mut r).unwrap(), expected);
1373        }
1374    }
1375
1376    #[test]
1377    fn read_cmp_op_rejects_unknown_byte() {
1378        let mut r = Reader::new(&[0xfe]);
1379        assert!(matches!(
1380            read_cmp_op(&mut r),
1381            Err(BytecodeError::Corrupt("cmp op"))
1382        ));
1383    }
1384
1385    #[test]
1386    fn read_cmp_value_rejects_unknown_byte() {
1387        let mut r = Reader::new(&[0x77]);
1388        assert!(matches!(
1389            read_cmp_value(&mut r),
1390            Err(BytecodeError::Corrupt("cmp value"))
1391        ));
1392    }
1393
1394    #[test]
1395    fn cmp_number_roundtrips_full_u64() {
1396        // Regression for the u32 → u64 widening: writing wrapped to u32 and
1397        // silently truncated large numbers. The wire format preserves the
1398        // full u64.
1399        let mut w = Writer::default();
1400        let value = CmpValue::Number(u64::MAX - 5);
1401        write_cmp_value(&mut w, &value);
1402        let mut r = Reader::new(&w.0);
1403        assert_eq!(read_cmp_value(&mut r).unwrap(), value);
1404    }
1405
1406    #[test]
1407    fn bounded_count_rejects_oversized_count() {
1408        // Attacker writes count = u32::MAX with only a few bytes following.
1409        // Without bounding this triggers a multi-GB `Vec::with_capacity`.
1410        let mut payload = Vec::new();
1411        payload.extend_from_slice(&u32::MAX.to_le_bytes());
1412        let mut r = Reader::new(&payload);
1413        let raw = r.u32().unwrap();
1414        assert!(matches!(
1415            r.bounded_count(raw),
1416            Err(BytecodeError::Corrupt(
1417                "list length exceeds remaining bytes"
1418            ))
1419        ));
1420    }
1421
1422    #[test]
1423    fn read_strings_rejects_oversized_count() {
1424        // Bytecode: "RUSO" + version + huge string count + nothing else.
1425        let mut bad = Vec::new();
1426        bad.extend_from_slice(MAGIC);
1427        bad.push(VERSION);
1428        // skip past metadata/probes by hand-crafting minimal valid prefix
1429        // — instead exercise read_strings directly.
1430        let mut buf = Vec::new();
1431        buf.extend_from_slice(&u32::MAX.to_le_bytes());
1432        let mut r = Reader::new(&buf);
1433        assert!(matches!(
1434            read_strings(&mut r),
1435            Err(BytecodeError::Corrupt(_))
1436        ));
1437    }
1438
1439    #[test]
1440    fn read_payloads_rejects_oversized_count() {
1441        let mut buf = Vec::new();
1442        buf.extend_from_slice(&u32::MAX.to_le_bytes());
1443        let mut r = Reader::new(&buf);
1444        assert!(matches!(
1445            read_payloads(&mut r),
1446            Err(BytecodeError::Corrupt(_))
1447        ));
1448    }
1449
1450    #[test]
1451    fn read_payloads_rejects_oversized_payload_length() {
1452        // count = 1 (valid), but the single payload claims a huge length.
1453        let mut buf = Vec::new();
1454        buf.extend_from_slice(&1u32.to_le_bytes()); // count
1455        buf.extend_from_slice(&u32::MAX.to_le_bytes()); // payload length
1456        let mut r = Reader::new(&buf);
1457        assert!(matches!(
1458            read_payloads(&mut r),
1459            Err(BytecodeError::Corrupt(_))
1460        ));
1461    }
1462
1463    #[test]
1464    fn read_str_rejects_oversized_length() {
1465        let mut buf = Vec::new();
1466        buf.extend_from_slice(&u32::MAX.to_le_bytes());
1467        let mut r = Reader::new(&buf);
1468        assert!(matches!(r.str(), Err(BytecodeError::Corrupt(_))));
1469    }
1470
1471    #[test]
1472    fn decode_rejects_bad_version() {
1473        let mut buf = Vec::new();
1474        buf.extend_from_slice(MAGIC);
1475        buf.push(99); // unsupported version
1476        assert!(matches!(
1477            decode(&buf),
1478            Err(BytecodeError::BadVersion { found: 99, .. })
1479        ));
1480    }
1481
1482    #[test]
1483    fn decode_rejects_bad_magic() {
1484        let buf = [0u8, 0u8, 0u8, 0u8, VERSION];
1485        assert!(matches!(decode(&buf), Err(BytecodeError::BadMagic)));
1486    }
1487
1488    #[test]
1489    fn metadata_roundtrip_preserves_tags_and_lists() {
1490        let metadata = CheckMetadata {
1491            name: Some("Check".into()),
1492            description: None,
1493            impact: None,
1494            severity: Some(Severity::High),
1495            author: None,
1496            cve: vec!["CVE-2024-1".into()],
1497            cwe: vec!["CWE-79".into()],
1498            references: vec!["https://example.com".into()],
1499            cvss: vec![],
1500            cvss_score: vec![],
1501            mitigation: Some("patch".into()),
1502            tags: vec!["auth".into(), "rce".into()],
1503            version: Some("1.2.3".into()),
1504            family: Some("web".into()),
1505        };
1506        let mut w = Writer::default();
1507        write_metadata(&mut w, &metadata);
1508        let mut r = Reader::new(&w.0);
1509        let decoded = read_metadata(&mut r).unwrap();
1510        assert_eq!(decoded.tags, vec!["auth", "rce"]);
1511        assert_eq!(decoded.cve, vec!["CVE-2024-1"]);
1512        assert_eq!(decoded.mitigation.as_deref(), Some("patch"));
1513        assert_eq!(decoded.severity, Some(Severity::High));
1514        assert_eq!(decoded.version.as_deref(), Some("1.2.3"));
1515        assert_eq!(decoded.family.as_deref(), Some("web"));
1516    }
1517
1518    #[test]
1519    fn decode_rejects_out_of_range_string_index() {
1520        // A `Set { name: 7, value: 0 }` over an empty string pool would
1521        // panic the executor with an out-of-bounds index. decode() must
1522        // reject it as Corrupt instead.
1523        let program = BytecodeProgram {
1524            spec: ProgramSpec {
1525                probes: Default::default(),
1526                metadata: CheckMetadata::default(),
1527            },
1528            code: vec![Instr::Set { name: 7, value: 0 }],
1529            strings: vec![],
1530            payloads: vec![],
1531            matchers: vec![],
1532            extracts: vec![],
1533            evidence: vec![],
1534        };
1535        let bytes = encode(&program);
1536        match decode(&bytes) {
1537            Err(BytecodeError::Corrupt("operand index out of range")) => {}
1538            other => panic!("expected operand-index Corrupt, got {other:?}"),
1539        }
1540    }
1541
1542    #[test]
1543    fn decode_rejects_out_of_range_match_slice() {
1544        let program = BytecodeProgram {
1545            spec: ProgramSpec {
1546                probes: Default::default(),
1547                metadata: CheckMetadata::default(),
1548            },
1549            // MatchAll over [0,3) but the matcher pool is empty.
1550            code: vec![Instr::MatchAll { start: 0, len: 3 }],
1551            strings: vec![],
1552            payloads: vec![],
1553            matchers: vec![],
1554            extracts: vec![],
1555            evidence: vec![],
1556        };
1557        let bytes = encode(&program);
1558        assert!(matches!(decode(&bytes), Err(BytecodeError::Corrupt(_))));
1559    }
1560
1561    #[test]
1562    fn decode_accepts_in_range_operands() {
1563        let program = BytecodeProgram {
1564            spec: ProgramSpec {
1565                probes: Default::default(),
1566                metadata: CheckMetadata::default(),
1567            },
1568            code: vec![Instr::Set { name: 0, value: 1 }],
1569            strings: vec!["host".into(), "value".into()],
1570            payloads: vec![],
1571            matchers: vec![],
1572            extracts: vec![],
1573            evidence: vec![],
1574        };
1575        let bytes = encode(&program);
1576        let decoded = decode(&bytes).expect("valid operands round-trip");
1577        assert_eq!(decoded.code.len(), 1);
1578    }
1579
1580    #[test]
1581    fn load_bytecode_input_no_longer_reads_files() {
1582        // Earlier revisions accepted `@/path/to/file` to read raw bytecode.
1583        // That entry point is gone; `@…` should now be treated as hex input
1584        // and fail because `@` is not a hex digit.
1585        match load_bytecode_input("@/etc/passwd") {
1586            Err(BytecodeError::InvalidHex(_)) => {}
1587            other => panic!("expected InvalidHex, got {other:?}"),
1588        }
1589    }
1590}