diff --git a/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts index c973e1e6d..ba627f4bb 100644 --- a/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts +++ b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts @@ -148,14 +148,62 @@ test("a graceful return near the deadline leaves the builtin signal intact", asy } }); +/** + * Resolve true when `signal` settles, false if `ms` elapses first. The timer is + * always cleared, so a won race leaves nothing holding the event loop open. + */ +async function raceWithTimeout( + signal: Promise, + ms: number, +): Promise { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + signal.then(() => true), + new Promise((resolve) => { + timer = setTimeout(() => resolve(false), ms); + }), + ]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } +} + test("Ctrl+C aborts a held server connection via ctx.fetch: exit 130", async (t) => { const http = await import("node:http"); - let serverAborted = false; + // This test cancels an *in-flight* request, so it has to know the request is + // actually in flight before cancelling. It used to assume so after a fixed + // 200ms, which is a race: `bash.execute` has to reach the native + // interpreter, dispatch the builtin, and let undici open the connection + // first, and sibling tests in this file show builtin dispatch taking + // 1.3-1.5s on `windows-latest`. When 200ms ran out first, `cancel()` landed + // before the builtin ran, so no request was ever sent, the handler never + // ran, and nothing could ever report a disconnect — the assertion failed on + // a request that did not exist. That is the windows-latest flake in JS runs + // 45816668178 and 45980836967, and it is why a longer wait for the + // disconnect did not help: the two Windows lanes disagree run to run, so + // roughly half the time the 200ms won. + // + // So both halves now wait on events instead of the clock: `requestArrived` + // gates the cancel, and `disconnected` resolves on the first signal the + // client went away. Watching the socket as well as the request drops the + // assumption that `req` 'close' is the event that lands first on every + // platform. + let sawRequest!: () => void; + const requestArrived = new Promise((resolve) => { + sawRequest = resolve; + }); + let sawDisconnect!: () => void; + const disconnected = new Promise((resolve) => { + sawDisconnect = resolve; + }); const server = http.createServer((req, _res) => { // Hold the response indefinitely; detect the client going away. - req.on("close", () => { - serverAborted = true; - }); + sawRequest(); + req.on("close", sawDisconnect); + req.on("aborted", sawDisconnect); + req.socket.on("close", sawDisconnect); + req.socket.on("error", sawDisconnect); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); t.teardown(() => server.close()); @@ -171,17 +219,28 @@ test("Ctrl+C aborts a held server connection via ctx.fetch: exit 130", async (t) }, }); await bash.execute("MARKER=kept"); - const start = Date.now(); const pending = bash.execute("fetchHold"); - await new Promise((r) => setTimeout(r, 200)); + // Wait for the server to actually hold the request, so the cancel below + // aborts something that exists. Bounded so a request that never arrives + // fails here, where the cause is obvious, rather than as a mystery + // disconnect timeout further down. + const arrived = await raceWithTimeout(requestArrived, 30000); + t.true(arrived, "server received the held request before cancel"); + // Stop here on failure. Everything below is about aborting a request that + // is in flight, so without one it would cancel nothing, wait out the full + // disconnect timeout and report a second failure pointing away from the + // cause. `t.teardown`/`finally` still close the server. + if (!arrived) return; + // Timed from the cancel, not from `execute`: the bound below is about how + // fast cancellation unwinds, and starting the clock earlier would fold in + // however long dispatch and connection setup took on a slow runner. + const start = Date.now(); bash.cancel(); // programmatic Ctrl+C const cancelled = await pending; const elapsed = Date.now() - start; t.is(cancelled.exitCode, 130); t.true(elapsed < 10000, `cancellation took ${elapsed}ms`); - for (let i = 0; i < 100 && !serverAborted; i++) { - await new Promise((r) => setTimeout(r, 20)); - } + const serverAborted = await raceWithTimeout(disconnected, 20000); t.true(serverAborted, "server saw the connection abort"); const next = await bash.execute("echo next:$MARKER"); t.is(next.exitCode, 0); diff --git a/crates/bashkit/src/testing.rs b/crates/bashkit/src/testing.rs index ae536f321..1f898c699 100644 --- a/crates/bashkit/src/testing.rs +++ b/crates/bashkit/src/testing.rs @@ -59,11 +59,60 @@ pub const UNIVERSAL_BANNED: &[&str] = &[ "/.rustup/toolchains/", ]; -/// Cap on per-call stderr length. A single bad input must not flood -/// stderr beyond this — catches "one bad regex generates 10 MB of -/// library error spam" regressions. +/// Cap on per-call stderr length for the **strict** per-builtin path +/// ([`assert_no_leak`]). A hand-written `no_leak_*` case controls its own +/// input, so it has no reason to produce kilobytes of diagnostics: this stays +/// tight and catches "one bad regex generates 10 MB of library error spam" +/// regressions. +/// +/// Do not confuse this with the bound on a *single* diagnostic. One +/// diagnostic staying small is a separate product invariant (L-ARITH-002, +/// `MAX_ARITHMETIC_DIAG_ECHO`) covered by +/// `tests/integration/diagnostic_prefix_tests.rs`. pub const MAX_STDERR_BYTES: usize = 1024; +/// Cap on whole-execution stderr length for the **fuzz** path +/// ([`assert_fuzz_invariants`]), which is looser than [`MAX_STDERR_BYTES`] on +/// purpose. +/// +/// A fuzz target inlines bytes it does not choose, and one that builds +/// `ExecutionLimits::max_stderr_bytes(N)` is declaring N bytes acceptable for +/// its scripts. The engine truncates only at that limit, so a harness cap +/// below N rejects legitimately chatty-but-bounded output instead of catching +/// anything. Sharing the strict 1024 figure did exactly that: Fuzz Testing run +/// 45932089002 failed `printf_fuzz`, whose `printf '%d %o %x'` cycles its +/// format over every operand and so emits one `invalid number` diagnostic per +/// operand — 34 non-numeric operands rendered 1,283 bytes, inside the 4096 the +/// target itself configures. Any script landing in 1024..=4096 failed by +/// construction, so the cap was unsatisfiable rather than strict. At the +/// largest configured ceiling the assertion says "the engine honored the +/// stderr limit it was given", which is the regression it was written for. +/// +/// # Residual: targets that configure nothing +/// +/// Fifteen of the 26 fuzz targets configure 4096 and three configure 1024; the +/// remaining eight take the 1 MiB default, which is 256x this cap. For those +/// the harness — not a declared budget — is the operative bound, so this is a +/// deliberate flood limit for them rather than a satisfiable-by-construction +/// one, and the same false positive can recur there: a legitimate >4 KiB +/// stderr the engine would permit still trips it. That is a narrow risk today +/// (none of the eight drives a per-operand diagnostic loop the way `printf` +/// does), and the fix when it happens is to give that target an explicit +/// `max_stderr_bytes` declaring its real budget, not to raise this constant +/// blindly. +pub const MAX_FUZZ_STDERR_BYTES: usize = 4096; + +/// The largest `ExecutionLimits::max_stderr_bytes` any fuzz target explicitly +/// builds. Lowering [`MAX_FUZZ_STDERR_BYTES`] below it would make the +/// assertion unsatisfiable for those targets again, so the mismatch is a +/// compile error rather than a nightly-only failure. Raise this if a target +/// ever configures a larger budget. +const FUZZ_TARGET_STDERR_LIMIT: usize = 4096; +const _: () = assert!( + MAX_FUZZ_STDERR_BYTES >= FUZZ_TARGET_STDERR_LIMIT, + "MAX_FUZZ_STDERR_BYTES is tighter than the max_stderr_bytes the fuzz targets configure" +); + /// Magic value seeded into the host OS environment by `fuzz_init`. If /// this string ever appears in builtin stdout or stderr, a builtin is /// reading from `std::env::vars()` instead of the sandboxed `ctx.env` @@ -294,16 +343,65 @@ pub fn input_echo_would_trip(input: &str) -> bool { /// contains `"`, so it needs no padding of its own. const DIAGNOSTIC_ECHO_PAD: (&str, &str) = (": ", ": "); -/// True when `text` carries `needle` into a diagnostic — literally, or -/// after the shell drops NUL bytes during word expansion, which turns -/// ` bool { - text.contains(needle) || (text.contains('\0') && text.replace('\0', "").contains(needle)) + if text.contains(needle) { + return true; + } + if text.contains(DROPPED_BY_PARSERS) { + let stripped: String = text + .chars() + .filter(|c| !DROPPED_BY_PARSERS.contains(c)) + .collect(); + if stripped.contains(needle) { + return true; + } + } + false } /// True when `script` itself spells `pat`, so a diagnostic that quotes any @@ -545,8 +643,8 @@ fn is_clap_error_chrome_line(line: &str) -> bool { pub fn assert_fuzz_invariants(result: &ExecResult, script: &str, ctx: &str, tool_banned: &[&str]) { let stderr = &result.stderr; assert!( - stderr.len() <= MAX_STDERR_BYTES, - "[{ctx}] stderr exceeds {MAX_STDERR_BYTES} bytes ({} bytes):\n---\n{stderr}\n---", + stderr.len() <= MAX_FUZZ_STDERR_BYTES, + "[{ctx}] stderr exceeds {MAX_FUZZ_STDERR_BYTES} bytes ({} bytes):\n---\n{stderr}\n---", stderr.len() ); let stripped = strip_real_shell_error_lines(stderr); @@ -579,12 +677,22 @@ pub fn assert_fuzz_invariants(result: &ExecResult, script: &str, ctx: &str, tool } } +/// Clip `s` to at most `max` bytes for a failure message. +/// +/// Floors the cut to a character boundary: callers pass a fixed byte budget +/// and the strings here are arbitrary fuzz output, so slicing at `max` +/// directly panics whenever that offset lands inside a multi-byte character — +/// turning a clear assertion message into an unrelated backtrace on exactly +/// the path that reports a canary leak. fn truncate(s: &str, max: usize) -> String { if s.len() <= max { - s.to_string() - } else { - format!("{}...", &s[..max.min(s.len())]) + return s.to_string(); + } + let mut end = max; + while end > 0 && !s.is_char_boundary(end) { + end -= 1; } + format!("{}...", &s[..end]) } /// Decode one CPython HTTP bridge request record (the bytes the guest hands @@ -834,10 +942,14 @@ mod tests { #[test] fn attribution_does_not_relax_the_stderr_cap() { // A script that spells a banned shape still may not flood stderr. + // Sized off the constant so raising the cap cannot silently turn this + // into a no-op, the way the literal `repeat(200)` did. + const SHAPE: &str = "Undefined::"; let result = ExecResult { - stderr: "Undefined::".repeat(200).into(), + stderr: SHAPE.repeat(MAX_FUZZ_STDERR_BYTES / SHAPE.len() + 1).into(), ..Default::default() }; + assert!(result.stderr.len() > MAX_FUZZ_STDERR_BYTES); let err = std::panic::catch_unwind(|| { assert_fuzz_invariants(&result, "echo Undefined::", "cap_still_on", &[]); }) @@ -1033,4 +1145,115 @@ mod tests { let stripped = strip_real_shell_error_lines(s); assert!(stripped.contains("Span {"), "stripped: {stripped:?}"); } + + /// Fuzz Testing run 45932089002, `csv_fuzz`: the input carried the canary + /// with a `"` spliced into it, `echo` passed it through verbatim, and + /// `csv headers` removed the quote as a CSV quote character — so the + /// canary reached stdout whole while the script text never spelled it. + /// End-to-end on purpose: the quote removal belongs to the csv builtin, + /// so a hand-built `ExecResult` would not prove the path exists. + #[tokio::test] + async fn canary_forged_with_a_quote_the_csv_parser_drops_is_not_a_leak() { + let (head, tail) = FUZZ_HOST_CANARY.split_at(FUZZ_HOST_CANARY.len() - 10); + let forged = format!("{head}\"{tail}"); + assert!( + !forged.contains(FUZZ_HOST_CANARY), + "forgery must not be literal" + ); + let script = format!("echo '{}' | csv headers", forged.replace('\'', "'\\''")); + let result = run(&script).await; + // Precondition: the builtin really does reconstitute the canary. + assert!( + result.stdout.contains(FUZZ_HOST_CANARY), + "csv no longer drops the quote, so this regression is unreachable: {:?}", + result.stdout.to_string() + ); + // The script explains it, so this is a forgery and not a host-env read. + assert_fuzz_invariants(&result, &script, "canary_quote_forge", &[]); + } + + #[test] + #[should_panic(expected = "FUZZ canary leaked into stdout")] + fn a_script_with_quotes_that_cannot_spell_the_canary_still_leaks() { + // Dropping quote characters must not blanket-excuse any script that + // merely contains one: this script quotes something else entirely. + let result = ExecResult { + stdout: FUZZ_HOST_CANARY.into(), + ..Default::default() + }; + assert_fuzz_invariants( + &result, + "echo '\"unrelated\"' | csv headers", + "canary_leak_quoted", + &[], + ); + } + + /// Fuzz Testing run 45932089002, `printf_fuzz`: `printf '%d %o %x'` cycles + /// its format over every operand, so N non-numeric operands emit N + /// `invalid number` diagnostics. Thirty-four of them came to 1,283 bytes — + /// bounded, legitimate output well inside the `max_stderr_bytes(4096)` the + /// target configures, yet over the harness's old 1 KiB cap. + #[test] + fn per_operand_diagnostics_within_the_engine_limit_are_not_a_flood() { + let line = "bash: line 1: printf: : invalid number\n"; + let stderr = line.repeat(33); + assert!( + (1024..=4096).contains(&stderr.len()), + "fixture must land in the band the old cap rejected: {} bytes", + stderr.len() + ); + let result = ExecResult { + stderr: stderr.into(), + ..Default::default() + }; + assert_fuzz_invariants( + &result, + "printf '%d %o %x' ' ' ' ' ' '", + "stderr_per_operand", + &[], + ); + } + + #[test] + fn truncate_cuts_on_a_char_boundary() { + // The canary assertions hand `truncate` arbitrary fuzz output with a + // fixed 512-byte budget, so a cut landing inside a multi-byte + // character used to panic while *reporting* a leak. + let s = "é".repeat(400); // 2 bytes each; 512 splits the 256th + assert!(!s.is_char_boundary(512 - 1) || !s.is_char_boundary(511)); + let out = truncate(&s, 511); + assert!(out.ends_with("...")); + assert!(out.len() < s.len()); + // Multi-byte at the very first boundary, and the no-op path. + assert_eq!(truncate("ée", 1), "..."); + assert_eq!(truncate("abc", 3), "abc"); + } + + #[test] + #[should_panic(expected = "stderr exceeds")] + fn stderr_past_the_strict_cap_is_still_a_flood() { + // The fuzz path's cap moved; the strict path's did not go away. + let result = ExecResult { + stderr: "x".repeat(MAX_STDERR_BYTES + 1).into(), + ..Default::default() + }; + assert_no_leak(&result, "stderr_flood", &[]); + } + + #[test] + #[should_panic(expected = "stderr exceeds")] + fn loosening_the_fuzz_cap_did_not_loosen_the_strict_path() { + // Regression for the review finding on this change: both paths read one + // shared constant, so raising it for the fuzz targets silently let a + // builtin emit 1-4 KiB of Debug spam past `assert_no_leak`, which the + // threat model states is absolute. Sized between the two caps, so it + // fails if they are ever collapsed back into one. + const { assert!(MAX_STDERR_BYTES < MAX_FUZZ_STDERR_BYTES) } + let result = ExecResult { + stderr: "x".repeat(MAX_FUZZ_STDERR_BYTES).into(), + ..Default::default() + }; + assert_no_leak(&result, "strict_cap_unrelaxed", &[]); + } } diff --git a/crates/bashkit/tests/fuzz_crash_regressions.rs b/crates/bashkit/tests/fuzz_crash_regressions.rs index 3c2897588..9162a8905 100644 --- a/crates/bashkit/tests/fuzz_crash_regressions.rs +++ b/crates/bashkit/tests/fuzz_crash_regressions.rs @@ -124,6 +124,63 @@ async fn csv_crash_rustup_toolchains_is_an_echo_not_a_leak() { } } +/// `csv_fuzz`, Fuzz Testing run 45932089002: the input carried the host canary +/// with a `"` spliced into it (`..._D"O_NOT_LEAK`). `echo` passed that through +/// verbatim, then `csv headers` dropped the `"` as a CSV quote character and +/// printed the canary whole — so stdout held a token the script text never +/// spelled, and the TM-INF-013 assertion fired with no builtin having read +/// host env. libFuzzer harvests the canary from the detector's own `contains`, +/// so this is a forgery the harness armed; attribution now looks through the +/// characters a parser drops (`DROPPED_BY_PARSERS`). +#[tokio::test] +async fn csv_crash_quote_forged_canary_is_an_echo_not_a_leak() { + fuzz_init(); + let data = + b64("CgAKLwoACgAKCkJBU0hLSVRfRlVaWl9IT1NUX0NBTkFSWV80N2E4M2JjZl9EIk9fTk9UX0xFQUsFCgUKW1s="); + let input = std::str::from_utf8(&data).expect("crash unit is UTF-8"); + let mut bash = bash(4096); + for script in [ + format!("echo '{}' | csv headers", sq(input)), + format!("echo '{}' | csv count", sq(input)), + format!("echo '{}' | csv select 1", sq(input)), + format!("echo '{}' | csv -d '\\t' headers", sq(input)), + ] { + fuzz_exec(&mut bash, &script, "csv_fuzz", &[]).await; + } +} + +/// `printf_fuzz`, Fuzz Testing run 45932089002: `printf '%d %o %x'` cycles its +/// format over every operand, so this unit's 34 non-numeric operands each drew +/// an `invalid number` diagnostic — 1,283 bytes of bounded, legitimate stderr, +/// under the `max_stderr_bytes(4096)` the target configures but over the +/// harness's old 1 KiB cap. Not a flood: the harness was holding a +/// whole-execution budget to a single diagnostic's size. +#[tokio::test] +async fn printf_crash_per_operand_diagnostics_are_not_a_flood() { + fuzz_init(); + let data = b64( + "SwoKDgogCg4KIAoOCgoOCiAKDgoOCiAKDgolCg4KIAoOCiAKDgoOCiBACg4OCiAKDgolCg4KIAoOCiAKDgoOCiBACg4KIA==", + ); + let input = std::str::from_utf8(&data).expect("crash unit is UTF-8"); + let (format_str, args_str) = match input.find('\n') { + Some(pos) => (&input[..pos], &input[pos + 1..]), + None => (input, ""), + }; + let args_joined = args_str + .lines() + .map(|a| format!("'{}'", sq(a))) + .collect::>() + .join(" "); + let mut bash = bash(4096); + for script in [ + format!("printf '{}' {}", sq(format_str), args_joined), + format!("printf -v result '{}' {}", sq(format_str), args_joined), + format!("printf '%d %o %x' {args_joined}"), + ] { + fuzz_exec(&mut bash, &script, "printf_fuzz", &[]).await; + } +} + /// `tomlq_fuzz` run 304: `tomlq: path '' not found` quotes the query /// verbatim, and the query was `/.rustup/toolchains/…`. #[tokio::test] diff --git a/crates/bashkit/tests/integration/arithmetic_fuzz_scaffold_tests.rs b/crates/bashkit/tests/integration/arithmetic_fuzz_scaffold_tests.rs index 606c54403..a6f8a306c 100644 --- a/crates/bashkit/tests/integration/arithmetic_fuzz_scaffold_tests.rs +++ b/crates/bashkit/tests/integration/arithmetic_fuzz_scaffold_tests.rs @@ -2,7 +2,7 @@ // // The target wraps its input in `echo $((...))` and asserts the fuzz // invariants: no panic, and stderr that neither leaks Debug shapes/host paths -// nor runs past `bashkit::testing::MAX_STDERR_BYTES`. +// nor runs past `bashkit::testing::MAX_FUZZ_STDERR_BYTES`. // // An arithmetic error names the expression and then the unparsed rest as the // "error token". Both come from the script, so an expression whose first diff --git a/crates/bashkit/tests/integration/diagnostic_prefix_tests.rs b/crates/bashkit/tests/integration/diagnostic_prefix_tests.rs index 9dbe3e350..722b1f2d5 100644 --- a/crates/bashkit/tests/integration/diagnostic_prefix_tests.rs +++ b/crates/bashkit/tests/integration/diagnostic_prefix_tests.rs @@ -240,9 +240,17 @@ async fn interactive_mode_keeps_bare_prefix() { // so one bounded expression produced a diagnostic about twice its size. // `arithmetic_fuzz` (nightly fuzz run 270) found a 507-byte expression that // rendered 1,076 bytes of stderr, over the 1 KiB cap -// `bashkit::testing::assert_no_leak` holds every builtin to. - -/// Same cap as `bashkit::testing::MAX_STDERR_BYTES`. +// `bashkit::testing::assert_no_leak` holds every builtin to -- which is still +// 1 KiB. The fuzz path's whole-execution budget moved to the engine ceiling +// (`MAX_FUZZ_STDERR_BYTES`); the 1 KiB figure here is the per-diagnostic bound +// it always meant. + +/// Bound on a *single* diagnostic (L-ARITH-002), deliberately independent of +/// the harness's per-execution budgets: `bashkit::testing::MAX_STDERR_BYTES` +/// for the strict path and `MAX_FUZZ_STDERR_BYTES` for the fuzz path, which +/// tracks the engine's `max_stderr_bytes` ceiling. Conflating a whole-execution +/// budget with this one is what made the fuzz harness reject legitimately +/// chatty scripts; this per-diagnostic figure is the one that must stay small. const MAX_DIAG: usize = 1024; /// The reduced `arithmetic_fuzz` crash. The rejected `#` sits near the front, diff --git a/knowledge/log.md b/knowledge/log.md index 8dfa4b1dc..99d4b1a86 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -1,5 +1,9 @@ # Bashkit Knowledge Update Log +## 2026-11-27 + +* **Both fuzz-harness guards were unsatisfiable, not strict (nightly `Fuzz Testing` run 45932089002)**: `csv_fuzz` and `printf_fuzz` went red on the same night, each on a harness assertion rather than a product bug. `csv_fuzz` reported the host canary in stdout from the input `BASHKIT_FUZZ_HOST_CANARY_47a83bcf_D"O_NOT_LEAK`: `echo` passed the bytes through verbatim, then `csv headers` dropped the `"` as its CSV quote character and printed the canary whole, so the output held a token the script text never spelled. That is run 272's forgery one parser further down the pipeline -- libFuzzer still harvests the canary from the detector's own `contains`, and a spliced quote survived the comparison a spliced NUL already did not -- so `carries_through_expansion` now strips `DROPPED_BY_PARSERS` (NUL from word expansion, `"`/`'`/`\` from quote removal or the csv field parser) as well as NUL. Stripping only ever adds matches, and no banned shape and no part of the canary contains those characters, so every match it adds is a parser dropping punctuation out of script text. `printf_fuzz` tripped the stderr byte cap with 1,283 bytes, which was not a flood: `printf '%d %o %x'` cycles its format over every operand, so 34 non-numeric operands drew 34 `invalid number` diagnostics -- linear in the input and well inside the `max_stderr_bytes(4096)` the target configures. The harness was holding a *whole-execution* budget to a *single diagnostic's* size, so every script landing in 1024..=4096 failed by construction; The fuzz path now has its own `MAX_FUZZ_STDERR_BYTES` at the largest configured ceiling, which keeps what the assertion was for (the engine honored the limit it was given, and 10 MB of spam still fails) and leaves the 1 KiB per-diagnostic bound where it belongs, in `diagnostic_prefix_tests.rs` (L-ARITH-002). Two notes for the next cap change, both found in review of this one: raising the single shared `MAX_STDERR_BYTES` was the first attempt and it also moved `assert_no_leak`, the strict path the threat model calls absolute, from 1 KiB to 4 KiB -- the caps are separate constants now and `loosening_the_fuzz_cap_did_not_loosen_the_strict_path` fails if they are recombined; and `attribution_does_not_relax_the_stderr_cap` had hard-coded a 2,200-byte fixture that would have silently become a no-op, so it is sized off the constant. The eight targets that configure no limit take the 1 MiB default, so for them 4 KiB is a harness bound rather than a satisfiable one and this class can recur; the fix then is an explicit `max_stderr_bytes` on that target. Also fixed in passing, on the same reporting path: `truncate` sliced arbitrary fuzz output at a fixed 512 bytes and panicked whenever that offset landed inside a multi-byte character, replacing a canary-leak message with an unrelated backtrace. Crash-unit replays for both live in `crates/bashkit/tests/fuzz_crash_regressions.rs`. See [Security Testing](security/security-testing.md#builtin-diagnostics-and-fuzzing) and [Threat Model](security/threat-model.md). + ## 2026-11-25 * **jq generated value depth (#3013, TM-DOS-027)**: a flat `reduce range(100000) as $i (1; [.])` built a 100,000-level value from shallow syntax; traversal or `Rc` destruction then overflowed the native stack and killed the embedding process (Python SIGSEGV), which input-depth, heap, output and evaluator-context limits all miss and `catch_unwind` cannot contain. Values now have a 100-container ceiling admitted at construction, child attachment and before `fromjson` descent, sticky across `try`. Prevention added with the fix: `jq_value_depth_tests::generated_depth_bounded` replays the issue's full-scale filters in a supervised child on a 2 MiB embedding stack (verified to fail with SIGABRT when admission is disabled, without taking down the test binary); `container_mutation_sites_are_reviewed` pins every site in `builtins/jq` that creates or mutably reaches into an array/object body, so a jaq-json vendor sync that adds one fails until its depth admission is reviewed; a const assertion keeps input depth within value depth. The awk supervised-child launcher moved to the shared `tests/integration/bounded_child.rs` so new crash regressions reuse one bounded harness. See [Vendored jaq-json](runtimes/jaq-json-vendor.md#structural-depth-3013). diff --git a/knowledge/operations/testing.md b/knowledge/operations/testing.md index 2d507e145..13c1bea4d 100644 --- a/knowledge/operations/testing.md +++ b/knowledge/operations/testing.md @@ -830,3 +830,18 @@ cross-runtime compatibility. 2. runtime-compat tests use only `node:test`, `node:assert`, `node:module` 3. Files are plain `.mjs` (no TypeScript) 4. Keep files focused, one file per concern area +5. A test that needs something to have *happened* before it acts waits on the + event that says so, never on a fixed delay. The ava suite runs on + `windows-latest` as well as ubuntu (the `Runtime callbacks` lane of + `js.yml`, which gates `JS Check`), and builtin dispatch there can take + 1.3-1.5s, so a sleep tuned on Linux loses the race about half the time. + This cost two red runs on main (45816668178, 45980836967): a cancellation + test slept 200ms assuming its `ctx.fetch` was in flight, then cancelled. + When dispatch had not finished, no request was ever sent, so the server + handler never ran and no amount of waiting afterwards could observe the + disconnect the test asserted — the failure looked like a slow platform and + was really a request that did not exist. Reproduce the shape with + `bash.cancel()` before dispatch: exit 130, zero requests, zero closes. + Gate on the real signal (`requestArrived`), and resolve the outcome from + every event that could report it, raced against one generous timeout, so a + pass is immediate and only a genuine failure fails diff --git a/knowledge/security/security-testing.md b/knowledge/security/security-testing.md index 902b7f7d7..a04644776 100644 --- a/knowledge/security/security-testing.md +++ b/knowledge/security/security-testing.md @@ -291,6 +291,33 @@ hand-written `no_leak_*` cases must not put a banned shape in their input. Replays of the inputs that turned nightly fuzz runs red live in `crates/bashkit/tests/fuzz_crash_regressions.rs`. +Attribution also looks through the characters a parser on the way *deletes* +from the data it carries (`DROPPED_BY_PARSERS`): NUL, which shell word +expansion drops, and `"`/`'`/`\`, which shell quote removal and the `csv` +field parser drop. A needle spliced with one of those still reaches the output +intact, so the script has to be matched the same way -- run 45932089002 flagged +the host canary from a `csv` field spelled `..._D"O_NOT_LEAK`. + +Keep the three stderr budgets distinct, and do not let one constant serve two +of them. "Cap diagnostics at 1 KB" above is the bound on a *single* diagnostic +(L-ARITH-002). `MAX_STDERR_BYTES` (1 KiB) is the per-call budget for the strict +path, `assert_no_leak`, whose cases choose their own input. The fuzz path uses +`MAX_FUZZ_STDERR_BYTES` (4 KiB), the largest +`ExecutionLimits::max_stderr_bytes` any target configures, because a fuzz +target inlines bytes it did not choose and the engine emits up to the limit +that target declared — so a tighter harness figure there fails a legitimately +chatty script rather than catching anything. Run 45932089002 hit this on +`printf_fuzz`, where one `invalid number` diagnostic per operand came to 1,283 +bytes. + +Raising a single shared constant is the trap: it moves the strict cap too, +which is why these are now separate and +`loosening_the_fuzz_cap_did_not_loosen_the_strict_path` guards the split. The +eight targets that configure no limit take the 1 MiB default, so for them the +4 KiB harness figure is the operative bound rather than a satisfiable one — if +one of them ever emits legitimately more, give it an explicit +`max_stderr_bytes` rather than raising the harness cap. + ## Filesystem Certification The backend-neutral helper in diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index b636557a0..ae7101a9a 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -634,6 +634,59 @@ static source scan and the per-tool `assert_no_leak` cases stay absolute. Only a formatter whose leak is *triggered* by parsing the shape is genuinely hidden. +Run 45932089002 turned both halves of that design red again, each for a +reason the earlier runs had not reached, and neither was a product bug. + +`csv_fuzz` reported the host canary in stdout from the input +`BASHKIT_FUZZ_HOST_CANARY_47a83bcf_D"O_NOT_LEAK`. `echo` passed the bytes +through verbatim and `csv headers` then removed the `"` as its CSV quote +character, printing the canary whole — so the output carried a token the script +text never spelled, and attribution could not account for it. This is the +run-272 forgery one parser further down the pipeline: libFuzzer still harvests +the canary from the detector's own `contains`, and a spliced quote now survives +the comparison that a spliced NUL already did not. `carries_through_expansion` +therefore strips `DROPPED_BY_PARSERS` as well as NUL. Stripping can only add +matches, and no banned shape and no part of the canary contains any of those +characters, so the matches it adds are a parser dropping punctuation out of +script text. + +That is an over-approximation, deliberately. The strip is unconditional and +context-free, while a real parser drops those characters only in particular +positions — a `"` inside single quotes is data the shell keeps, `\` goes only +in escape position, and the csv quote rules are not the shell's — so a match +can be added for a splice no parser would have undone. Combined with +attribution being whole-script and whole-stderr, a fragment spliced in one part +of the script can excuse a genuine occurrence elsewhere in the same execution. +This is the same residual false negative `script_explains` carries, accepted +for the same reasons, and erring toward over-approximation is the right +direction here: under-approximating is what turns the nightly red on the +detector's own dictionary, as runs 272, 304, 310 and 45932089002 each did. + +`printf_fuzz` tripped the stderr byte cap with 1,283 bytes. `printf '%d %o %x'` +cycles its format over every operand, so 34 non-numeric operands drew 34 +`invalid number` diagnostics: output linear in the input, bounded, and well +inside the `max_stderr_bytes(4096)` the target itself configures. The harness +was holding a whole-execution budget to a single diagnostic's size, so any +script landing in 1024..=4096 was guaranteed to fail — the cap was +unsatisfiable rather than strict. The fuzz path now has its own +`MAX_FUZZ_STDERR_BYTES` at the largest configured ceiling, which preserves what +the assertion was written for: it says the engine honored the stderr limit it +was given, and 10 MB of library spam still fails. + +The first attempt raised the one shared `MAX_STDERR_BYTES` instead, which also +moved `assert_no_leak` — the strict path the threat model calls absolute — from +1 KiB to 4 KiB, letting a builtin emit kilobytes of Debug spam past it. Review +caught it; the caps are now separate constants and +`loosening_the_fuzz_cap_did_not_loosen_the_strict_path` fails if they are ever +collapsed back. Attribution still cannot relax either +(`attribution_does_not_relax_the_stderr_cap`, now sized off the constant so +raising a cap cannot quietly turn it into a no-op). Eight targets configure no +limit at all and so take the 1 MiB default; for them the harness cap is the +operative bound rather than a satisfiable one, so the same false positive can +recur there, and the fix then is to give that target an explicit +`max_stderr_bytes`. Crash-unit replays for both failures live in +`crates/bashkit/tests/fuzz_crash_regressions.rs`. + Display of a **Bashkit** error is not a safe formatter either: `Error`'s own variants stringify as Rust enum shapes (`io error: `, `internal error: `) that no shell prints, and `internal error:` is in `UNIVERSAL_BANNED`. Builtins @@ -673,13 +726,30 @@ machinery (`bashkit::testing::assert_fuzz_invariants`): assertion is scoped by attribution: a canary the executed script itself contains is the shell echoing input back, not a host read (run 272, above), so only an unexplained occurrence fails. + Attribution looks through the characters a parser on the way *deletes* + from the data it carries (`DROPPED_BY_PARSERS`: NUL from shell word + expansion, and `"`/`'`/`\` from shell quote removal or the `csv` + field parser), because a canary spliced with one of those still + arrives intact (run 45932089002, below). - **TM-INF-016 (host paths)**: `UNIVERSAL_BANNED` includes `/rustc/`, `/.cargo/registry/`, `target/{debug,release}/deps/`, `/.rustup/toolchains/` so leaked panic backtraces / build-artifact paths fail the assertion. -- **stderr flooding**: per-call stderr capped at `MAX_STDERR_BYTES` - (1 KB), one bad input that produces 10 MB of library-error spam - trips this. +- **stderr flooding**: one bad input that produces 10 MB of + library-error spam trips this. There are **two** caps, and they are + deliberately different. The strict per-builtin path + (`assert_no_leak`) stays at `MAX_STDERR_BYTES` (1 KiB): a + hand-written `no_leak_*` case controls its own input and has no + reason to emit kilobytes. The fuzz path (`assert_fuzz_invariants`) + uses `MAX_FUZZ_STDERR_BYTES` (4 KiB), the largest `max_stderr_bytes` + any target configures, because a target inlines bytes it did not + choose and the engine truncates only at the limit that target + declared — so a tighter harness number there is unsatisfiable rather + than strict (run 45932089002, below). Keeping them separate matters: + sharing one constant is how raising the fuzz figure first silently + relaxed the strict path. The bound on a *single* diagnostic is a + third, separate invariant (L-ARITH-002, + `MAX_ARITHMETIC_DIAG_ECHO`), also 1 KiB. Fuzz/proptest targets inline arbitrary input bytes into shell scripts, so bash/ls/uutils clap CLIs echo the input verbatim in error chrome (`bash: : command not found`,