interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-wire / tests / g1_fuzz.rs

255 lines · 9042 bytes Raw Blame History
1//! G1 acceptance: coverage-guided fuzzing of the untrusted length-prefixed frame decoder,
2//! for a budget fixed before the run, finds no panic, no read past a frame, and no
3//! allocation above the declared cap, and every malformed frame in the fuzz corpus is
4//! refused with a typed refusal.
5//!
6//! The budget here is a fixed execution count (deterministic in CI). The time-budgeted
7//! evidence run uses the `synapse-wire-fuzz` binary (see `docs/G1_WIRE_FRAMES.md`).
8//! Negative controls plant one bug each in a copy of the target and require the same
9//! fuzzer, with the same budget, to report it, so a silent detector cannot pass.
10
11use synapse_core::RefusalCode;
12use synapse_wire::frame::{WireLimits, WireRefusal, FRAME_HEADER_LEN};
13use synapse_wire::fuzz::{
14 malformed_seed_corpus, replay_corpus, run, run_target, seed_corpus, server_decode, Budget,
15 CountingAlloc, FuzzConfig, FuzzReport, TargetOutcome,
16};
17use synapse_wire::probe::{EdgeProbe, Probe};
18
19#[global_allocator]
20static ALLOC: CountingAlloc = CountingAlloc;
21
22/// Fuzz cap on a frame body (bytes); seeds are all smaller.
23const CAP: u32 = 8192;
24/// Execution budget, fixed before the run.
25const EXECS: u64 = 300_000;
26const SEED: u64 = 0x6100_F022;
27
28fn cfg(execs: u64) -> FuzzConfig {
29 FuzzConfig {
30 seed: SEED,
31 budget: Budget::Execs(execs),
32 limits: WireLimits {
33 max_frame_body: CAP,
34 },
35 max_corpus: 20_000,
36 }
37}
38
39fn seeds() -> Vec<Vec<u8>> {
40 let s = seed_corpus(&WireLimits {
41 max_frame_body: CAP,
42 });
43 assert_eq!(s.len(), VALID_SEEDS, "every sample frame fits the fuzz cap");
44 let mut all = s;
45 all.extend(malformed());
46 all
47}
48
49const VALID_SEEDS: usize = 14;
50
51fn malformed() -> Vec<Vec<u8>> {
52 malformed_seed_corpus(&WireLimits {
53 max_frame_body: CAP,
54 })
55}
56
57fn main_run() -> FuzzReport {
58 run(cfg(EXECS), &seeds())
59}
60
61#[test]
62fn fuzzing_frame_decoder_finds_no_panic_no_read_past_frame_no_allocation_over_cap() {
63 let r = main_run();
64 assert!(r.alloc_tracking, "the counting allocator must be installed");
65 assert_eq!(r.execs, EXECS);
66 assert_eq!(
67 r.violation_total(),
68 0,
69 "violations: {:?}",
70 r.violations
71 .iter()
72 .map(|v| (v.kind, &v.detail))
73 .collect::<Vec<_>>()
74 );
75 assert!(
76 r.peak_alloc as u64 <= u64::from(CAP),
77 "peak {}",
78 r.peak_alloc
79 );
80 // The run explored the decoder: new coverage beyond the seeds, most sites reached.
81 assert!(r.corpus.len() > r.seeds, "corpus {}", r.corpus.len());
82 assert!(
83 r.sites_unreached.len() * 10 <= r.sites_total,
84 "unreached decoder sites (lines of frame.rs): {:?} of {}",
85 r.sites_unreached,
86 r.sites_total
87 );
88 // Both accepted and refused outcomes, for every frame kind, were exercised.
89 for kind in [
90 "Hello", "Have", "Want", "Chunk", "Submit", "Accepted", "Refused",
91 ] {
92 assert!(
93 r.outcomes.contains_key(&format!("accepted:{kind}")),
94 "no accepted {kind}"
95 );
96 }
97}
98
99#[test]
100fn every_malformed_frame_in_fuzz_corpus_is_refused_with_typed_refusal() {
101 let r = main_run();
102 let limits = WireLimits {
103 max_frame_body: CAP,
104 };
105 let replay = replay_corpus(&r.corpus, &limits);
106 assert!(replay.violations.is_empty(), "{:?}", replay.violations);
107 let refused: usize = replay.refused.values().sum();
108 assert_eq!(replay.entries, replay.accepted_canonical + refused);
109 // The well-formed seeds are in the corpus and still decode canonically.
110 assert!(
111 replay.accepted_canonical >= VALID_SEEDS,
112 "accepted {} of {VALID_SEEDS} valid seeds",
113 replay.accepted_canonical
114 );
115 // Every hand-made malformed seed (bad magic, version, kind, flags, reserved, length over
116 // the cap, truncated, trailing byte) is in the corpus and refused with a typed refusal.
117 let bad = malformed();
118 assert_eq!(bad.len(), VALID_SEEDS * 9);
119 for (i, input) in bad.iter().enumerate() {
120 assert_eq!(&r.corpus[VALID_SEEDS + i], input);
121 match synapse_wire::fuzz::target(input, &limits) {
122 TargetOutcome::Refused(_) => {}
123 other => panic!("malformed seed {i} was not refused: {other:?}"),
124 }
125 }
126 assert!(refused > 0);
127 assert!(
128 replay.refused.len() >= 10,
129 "refusal kinds reached: {:?}",
130 replay.refused
131 );
132 // Each refusal maps to the typed service refusal `WireFrameMalformed`.
133 for input in &r.corpus {
134 if let TargetOutcome::Refused(w) = synapse_wire::fuzz::target(input, &limits) {
135 assert_eq!(w.clone().into_error().code, RefusalCode::WireFrameMalformed);
136 }
137 }
138}
139
140// ---------------------------------------------------------------------------------------
141// Negative controls: planted bugs the fuzzer must find within the same kind of budget.
142// ---------------------------------------------------------------------------------------
143
144const CONTROL_EXECS: u64 = 60_000;
145
146fn control(target: synapse_wire::fuzz::Target, kind: &str) {
147 let r = run_target(cfg(CONTROL_EXECS), &seeds(), target);
148 assert!(
149 r.violation_counts.get(kind).copied().unwrap_or(0) > 0,
150 "planted {kind} bug not found; counts {:?}",
151 r.violation_counts
152 );
153}
154
155/// A decoder that panics on a non-zero flags byte (a missing check before a table lookup).
156fn planted_panic(input: &[u8], l: &WireLimits, p: &mut EdgeProbe) -> TargetOutcome {
157 if input.len() >= FRAME_HEADER_LEN && input[0..4] == *b"SYNW" && input[6] != 0 {
158 let table = [0u8; 1];
159 let i = input[6] as usize;
160 p.site(1);
161 let _ = std::hint::black_box(table[std::hint::black_box(i)]);
162 }
163 server_decode(input, l, p)
164}
165
166/// A decoder that sizes a buffer from the declared length before checking the cap.
167fn planted_over_alloc(input: &[u8], l: &WireLimits, p: &mut EdgeProbe) -> TargetOutcome {
168 if input.len() >= FRAME_HEADER_LEN {
169 let n = u32::from_le_bytes(input[12..16].try_into().unwrap()) as usize;
170 let v: Vec<u8> = Vec::with_capacity(n.min(1 << 20));
171 std::hint::black_box(v);
172 }
173 server_decode(input, l, p)
174}
175
176/// A decoder whose answer depends on the byte after the frame (reads one byte too far).
177fn planted_read_past(input: &[u8], l: &WireLimits, p: &mut EdgeProbe) -> TargetOutcome {
178 let out = server_decode(input, l, p);
179 if let TargetOutcome::Accepted { consumed, .. } = &out {
180 if let Some(&next) = input.get(*consumed) {
181 p.touched(*consumed + 1);
182 if next & 1 == 1 {
183 return TargetOutcome::Refused(WireRefusal::TrailingBytes {
184 at: *consumed,
185 count: 1,
186 });
187 }
188 }
189 }
190 out
191}
192
193/// A decoder that ignores the reserved byte, so two encodings of one frame decode.
194fn planted_non_canonical(input: &[u8], l: &WireLimits, p: &mut EdgeProbe) -> TargetOutcome {
195 let mut v = input.to_vec();
196 if v.len() >= 8 {
197 v[7] = 0;
198 }
199 server_decode(&v, l, p)
200}
201
202#[test]
203fn negative_control_fuzzer_finds_planted_panic() {
204 control(planted_panic, "panic");
205}
206
207#[test]
208fn negative_control_fuzzer_finds_planted_allocation_over_cap() {
209 control(planted_over_alloc, "alloc_over_cap");
210}
211
212#[test]
213fn negative_control_fuzzer_finds_planted_read_past_frame() {
214 control(planted_read_past, "read_past_frame");
215}
216
217#[test]
218fn negative_control_fuzzer_finds_planted_non_canonical_accept() {
219 control(planted_non_canonical, "non_canonical_accept");
220}
221
222/// Regression from the first 300 s evidence run (`evidence/g1-wire-frames/fuzz-run1-71fa41e/`): a `Submit`
223/// whose scope lists many empty paths took 4 wire bytes per path but 24 bytes of memory per
224/// decoded `String`, so one allocation passed the cap. The decoder now refuses a path count
225/// whose decoded size would pass the cap.
226#[test]
227fn fuzz_regression_many_scope_paths_stay_under_allocation_cap() {
228 use synapse_wire::frame::{decode_frame, encode_frame, Frame, FrameBody};
229 use synapse_wire::fuzz::measured;
230 use synapse_wire::testkit::{envelope, ChainFixture};
231 let fx = ChainFixture::new(1, None);
232 let (env, _) = envelope(&fx.agent, "many", &[], &["x"], 1);
233 let mut req =
234 synapse_wire::session::submit_request(&fx.agent, fx.chain.clone(), &env, [5; 32], 1)
235 .unwrap();
236 req.scope.paths = vec![String::new(); 400];
237 let bytes = encode_frame(&Frame {
238 request_id: 1,
239 body: FrameBody::Submit(Box::new(req)),
240 })
241 .unwrap();
242 let limits = WireLimits {
243 max_frame_body: CAP,
244 };
245 assert!(bytes.len() - FRAME_HEADER_LEN <= CAP as usize);
246 let (res, peak, _) = measured(|| decode_frame(&bytes, &limits));
247 assert!(
248 peak as u64 <= u64::from(CAP),
249 "largest allocation {peak} over cap {CAP}"
250 );
251 assert!(
252 matches!(res.unwrap(), Err(WireRefusal::LengthOverCap { .. })),
253 "refused as over the cap"
254 );
255}