From 3dc927c22128a20df3d3ce7c637d7735e94f0b61 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Fri, 27 Nov 2026 09:42:42 +0000 Subject: [PATCH 1/6] fix(testing): make the fuzz stderr cap satisfiable and see through dropped quotes Nightly Fuzz Testing run 45932089002 went red on csv_fuzz and printf_fuzz. Neither was a product bug; both were harness guards reporting inputs they had armed the fuzzer to build. csv_fuzz flagged 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. That is the run-272 forgery one parser further down the pipeline: libFuzzer harvests the canary from the detector's own `contains`, and a spliced quote survived the comparison a spliced NUL already did not. carries_through_expansion now strips DROPPED_BY_PARSERS -- NUL from word expansion, and `"`/`'`/`\` from shell quote removal or the csv field parser -- 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 every match it adds is a parser dropping punctuation out of script text, which is an echo by definition. 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 -- output linear in the input 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 failed by construction; the cap was unsatisfiable rather than strict. MAX_STDERR_BYTES now matches the largest limit any target configures, which keeps what the assertion was written for: for those targets it says the engine honored the limit it was given, and 10 MB of library spam still fails. A const assertion makes a future mismatch a compile error instead of a nightly-only failure, and the 1 KiB per-diagnostic bound stays where it belongs, in diagnostic_prefix_tests.rs (L-ARITH-002). Both crash units are replayed in fuzz_crash_regressions.rs and reproduce the exact CI failures against the old harness, including the same 1,283 bytes. attribution_does_not_relax_the_stderr_cap had hard-coded a 2,200-byte fixture and would have silently become a no-op, so it is now sized off the constant. --- crates/bashkit/src/testing.rs | 173 +++++++++++++++++- .../bashkit/tests/fuzz_crash_regressions.rs | 57 ++++++ .../integration/diagnostic_prefix_tests.rs | 12 +- knowledge/log.md | 4 + knowledge/security/security-testing.md | 18 ++ knowledge/security/threat-model.md | 48 ++++- 6 files changed, 296 insertions(+), 16 deletions(-) diff --git a/crates/bashkit/src/testing.rs b/crates/bashkit/src/testing.rs index ae536f321..4afa0554b 100644 --- a/crates/bashkit/src/testing.rs +++ b/crates/bashkit/src/testing.rs @@ -59,10 +59,45 @@ pub const UNIVERSAL_BANNED: &[&str] = &[ "/.rustup/toolchains/", ]; -/// Cap on per-call stderr length. A single bad input must not flood +/// Cap on per-execution stderr length. A single bad input must not flood /// stderr beyond this — catches "one bad regex generates 10 MB of /// library error spam" regressions. -pub const MAX_STDERR_BYTES: usize = 1024; +/// +/// This is a *whole-execution* budget, and a target that builds +/// `ExecutionLimits::max_stderr_bytes(N)` is declaring N bytes acceptable for +/// its scripts. The harness must therefore not sit below the largest N any +/// target configures: the engine truncates only at its own limit, so a tighter +/// harness cap rejects legitimately chatty-but-bounded output instead of +/// catching anything. Fifteen of the 26 fuzz targets configure 4096, three +/// configure 1024, and the rest take the 1 MiB default — so at 1024 this +/// assertion was guaranteed to fire somewhere in 1024..=4096. Fuzz Testing run +/// 45932089002 hit it on `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 of entirely +/// legitimate output. Matching the largest configured ceiling keeps the +/// original intent intact: for those targets the assertion now says "the +/// engine honored the stderr limit it was given", which is exactly the +/// 10-MB-spam regression it was written for, and for the targets that +/// configure nothing it stays the deliberate harness-side flood bound it +/// always was. +/// +/// 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`; conflating the two is what +/// produced the false positive. +pub const MAX_STDERR_BYTES: usize = 4096; + +/// The largest `ExecutionLimits::max_stderr_bytes` any fuzz target explicitly +/// builds. Lowering [`MAX_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_STDERR_BYTES >= FUZZ_TARGET_STDERR_LIMIT, + "MAX_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 @@ -294,16 +329,50 @@ 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 @@ -834,10 +903,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_STDERR_BYTES / SHAPE.len() + 1).into(), ..Default::default() }; + assert!(result.stderr.len() > MAX_STDERR_BYTES); let err = std::panic::catch_unwind(|| { assert_fuzz_invariants(&result, "echo Undefined::", "cap_still_on", &[]); }) @@ -1033,4 +1106,84 @@ 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] + #[should_panic(expected = "stderr exceeds")] + fn stderr_past_the_engine_limit_is_still_a_flood() { + // The cap moved to match the engine ceiling; it did not go away. + let result = ExecResult { + stderr: "x".repeat(MAX_STDERR_BYTES + 1).into(), + ..Default::default() + }; + assert_no_leak(&result, "stderr_flood", &[]); + } } 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/diagnostic_prefix_tests.rs b/crates/bashkit/tests/integration/diagnostic_prefix_tests.rs index 9dbe3e350..fbd9d31ae 100644 --- a/crates/bashkit/tests/integration/diagnostic_prefix_tests.rs +++ b/crates/bashkit/tests/integration/diagnostic_prefix_tests.rs @@ -240,9 +240,15 @@ 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` then held every builtin to. That harness +// cap has since moved to the engine's whole-execution ceiling, so the 1 KiB +// figure lives on here as the per-diagnostic bound it always meant. + +/// Bound on a *single* diagnostic (L-ARITH-002), deliberately independent of +/// `bashkit::testing::MAX_STDERR_BYTES`, which is a whole-execution budget and +/// now tracks the engine's `max_stderr_bytes` ceiling instead. Conflating the +/// two 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..28471cf91 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; `MAX_STDERR_BYTES` now tracks the engine 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). Note for the next cap change: `attribution_does_not_relax_the_stderr_cap` had hard-coded a 2,200-byte fixture and would have silently become a no-op, so it is now sized off the constant. 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/security/security-testing.md b/knowledge/security/security-testing.md index 902b7f7d7..8a0259262 100644 --- a/knowledge/security/security-testing.md +++ b/knowledge/security/security-testing.md @@ -291,6 +291,24 @@ 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 two stderr budgets distinct. "Cap diagnostics at 1 KB" above is the +bound on a *single* diagnostic (L-ARITH-002). `MAX_STDERR_BYTES` is the +*whole-execution* budget and must track the largest +`ExecutionLimits::max_stderr_bytes` any target configures (4 KiB), because the +engine may emit right up to the limit it was given: a tighter harness figure +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. A target that configures a lower figure is +still held to it by the engine, and the eight targets that configure nothing +keep the 4 KiB harness bound. + ## Filesystem Certification The backend-neutral helper in diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index b636557a0..0ad55a736 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -634,6 +634,36 @@ 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 since no banned shape and no part of the canary contains any of +those characters, every match it adds is a parser dropping punctuation out of +script text — an echo by definition. + +`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. It now matches the engine 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. Attribution +remains unable to relax it (`attribution_does_not_relax_the_stderr_cap`), and +that test is now sized off the constant so raising the cap cannot quietly turn +it into a no-op. Crash-unit replays for both 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 +703,25 @@ 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**: whole-execution stderr capped at + `MAX_STDERR_BYTES` (4 KiB, the largest `max_stderr_bytes` any fuzz + target configures), one bad input that produces 10 MB of + library-error spam trips this. The cap tracks that figure + deliberately: for a target that configured it, a tighter harness + number is unsatisfiable, because the engine may emit right up to the + limit it was given (run 45932089002, below); for the targets that + configure nothing it stays a harness-side flood bound. The bound on a + *single* diagnostic is a separate invariant (L-ARITH-002, + `MAX_ARITHMETIC_DIAG_ECHO`), still 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`, From d826d0088e416b3aea5a35bca4cef9c2336a3745 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Fri, 27 Nov 2026 09:42:59 +0000 Subject: [PATCH 2/6] test(js): wait on the server disconnect event instead of a fixed poll The windows-latest lane of JS run 45816668178 failed on "Ctrl+C aborts a held server connection via ctx.fetch: exit 130" at its `server saw the connection abort` assertion, taking the JS Check gate and main with it. Every other lane passed, and the seven preceding runs on main were green. The product path is not at fault: bash.cancel() aborts the builtin controller synchronously before it calls native.cancel(), and abort() dispatches to undici in the same tick, so the request is already aborted by the time execute() resolves -- which the test confirms independently via exit 130 and its elapsed bound. What remained was the kernel and the server's event loop noticing the socket go away, and the test gave that a fixed 2s of 20ms polling rounds on a single event, `req` 'close'. Neither the delay nor which event lands first is uniform across platforms, so the assertion was timing out on the slowest runner in the matrix rather than catching anything. The test now resolves a promise from `req` 'close'/'aborted' and the socket's 'close'/'error' and races it against one generous timeout. The usual case passes as soon as the event arrives instead of after a fixed wait, a slow delivery no longer reads as a failure, and a genuine failure to propagate still fails because the timeout resolves false. Recorded as a maintenance rule for the ava suite, which runs on windows-latest as well as ubuntu. --- .../__test__/custom-builtin-cancel.spec.ts | 35 +++++++++++++++---- knowledge/operations/testing.md | 10 ++++++ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts index c973e1e6d..35e754b7d 100644 --- a/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts +++ b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts @@ -150,12 +150,28 @@ test("a graceful return near the deadline leaves the builtin signal intact", asy test("Ctrl+C aborts a held server connection via ctx.fetch: exit 130", async (t) => { const http = await import("node:http"); - let serverAborted = false; + // Resolve on the first sign the client went away, rather than sampling a + // flag on a fixed schedule. `bash.cancel()` aborts the builtin controller + // synchronously before it calls `native.cancel()`, and `abort()` dispatches + // to undici in the same tick, so by the time `execute()` resolves the + // request is already aborted — what is left is the kernel and the server's + // event loop noticing, which is neither instant nor uniform across + // platforms. The old code polled `req` 'close' for a fixed 2s and called a + // slower delivery a failure: that is what reddened the windows-latest lane + // of JS run 45816668178 while every other lane passed. Waiting on an event + // makes the usual case immediate and the slow case tolerant, and watching + // the socket as well as the request drops the assumption that `req` 'close' + // is the event that lands first on every platform. + 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; - }); + 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()); @@ -179,9 +195,14 @@ test("Ctrl+C aborts a held server connection via ctx.fetch: exit 130", async (t) 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)); - } + let timer: ReturnType | undefined; + const serverAborted = await Promise.race([ + disconnected.then(() => true), + new Promise((resolve) => { + timer = setTimeout(() => resolve(false), 20000); + }), + ]); + if (timer !== undefined) clearTimeout(timer); t.true(serverAborted, "server saw the connection abort"); const next = await bash.execute("echo next:$MARKER"); t.is(next.exitCode, 0); diff --git a/knowledge/operations/testing.md b/knowledge/operations/testing.md index 2d507e145..b462e487e 100644 --- a/knowledge/operations/testing.md +++ b/knowledge/operations/testing.md @@ -830,3 +830,13 @@ 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 waits on something outside its own event loop — a socket + closing, a child exiting, the OS noticing an abort — waits on the event, + not on a fixed number of polling rounds. The ava suite runs on + `windows-latest` as well as ubuntu (the `Runtime callbacks` lane of + `js.yml`, which gates `JS Check`), and delivery there is slower and ordered + differently: JS run 45816668178 reddened main when a 2s poll for the + server-side `req` 'close' of an aborted `ctx.fetch` ran out on Windows + alone. Resolve a promise from every event that would signal the condition + and race it against one generous timeout, so the pass is immediate and only + a genuine failure to propagate fails From ab7a1dbb1be1d26f7a2d8734b9091189505b92fe Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Fri, 27 Nov 2026 10:17:15 +0000 Subject: [PATCH 3/6] fix(testing): keep the strict stderr cap at 1 KiB, separate from the fuzz one Review of the previous commit caught that raising the single shared MAX_STDERR_BYTES also moved assert_no_leak, the strict per-builtin path the threat model calls absolute, from 1 KiB to 4 KiB -- so a builtin emitting kilobytes of Debug spam would have passed a gate that previously failed it. Only the fuzz path needed the looser figure, because only a fuzz target inlines bytes it did not choose and runs under a limit it declared itself. The two budgets are now separate constants: MAX_STDERR_BYTES stays 1 KiB for assert_no_leak, and the new MAX_FUZZ_STDERR_BYTES is 4 KiB for assert_fuzz_invariants, with the const assertion moved onto it. loosening_the_fuzz_cap_did_not_loosen_the_strict_path pins the split and fails if they are ever collapsed back into one. Two documentation claims were also too strong, and are now qualified where they are made: - The guard does not make the cap satisfiable for every target. Eight of the 26 configure no limit and so take the 1 MiB default, 256x the harness figure, so for them 4 KiB is a deliberate flood bound rather than a satisfiable one and this class of false positive can recur. The fix when it does is an explicit max_stderr_bytes on that target, not a blind raise. - Stripping DROPPED_BY_PARSERS over-approximates: it is unconditional and context-free, while a real parser drops those characters only in particular positions, and attribution is whole-script and whole-stderr. So it can excuse an occurrence no parser would have produced. That is the same residual false negative script_explains already documents, accepted for the same reasons, and erring this direction is right -- under-approximating is what turns the nightly red on the detector's own dictionary. Fixed in passing on the same reporting path: truncate sliced arbitrary fuzz output at a fixed 512 bytes, panicking whenever that offset landed inside a multi-byte character and replacing a canary-leak message with an unrelated backtrace. It now floors the cut to a character boundary. --- crates/bashkit/src/testing.rs | 158 +++++++++++++----- .../arithmetic_fuzz_scaffold_tests.rs | 2 +- .../integration/diagnostic_prefix_tests.rs | 16 +- knowledge/log.md | 2 +- knowledge/security/security-testing.md | 29 ++-- knowledge/security/threat-model.md | 48 ++++-- 6 files changed, 176 insertions(+), 79 deletions(-) diff --git a/crates/bashkit/src/testing.rs b/crates/bashkit/src/testing.rs index 4afa0554b..1f898c699 100644 --- a/crates/bashkit/src/testing.rs +++ b/crates/bashkit/src/testing.rs @@ -59,44 +59,58 @@ pub const UNIVERSAL_BANNED: &[&str] = &[ "/.rustup/toolchains/", ]; -/// Cap on per-execution stderr length. A single bad input must not flood -/// stderr beyond this — catches "one bad regex generates 10 MB of -/// library error spam" regressions. -/// -/// This is a *whole-execution* budget, and a target that builds -/// `ExecutionLimits::max_stderr_bytes(N)` is declaring N bytes acceptable for -/// its scripts. The harness must therefore not sit below the largest N any -/// target configures: the engine truncates only at its own limit, so a tighter -/// harness cap rejects legitimately chatty-but-bounded output instead of -/// catching anything. Fifteen of the 26 fuzz targets configure 4096, three -/// configure 1024, and the rest take the 1 MiB default — so at 1024 this -/// assertion was guaranteed to fire somewhere in 1024..=4096. Fuzz Testing run -/// 45932089002 hit it on `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 of entirely -/// legitimate output. Matching the largest configured ceiling keeps the -/// original intent intact: for those targets the assertion now says "the -/// engine honored the stderr limit it was given", which is exactly the -/// 10-MB-spam regression it was written for, and for the targets that -/// configure nothing it stays the deliberate harness-side flood bound it -/// always was. +/// 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`; conflating the two is what -/// produced the false positive. -pub const MAX_STDERR_BYTES: usize = 4096; +/// `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_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. +/// 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_STDERR_BYTES >= FUZZ_TARGET_STDERR_LIMIT, - "MAX_STDERR_BYTES is tighter than the max_stderr_bytes the fuzz targets configure" + 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 @@ -354,11 +368,26 @@ const DROPPED_BY_PARSERS: &[char] = &['\0', '"', '\'', '\\']; /// a forgery the detector armed, not a host-env read. /// /// The `contains` guard keeps the allocation off the common path: this runs -/// once per pattern per fuzz iteration. Stripping can only *add* matches, so -/// it only ever widens attribution — and since no [`UNIVERSAL_BANNED`] shape -/// and no part of the canary contains any of these characters, every match it -/// adds is a parser dropping punctuation out of script text, which is an echo -/// by definition. +/// once per pattern per fuzz iteration. +/// +/// # This over-approximates, deliberately +/// +/// The strip is unconditional and context-free, while a real parser drops +/// these characters only in particular positions: a `"` inside single quotes +/// is data the shell keeps, `\` is removed 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 actually have undone. Combined with attribution being +/// whole-script and whole-stderr, that means 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`] documents, and +/// it is accepted for the same reasons: the miss is per-input rather than +/// per-bug, so the fuzzer reaches the same formatter through inputs that do +/// not carry the splice, and the static source scan plus the per-tool +/// [`assert_no_leak`] cases stay absolute. Erring toward over-approximation is +/// the right direction here — under-approximating turns the nightly red on the +/// detector's own dictionary, which is what runs 272, 304, 310 and 45932089002 +/// each did. fn carries_through_expansion(text: &str, needle: &str) -> bool { if text.contains(needle) { return true; @@ -614,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); @@ -648,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 @@ -907,10 +946,10 @@ mod tests { // into a no-op, the way the literal `repeat(200)` did. const SHAPE: &str = "Undefined::"; let result = ExecResult { - stderr: SHAPE.repeat(MAX_STDERR_BYTES / SHAPE.len() + 1).into(), + stderr: SHAPE.repeat(MAX_FUZZ_STDERR_BYTES / SHAPE.len() + 1).into(), ..Default::default() }; - assert!(result.stderr.len() > MAX_STDERR_BYTES); + assert!(result.stderr.len() > MAX_FUZZ_STDERR_BYTES); let err = std::panic::catch_unwind(|| { assert_fuzz_invariants(&result, "echo Undefined::", "cap_still_on", &[]); }) @@ -1176,14 +1215,45 @@ mod tests { ); } + #[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_engine_limit_is_still_a_flood() { - // The cap moved to match the engine ceiling; it did not go away. + 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/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 fbd9d31ae..722b1f2d5 100644 --- a/crates/bashkit/tests/integration/diagnostic_prefix_tests.rs +++ b/crates/bashkit/tests/integration/diagnostic_prefix_tests.rs @@ -240,15 +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` then held every builtin to. That harness -// cap has since moved to the engine's whole-execution ceiling, so the 1 KiB -// figure lives on here as the per-diagnostic bound it always meant. +// `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 -/// `bashkit::testing::MAX_STDERR_BYTES`, which is a whole-execution budget and -/// now tracks the engine's `max_stderr_bytes` ceiling instead. Conflating the -/// two is what made the fuzz harness reject legitimately chatty scripts; this -/// per-diagnostic figure is the one that must stay small. +/// 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 28471cf91..99d4b1a86 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,7 +2,7 @@ ## 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; `MAX_STDERR_BYTES` now tracks the engine 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). Note for the next cap change: `attribution_does_not_relax_the_stderr_cap` had hard-coded a 2,200-byte fixture and would have silently become a no-op, so it is now sized off the constant. 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). +* **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 diff --git a/knowledge/security/security-testing.md b/knowledge/security/security-testing.md index 8a0259262..a04644776 100644 --- a/knowledge/security/security-testing.md +++ b/knowledge/security/security-testing.md @@ -298,16 +298,25 @@ 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 two stderr budgets distinct. "Cap diagnostics at 1 KB" above is the -bound on a *single* diagnostic (L-ARITH-002). `MAX_STDERR_BYTES` is the -*whole-execution* budget and must track the largest -`ExecutionLimits::max_stderr_bytes` any target configures (4 KiB), because the -engine may emit right up to the limit it was given: a tighter harness figure -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. A target that configures a lower figure is -still held to it by the engine, and the eight targets that configure nothing -keep the 4 KiB harness bound. +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 diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 0ad55a736..0236565aa 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -656,12 +656,23 @@ cycles its format over every operand, so 34 non-numeric operands drew 34 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. It now matches the engine 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. Attribution -remains unable to relax it (`attribution_does_not_relax_the_stderr_cap`), and -that test is now sized off the constant so raising the cap cannot quietly turn -it into a no-op. Crash-unit replays for both live in +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 @@ -712,16 +723,21 @@ machinery (`bashkit::testing::assert_fuzz_invariants`): `/.cargo/registry/`, `target/{debug,release}/deps/`, `/.rustup/toolchains/` so leaked panic backtraces / build-artifact paths fail the assertion. -- **stderr flooding**: whole-execution stderr capped at - `MAX_STDERR_BYTES` (4 KiB, the largest `max_stderr_bytes` any fuzz - target configures), one bad input that produces 10 MB of - library-error spam trips this. The cap tracks that figure - deliberately: for a target that configured it, a tighter harness - number is unsatisfiable, because the engine may emit right up to the - limit it was given (run 45932089002, below); for the targets that - configure nothing it stays a harness-side flood bound. The bound on a - *single* diagnostic is a separate invariant (L-ARITH-002, - `MAX_ARITHMETIC_DIAG_ECHO`), still 1 KiB. +- **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`, From 4f2966d9713aee7075ef5d2145e84689890c3e38 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Fri, 27 Nov 2026 10:19:44 +0000 Subject: [PATCH 4/6] docs(threat-model): qualify the dropped-quote attribution claim The csv_fuzz paragraph still read 'an echo by definition', which overstates an unconditional context-free strip and contradicts the qualified wording the same change put on carries_through_expansion. State the over-approximation and the residual it shares with script_explains, as the code comment does. --- knowledge/security/threat-model.md | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 0236565aa..ae7101a9a 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -646,9 +646,21 @@ 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 since no banned shape and no part of the canary contains any of -those characters, every match it adds is a parser dropping punctuation out of -script text — an echo by definition. +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 From 070150dd83df02004d4bfe3868e4b29d319a4a3c Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Fri, 27 Nov 2026 10:37:38 +0000 Subject: [PATCH 5/6] fix(js): wait for the held request before cancelling it My previous commit on this test was wrong about the cause and did not fix it: `Runtime callbacks (windows-latest)` failed again on ab7a1db, same assertion, despite a 20s budget and four disconnect listeners. That ruled out slow delivery -- when it fails, the disconnect never arrives at all. The real cause is upstream of the disconnect. The test cancels an in-flight request, but it only assumed the request was in flight, after sleeping 200ms. `bash.execute` has to reach the native interpreter, dispatch the builtin and let undici open the connection within that window, 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: no request was ever sent, the server handler never ran, so no listener existed to report a disconnect and no later wait could help. The assertion was failing on a request that did not exist. Reproduced on Linux by cancelling before dispatch instead of sleeping, which gives the exact Windows signature -- exit 130, zero requests at the server, zero closes after the original 2s budget. So this needs no platform-specific explanation: Windows just loses the race more often, which is also why the two Windows lanes disagreed run to run while macos and ubuntu stayed green. The cancel now waits on `requestArrived` from the server handler, so it aborts something that exists, and that wait is bounded so a request that never arrives fails where the cause is visible. The elapsed bound is timed from the cancel rather than from `execute`, since it is about how fast cancellation unwinds and would otherwise fold in dispatch and connection setup on a slow runner. The event-based disconnect wait is kept and factored into `raceWithTimeout`. --- .../__test__/custom-builtin-cancel.spec.ts | 77 +++++++++++++------ knowledge/operations/testing.md | 23 +++--- 2 files changed, 69 insertions(+), 31 deletions(-) diff --git a/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts index 35e754b7d..a656a4dc2 100644 --- a/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts +++ b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts @@ -148,26 +148,58 @@ 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"); - // Resolve on the first sign the client went away, rather than sampling a - // flag on a fixed schedule. `bash.cancel()` aborts the builtin controller - // synchronously before it calls `native.cancel()`, and `abort()` dispatches - // to undici in the same tick, so by the time `execute()` resolves the - // request is already aborted — what is left is the kernel and the server's - // event loop noticing, which is neither instant nor uniform across - // platforms. The old code polled `req` 'close' for a fixed 2s and called a - // slower delivery a failure: that is what reddened the windows-latest lane - // of JS run 45816668178 while every other lane passed. Waiting on an event - // makes the usual case immediate and the slow case tolerant, and watching - // the socket as well as the request drops the assumption that `req` 'close' - // is the event that lands first on every platform. + // 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. + sawRequest(); req.on("close", sawDisconnect); req.on("aborted", sawDisconnect); req.socket.on("close", sawDisconnect); @@ -187,22 +219,23 @@ 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"); + // 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`); - let timer: ReturnType | undefined; - const serverAborted = await Promise.race([ - disconnected.then(() => true), - new Promise((resolve) => { - timer = setTimeout(() => resolve(false), 20000); - }), - ]); - if (timer !== undefined) clearTimeout(timer); + 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/knowledge/operations/testing.md b/knowledge/operations/testing.md index b462e487e..13c1bea4d 100644 --- a/knowledge/operations/testing.md +++ b/knowledge/operations/testing.md @@ -830,13 +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 waits on something outside its own event loop — a socket - closing, a child exiting, the OS noticing an abort — waits on the event, - not on a fixed number of polling rounds. The ava suite runs on +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 delivery there is slower and ordered - differently: JS run 45816668178 reddened main when a 2s poll for the - server-side `req` 'close' of an aborted `ctx.fetch` ran out on Windows - alone. Resolve a promise from every event that would signal the condition - and race it against one generous timeout, so the pass is immediate and only - a genuine failure to propagate fails + `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 From 136ced9dec5a0e5ed162aeb41c52ceab14c9b94f Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Fri, 27 Nov 2026 11:01:01 +0000 Subject: [PATCH 6/6] test(js): stop the cancel test when its request never arrives Review follow-up. A false `arrived` recorded the failure and then fell through into cancelling a request that was never sent, waiting out the full disconnect timeout and reporting a second failure that points away from the cause -- the opposite of what the arrival assertion's message promises. Return there instead; the server still closes via t.teardown and the finally block. The windows-latest lanes both passed on 070150d, including the execution-plan one that failed on ab7a1db, so the dispatch-race diagnosis holds. --- crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts index a656a4dc2..ba627f4bb 100644 --- a/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts +++ b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts @@ -226,6 +226,11 @@ test("Ctrl+C aborts a held server connection via ctx.fetch: exit 130", async (t) // 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.