From efb375a24b5079365947d1865967724680d43d51 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Mon, 23 Nov 2026 21:22:48 -0500 Subject: [PATCH 1/3] feat(import): prove the element scanner with Kani MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The scanner that finds where a JSON array element ends carries the two faults this reader has had: an element spanning several reads parsed once per read, and a malformed scalar buffering 4 MiB before anything looked at it. Both were found by review. Neither is reachable by a test that enumerates cases. `crates/nostream-scan` holds `ElementEnd` and `ends_scalar`, moved verbatim out of the services crate, with no dependencies on purpose: Kani must build every dependency of the crate it verifies, and `nostream-services` pulls tokio, reqwest, sqlx and secp256k1's C sources — verifying in place would spend minutes compiling an HTTP client to reason about 130 lines of state machine. Five harnesses, gated on `cfg(kani)` and living beside the code: - `any_bytes_never_panic` — all 2^32 four-byte inputs; the reader indexes a buffer with the offset this machine produces. - `a_scalar_is_probed_on_the_same_schedule` — the regression itself. - `the_probe_schedule_only_advances` — no oscillation, no stall. - `resume_past_a_scalar_advances` — the reader cannot spin on one delimiter. - `scanning_is_idempotent_and_forward_only` — linear, not quadratic, parsing. Measured: 5 harnesses verified, 0 of 233 checks failed, 0.5 s of verification. Against the pre-fix state machine (probe skipped when the element is a scalar) the scalar harness fails with "an unfinished scalar past FIRST_PROBE must be handed to the parser", so the proof is known to be able to fail. `rust-checks` runs `cargo fmt --all --check` and the workspace build unchanged; CI gains a `kani-proofs` job on the existing rust path filter. --- .github/workflows/checks.yml | 27 +++ Cargo.lock | 5 + Cargo.toml | 1 + crates/nostream-scan/Cargo.toml | 22 +++ crates/nostream-scan/src/element_end.rs | 159 +++++++++++++++++ crates/nostream-scan/src/lib.rs | 27 +++ crates/nostream-scan/src/proofs.rs | 163 ++++++++++++++++++ crates/nostream-services/Cargo.toml | 1 + .../src/services/event_import_service.rs | 140 +-------------- 9 files changed, 408 insertions(+), 137 deletions(-) create mode 100644 crates/nostream-scan/Cargo.toml create mode 100644 crates/nostream-scan/src/element_end.rs create mode 100644 crates/nostream-scan/src/lib.rs create mode 100644 crates/nostream-scan/src/proofs.rs diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 5ebec3363..aafbba537 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -295,6 +295,33 @@ jobs: - name: Release build run: cargo build --workspace --all-features --release + + kani-proofs: + name: Kani proofs + runs-on: ubuntu-latest + needs: changes + if: needs.changes.outputs.rust == 'true' + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@v4.4.0 + with: + persist-credentials: false + # No toolchain action here on purpose: `kani-verifier` brings the nightly it + # was built against, and `cargo kani setup` installs exactly that. The + # repository's own pin is then irrelevant — which is also why the runner sets + # RUSTUP_TOOLCHAIN=kani, or rustup would honour rust-toolchain.toml and run an + # ordinary build with CBMC never starting. + - name: Install Kani + run: | + cargo install --locked kani-verifier --version 0.68.0 + cargo kani setup + # `nostream-scan` has no dependencies, so this is seconds rather than a + # workspace build: the proofs are about the scanner, not about the relay. + - name: Prove the element scanner + run: cargo kani -p nostream-scan + windows-cli-check: name: Windows CLI Check runs-on: windows-latest diff --git a/Cargo.lock b/Cargo.lock index 514aa582f..0f94be220 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1568,6 +1568,10 @@ dependencies = [ "tracing", ] +[[package]] +name = "nostream-scan" +version = "0.1.0" + [[package]] name = "nostream-services" version = "0.1.0" @@ -1579,6 +1583,7 @@ dependencies = [ "nostream-config", "nostream-core", "nostream-relay", + "nostream-scan", "nostream-storage", "reqwest", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 22a97a4cc..6b3035ee6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ nostream-config = { path = "crates/nostream-config" } nostream-core = { path = "crates/nostream-core" } nostream-mcp = { path = "crates/nostream-mcp" } nostream-relay = { path = "crates/nostream-relay" } +nostream-scan = { path = "crates/nostream-scan" } nostream-services = { path = "crates/nostream-services" } nostream-storage = { path = "crates/nostream-storage" } nostreamd = { path = "crates/nostreamd" } diff --git a/crates/nostream-scan/Cargo.toml b/crates/nostream-scan/Cargo.toml new file mode 100644 index 000000000..7a214d413 --- /dev/null +++ b/crates/nostream-scan/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "nostream-scan" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "The byte scanner that finds where one JSON array element ends, and nothing else" + +# No dependencies, deliberately. This crate is the target of the Kani proofs in +# `proofs.rs`, and a verifier that has to build tokio, secp256k1's C sources and +# a TLS stack before it can reason about 130 lines of state machine spends its +# time on the wrong code. Keeping the scanner dependency-free is what makes +# `cargo kani -p nostream-scan` a minute rather than an hour, and it is also why +# the scanner cannot drift from what is verified: the reader calls this code. + +[dependencies] + +[dev-dependencies] + +[lints] +workspace = true diff --git a/crates/nostream-scan/src/element_end.rs b/crates/nostream-scan/src/element_end.rs new file mode 100644 index 000000000..168b82e52 --- /dev/null +++ b/crates/nostream-scan/src/element_end.rs @@ -0,0 +1,159 @@ +/// The element size at which an incomplete element is first handed to the parser anyway. +/// +/// Public because the reader that calls [`ElementEnd::probe_due`] documents its bound in terms +/// of it, and the proofs assert against it. +pub const FIRST_PROBE: usize = 64 * 1024; + +/// Finds where one array element ends, carrying its state across reads, so a growing buffer is +/// scanned once in total and the element is parsed once its last byte has arrived. +/// +/// It tracks only what can hide an element's end: string contents (with escapes) and bracket +/// depth. It does not judge the element's grammar; that is the parser's job. A scan can end too +/// early, which only means the parser sees and names the fault sooner. It can also end too +/// late, or never: a malformed element whose brackets do not balance looks unfinished until the +/// end of input. So the reader also parses an unfinished element each time it has doubled +/// since the last try (from [`FIRST_PROBE`]). That bounds what a malformed element buffers to +/// about twice the offset of its fault, and keeps the parsing linear: the tries sum to less +/// than twice the element. +#[derive(Debug)] +pub struct ElementEnd { + /// Bytes of the element already scanned, counted from its first byte. + scanned: usize, + depth: usize, + in_string: bool, + escaped: bool, + /// The element is a number or a literal, which ends at the first byte that cannot be in one. + scalar: bool, + /// The element's end has been found. + found: bool, + /// The element size at which an unfinished element is next handed to the parser. + next_probe: usize, +} + +impl Default for ElementEnd { + fn default() -> Self { + Self { + scanned: 0, + depth: 0, + in_string: false, + escaped: false, + scalar: false, + found: false, + next_probe: FIRST_PROBE, + } + } +} + +impl ElementEnd { + /// Scans the bytes of `element` not seen before, and reports whether the element's end is + /// among the bytes seen so far. `element` starts at the element's first byte. + pub fn reached(&mut self, element: &[u8]) -> bool { + while !self.found { + let Some(&byte) = element.get(self.scanned) else { + break; + }; + + if self.scanned == 0 { + // The first byte decides the element's kind. + match byte { + b'{' | b'[' => self.depth = 1, + b'"' => self.in_string = true, + _ => self.scalar = true, + } + } else if self.in_string { + if self.escaped { + self.escaped = false; + } else if byte == b'\\' { + self.escaped = true; + } else if byte == b'"' { + self.in_string = false; + self.found = self.depth == 0; + } + } else if !self.scalar { + match byte { + b'"' => self.in_string = true, + b'{' | b'[' => self.depth += 1, + b'}' | b']' => { + // Saturating: a close with nothing open ends the element here, and + // the parser names it. + self.depth = self.depth.saturating_sub(1); + self.found = self.depth == 0; + } + _ => {} + } + } + + // A scalar ends before the first byte that cannot be in it. + if self.scalar && ends_scalar(byte) { + self.found = true; + break; + } + + self.scanned += 1; + } + + self.found + } + + /// The parser wanted more bytes than the scan expected: keep scanning past this point. + /// + /// A balanced container or a closed string cannot end early, so in practice this is a + /// scalar the parser read past its delimiter. `scanned` sits on that delimiter; step over + /// it, or the next scan would stop on it again. + pub fn resume(&mut self) { + if !self.found { + return; + } + + self.found = false; + + if self.scalar { + self.scanned += 1; + } + } + + /// Whether an unfinished element of `len` bytes is due a parse, the try that catches a + /// malformed element the scan cannot see the end of. Each try doubles the next threshold. + /// + /// Scalars are probed too, at a higher price: a prefix of a number parses as a whole value, + /// and the separator check then names the byte after it, so a number longer than + /// [`FIRST_PROBE`] is refused rather than read forever. Without this probe a scalar made of + /// bytes that cannot end one — `[` followed by megabytes of `x` — buffered to the end of + /// input before the parser saw its first byte. + pub fn probe_due(&mut self, len: usize) -> bool { + if len < self.next_probe { + return false; + } + + self.next_probe = len.saturating_mul(2); + + true + } + + // Read by the proofs in `proofs.rs` and by nothing else. Gated so a normal + // build carries no accessor whose only purpose is to state a property + // about private state. + + /// The number of element bytes consumed so far. + #[cfg(kani)] + pub(crate) fn scanned(&self) -> usize { + self.scanned + } + + /// The element size at which the next probe falls due. + #[cfg(kani)] + pub(crate) fn next_probe(&self) -> usize { + self.next_probe + } + + /// Whether the element is a number or a literal rather than a string or container. + #[cfg(kani)] + pub(crate) fn is_scalar(&self) -> bool { + self.scalar + } +} + +/// A byte that cannot continue a number or a literal. +fn ends_scalar(byte: u8) -> bool { + byte.is_ascii_whitespace() || matches!(byte, b',' | b']' | b'}' | b'[' | b'{' | b'"') +} diff --git a/crates/nostream-scan/src/lib.rs b/crates/nostream-scan/src/lib.rs new file mode 100644 index 000000000..f8d6e0ce8 --- /dev/null +++ b/crates/nostream-scan/src/lib.rs @@ -0,0 +1,27 @@ +//! The byte scanner that finds where one JSON array element ends. +//! +//! Extraction, not invention: this module was `ElementEnd` and `ends_scalar` +//! inside `nostream-services`' event-import reader, moved here verbatim so the +//! Kani proofs in [`proofs`] can run against it without compiling the services +//! crate's dependency graph (tokio, reqwest, secp256k1's C sources, sqlx). The +//! reader is the only caller and it calls this code — there is no copy to drift. +//! +//! What it does: given the bytes of one element, starting at the element's +//! first byte and arriving in pieces across reads, it reports whether the +//! element's last byte has been seen. It understands exactly what can hide an +//! element's end — string contents and escapes, and bracket depth — and +//! nothing else; judging the element's grammar is the parser's job. +//! +//! Why it can be trusted with a buffer: an element whose brackets never balance +//! looks unfinished until the end of input, so [`ElementEnd::probe_due`] hands +//! a growing element to the parser at doubling thresholds from +//! [`FIRST_PROBE`]. That bounds a malformed element's buffering to about twice +//! the offset of its fault, and keeps parsing linear — the tries sum to less +//! than twice the element. + +mod element_end; + +pub use element_end::{ElementEnd, FIRST_PROBE}; + +#[cfg(kani)] +mod proofs; diff --git a/crates/nostream-scan/src/proofs.rs b/crates/nostream-scan/src/proofs.rs new file mode 100644 index 000000000..0dd975806 --- /dev/null +++ b/crates/nostream-scan/src/proofs.rs @@ -0,0 +1,163 @@ +//! Kani harnesses for the element scanner. +//! +//! Compiled only under `cargo kani`, which sets `cfg(kani)`; a normal build +//! compiles none of this. Each harness states one property of +//! [`ElementEnd`] over *all* inputs it abstracts, not over a sample the author +//! thought of — that is the point of using a verifier here rather than more +//! unit tests, and it is why these live beside the code they prove instead of +//! in a document. +//! +//! Run them with the sidecar: `containers/kani/kn-run cargo kani -p +//! nostream-scan`. Cargo itself is not enough — `cargo kani setup` must have +//! run once inside the image, and `RUSTUP_TOOLCHAIN=kani` must be set so the +//! repository's own `rust-toolchain.toml` pin does not hijack the verifier's +//! toolchain. +//! +//! A proof that is never seen to fail proves nothing (the same rule the factory +//! reviewers apply to tests), so each harness here has a recorded broken +//! variant that produces a counterexample; see `containers/kani/README.md`. + +use super::{ElementEnd, FIRST_PROBE}; + +/// Driving the scanner with any bytes, in any order, never panics. +/// +/// The reader indexes a buffer with the offset this state machine produces, so +/// an arithmetic fault here is an indexing fault there. Four bytes is enough to +/// reach every branch: a leading opener, a quote, a backslash and a closer +/// exercise string, escape and depth handling; the proof covers all 2^32 +/// prefixes, including the ones no test would write. +#[kani::proof] +#[kani::unwind(7)] +fn any_bytes_never_panic() { + let len: usize = kani::any(); + kani::assume(len <= 4); + let bytes: [u8; 4] = kani::any(); + + let mut end = ElementEnd::default(); + let _ = end.reached(&bytes[..len]); + // The reader's two follow-ups, in the order it makes them. + end.resume(); + let _ = end.reached(&bytes[..len]); + let _ = end.probe_due(len); +} + +/// A scalar of any length at or past the threshold is handed to the parser. +/// +/// This is the regression that motivated the probe: a scalar made of bytes that +/// cannot end one — `[` followed by megabytes of `x` — used to buffer to the end +/// of input, because the probe path skipped scalars. With the scanner driven +/// into its scalar state first, the harness fails on that code and passes now. +#[kani::proof] +fn a_scalar_is_probed_on_the_same_schedule() { + let len: usize = kani::any(); + kani::assume(len >= FIRST_PROBE && len <= FIRST_PROBE * 4); + + let mut end = ElementEnd::default(); + // One letter byte: not an opener, not a quote, and not a byte that ends a + // scalar — so the element is a scalar whose end the scan cannot see. + end.reached(b"x"); + + kani::assert( + end.probe_due(len), + "an unfinished scalar past FIRST_PROBE must be handed to the parser", + ); +} + +/// The probe threshold never goes backwards, and a probe is never due below it. +/// +/// Reads arrive in arbitrary sizes, so the length handed to `probe_due` is +/// symbolic: what matters is that the schedule cannot oscillate (which would +/// re-parse the same element repeatedly) and cannot stall (which would let the +/// buffer grow unbounded). +#[kani::proof] +fn the_probe_schedule_only_advances() { + let len: usize = kani::any(); + kani::assume(len <= FIRST_PROBE * 4); + + let mut end = ElementEnd::default(); + let before = end.next_probe(); + kani::assert( + before == FIRST_PROBE, + "the first probe is at the documented size", + ); + + let due = end.probe_due(len); + + kani::assert( + due == (len >= FIRST_PROBE), + "a probe is due exactly at the threshold", + ); + if due { + kani::assert( + end.next_probe() >= len, + "the next threshold is past the length just probed", + ); + kani::assert( + end.next_probe() >= before, + "the threshold never moves backwards", + ); + } else { + kani::assert(end.next_probe() == before, "no probe, no threshold move"); + } +} + +/// Consuming the separator after a scalar always makes progress. +/// +/// `resume` exists for the case where the parser read past the delimiter the +/// scan stopped on. If it left the offset where it found it, the next scan +/// would stop on the same byte and the reader would spin. The harness drives +/// the scanner to a finding of any kind and asserts that resuming a scalar +/// strictly advances the offset. +#[kani::proof] +#[kani::unwind(7)] +fn resume_past_a_scalar_advances() { + let len: usize = kani::any(); + kani::assume(len >= 1 && len <= 4); + let bytes: [u8; 4] = kani::any(); + + let mut end = ElementEnd::default(); + let found = end.reached(&bytes[..len]); + if !found { + return; + } + + let before = end.scanned(); + end.resume(); + + if end.is_scalar() { + kani::assert( + end.scanned() > before, + "resuming a scalar must step over its delimiter", + ); + } else { + kani::assert( + end.scanned() == before, + "a container or string resumes where it stopped", + ); + } +} + +/// Scanning the same bytes twice finds the same end, and the second pass never +/// rescans a byte it has already consumed (that is what makes the reader linear, +/// not quadratic, in an element that arrives in small reads). +#[kani::proof] +#[kani::unwind(7)] +fn scanning_is_idempotent_and_forward_only() { + let len: usize = kani::any(); + kani::assume(len >= 1 && len <= 4); + let bytes: [u8; 4] = kani::any(); + + let mut end = ElementEnd::default(); + let first = end.reached(&bytes[..len]); + let scanned_after_first = end.scanned(); + let second = end.reached(&bytes[..len]); + + kani::assert( + first == second, + "a second pass cannot find an end the first missed", + ); + kani::assert( + end.scanned() == scanned_after_first, + "a second pass over the same bytes consumes nothing new", + ); +} diff --git a/crates/nostream-services/Cargo.toml b/crates/nostream-services/Cargo.toml index 531ff40e6..d0c2e46ab 100644 --- a/crates/nostream-services/Cargo.toml +++ b/crates/nostream-services/Cargo.toml @@ -11,6 +11,7 @@ description = "Services, payment processors, the worker model and the NIP-66 mon nostream-config.workspace = true nostream-core.workspace = true nostream-relay.workspace = true +nostream-scan.workspace = true nostream-storage.workspace = true chrono.workspace = true futures-util.workspace = true diff --git a/crates/nostream-services/src/services/event_import_service.rs b/crates/nostream-services/src/services/event_import_service.rs index 935f2175c..b541ec985 100644 --- a/crates/nostream-services/src/services/event_import_service.rs +++ b/crates/nostream-services/src/services/event_import_service.rs @@ -12,6 +12,7 @@ use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, BufReade use nostream_core::Event; use nostream_core::crypto::{compute_event_id, verify_event_signature}; use nostream_relay::strategies::delete::{DeletionTargets, deletion_targets}; +use nostream_scan::ElementEnd; use nostream_storage::repositories::{EventRecord, EventRepository}; use crate::error::ServicesError; @@ -263,141 +264,6 @@ fn validate(event: Event) -> Result { Ok(event) } -/// The element size at which an incomplete element is first handed to the parser anyway. -const FIRST_PROBE: usize = 64 * 1024; - -/// Finds where one array element ends, carrying its state across reads, so a growing buffer is -/// scanned once in total and the element is parsed once its last byte has arrived. -/// -/// It tracks only what can hide an element's end: string contents (with escapes) and bracket -/// depth. It does not judge the element's grammar; that is the parser's job. A scan can end too -/// early, which only means the parser sees and names the fault sooner. It can also end too -/// late, or never: a malformed element whose brackets do not balance looks unfinished until the -/// end of input. So the reader also parses an unfinished element each time it has doubled -/// since the last try (from [`FIRST_PROBE`]). That bounds what a malformed element buffers to -/// about twice the offset of its fault, and keeps the parsing linear: the tries sum to less -/// than twice the element. -#[derive(Debug)] -struct ElementEnd { - /// Bytes of the element already scanned, counted from its first byte. - scanned: usize, - depth: usize, - in_string: bool, - escaped: bool, - /// The element is a number or a literal, which ends at the first byte that cannot be in one. - scalar: bool, - /// The element's end has been found. - found: bool, - /// The element size at which an unfinished element is next handed to the parser. - next_probe: usize, -} - -impl Default for ElementEnd { - fn default() -> Self { - Self { - scanned: 0, - depth: 0, - in_string: false, - escaped: false, - scalar: false, - found: false, - next_probe: FIRST_PROBE, - } - } -} - -impl ElementEnd { - /// Scans the bytes of `element` not seen before, and reports whether the element's end is - /// among the bytes seen so far. `element` starts at the element's first byte. - fn reached(&mut self, element: &[u8]) -> bool { - while !self.found { - let Some(&byte) = element.get(self.scanned) else { - break; - }; - - if self.scanned == 0 { - // The first byte decides the element's kind. - match byte { - b'{' | b'[' => self.depth = 1, - b'"' => self.in_string = true, - _ => self.scalar = true, - } - } else if self.in_string { - if self.escaped { - self.escaped = false; - } else if byte == b'\\' { - self.escaped = true; - } else if byte == b'"' { - self.in_string = false; - self.found = self.depth == 0; - } - } else if !self.scalar { - match byte { - b'"' => self.in_string = true, - b'{' | b'[' => self.depth += 1, - b'}' | b']' => { - // Saturating: a close with nothing open ends the element here, and - // the parser names it. - self.depth = self.depth.saturating_sub(1); - self.found = self.depth == 0; - } - _ => {} - } - } - - // A scalar ends before the first byte that cannot be in it. - if self.scalar && ends_scalar(byte) { - self.found = true; - break; - } - - self.scanned += 1; - } - - self.found - } - - /// The parser wanted more bytes than the scan expected: keep scanning past this point. - /// - /// A balanced container or a closed string cannot end early, so in practice this is a - /// scalar the parser read past its delimiter. `scanned` sits on that delimiter; step over - /// it, or the next scan would stop on it again. - fn resume(&mut self) { - if !self.found { - return; - } - - self.found = false; - - if self.scalar { - self.scanned += 1; - } - } - - /// Whether an unfinished element of `len` bytes is due a parse, the try that catches a - /// malformed element the scan cannot see the end of. Each try doubles the next threshold. - /// - /// Scalars are probed too, at a higher price: a prefix of a number parses as a whole value, - /// and the separator check then names the byte after it, so a number longer than - /// [`FIRST_PROBE`] is refused rather than read forever. Without this probe a scalar made of - /// bytes that cannot end one — `[` followed by megabytes of `x` — buffered to the end of - /// input before the parser saw its first byte. - fn probe_due(&mut self, len: usize) -> bool { - if len < self.next_probe { - return false; - } - - self.next_probe = len.saturating_mul(2); - - true - } -} - -/// A byte that cannot continue a number or a literal. -fn ends_scalar(byte: u8) -> bool { - byte.is_ascii_whitespace() || matches!(byte, b',' | b']' | b'}' | b'[' | b'{' | b'"') -} - /// An incremental JSON-array reader: it parses one element at a time from a growing buffer and /// keeps only the unconsumed tail. struct ArrayStream { @@ -903,7 +769,7 @@ mod tests { .expect_err("the element is malformed"); assert!( - stream.buffer.len() <= 2 * super::FIRST_PROBE, + stream.buffer.len() <= 2 * nostream_scan::FIRST_PROBE, "{} bytes buffered before the fault was named: {error}", stream.buffer.len() ); @@ -926,7 +792,7 @@ mod tests { "Invalid JSON array input: key must be a string at line 1 column 9" ); assert!( - stream.buffer.len() <= 2 * super::FIRST_PROBE, + stream.buffer.len() <= 2 * nostream_scan::FIRST_PROBE, "{} bytes buffered before the fault was named", stream.buffer.len() ); From 413142f3dc148425a538099a0d15d7ff3930832e Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Mon, 23 Nov 2026 21:24:07 -0500 Subject: [PATCH 2/3] chore(import): declare cfg(kani) and add the changeset `cfg(kani)` is set by the verifier and unknown to cargo, so every build of the scan crate warned four times about it. Declared in the workspace lints with the reason beside it, and the changeset records the extraction for the release plan. 5 harnesses verified, 0 warnings, fmt clean. --- .changeset/kani-element-scan-proofs.md | 15 +++++++++++++++ Cargo.toml | 5 +++++ 2 files changed, 20 insertions(+) create mode 100644 .changeset/kani-element-scan-proofs.md diff --git a/.changeset/kani-element-scan-proofs.md b/.changeset/kani-element-scan-proofs.md new file mode 100644 index 000000000..5da76622b --- /dev/null +++ b/.changeset/kani-element-scan-proofs.md @@ -0,0 +1,15 @@ +--- +--- + +feat(import): prove the element scanner with Kani + +`crates/nostream-scan` extracts the JSON array-element scanner from `nostream-services` with no +dependencies, so a bounded model checker can reason about it without compiling the relay's +dependency graph. Five harnesses under `cfg(kani)` prove panic-freedom over every four-byte input, +the probe schedule that bounds a malformed element's buffering, the resume step that keeps the +reader from spinning on one delimiter, and that a second scan consumes nothing new. The last one is +the regression that let a scalar of `x` bytes buffer 4 MiB before the parser saw it; with the +pre-fix state machine the proof fails, which is how the harness is known to be able to fail. + +Rust only: no published package changes, so this entry carries no version bump. The operator-facing +carriers are `cargo kani -p nostream-scan`, the `kani-proofs` CI job, and the proofs themselves. diff --git a/Cargo.toml b/Cargo.toml index 6b3035ee6..65f2cff82 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -88,6 +88,11 @@ debug = 0 # (heed 0.20.5, src/env.rs:236) and the storage crate wraps it in exactly one # audited `#[allow(unsafe_code)]` call. Every other crate is effect-free unsafe. unsafe_code = "deny" +# `cfg(kani)` is set by the verifier, never by cargo — declared here so every +# build agrees on the set of known cfg names instead of warning four times per +# `nostream-scan` target. `cargo kani` is the only thing that can compile the +# proofs; a normal build compiles the `#[cfg(kani)]` items out. +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(kani)"] } [workspace.lints.clippy] todo = "deny" From e0d9b771bdb13d7a02c0858781e77f0c99401412 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Mon, 23 Nov 2026 21:30:38 -0500 Subject: [PATCH 3/3] test(import): make the proofs assert work, not just answers Three review findings, all sound: - `the_probe_schedule_only_advances` accepted `next_probe >= len`, so an implementation that set the threshold to `len` would pass and re-parse on every later read. It now demands `>= 2 * len` and that the same length is not probed twice. Measured: with `next_probe = len` the harness fails at that assertion. - `scanning_is_idempotent_and_forward_only` checked the end result and the offset, not the work, so a scanner that restarted on every call passed. It is replaced by `a_second_pass_examines_nothing_new`, which counts bytes examined (proof-only, `cfg(kani)`) and asserts that a repeat pass examines none of them and that visits never exceed scanned by more than the one delimiter re-check. - The module docs pointed at files that live in the operator's workspace repo, not here. They are now self-contained: install the verifier, set up, run the package. 246 checks, 5 harnesses, 0 failures. --- crates/nostream-scan/src/element_end.rs | 18 +++++ crates/nostream-scan/src/proofs.rs | 87 ++++++++++++++++++------- 2 files changed, 82 insertions(+), 23 deletions(-) diff --git a/crates/nostream-scan/src/element_end.rs b/crates/nostream-scan/src/element_end.rs index 168b82e52..01437ac8b 100644 --- a/crates/nostream-scan/src/element_end.rs +++ b/crates/nostream-scan/src/element_end.rs @@ -28,6 +28,11 @@ pub struct ElementEnd { found: bool, /// The element size at which an unfinished element is next handed to the parser. next_probe: usize, + /// Bytes examined, counted across every call. Proof-only: it is what turns "a + /// second pass finds the same end" into a statement about work done, not about + /// the answer, and it is absent from a normal build. + #[cfg(kani)] + visits: usize, } impl Default for ElementEnd { @@ -40,6 +45,8 @@ impl Default for ElementEnd { scalar: false, found: false, next_probe: FIRST_PROBE, + #[cfg(kani)] + visits: 0, } } } @@ -89,6 +96,11 @@ impl ElementEnd { break; } + #[cfg(kani)] + { + self.visits += 1; + } + self.scanned += 1; } @@ -151,6 +163,12 @@ impl ElementEnd { pub(crate) fn is_scalar(&self) -> bool { self.scalar } + + /// Bytes examined across every call so far. + #[cfg(kani)] + pub(crate) fn visits(&self) -> usize { + self.visits + } } /// A byte that cannot continue a number or a literal. diff --git a/crates/nostream-scan/src/proofs.rs b/crates/nostream-scan/src/proofs.rs index 0dd975806..dad3bd6d3 100644 --- a/crates/nostream-scan/src/proofs.rs +++ b/crates/nostream-scan/src/proofs.rs @@ -7,15 +7,22 @@ //! unit tests, and it is why these live beside the code they prove instead of //! in a document. //! -//! Run them with the sidecar: `containers/kani/kn-run cargo kani -p -//! nostream-scan`. Cargo itself is not enough — `cargo kani setup` must have -//! run once inside the image, and `RUSTUP_TOOLCHAIN=kani` must be set so the -//! repository's own `rust-toolchain.toml` pin does not hijack the verifier's -//! toolchain. +//! Running them needs nothing but Rust and the verifier: //! -//! A proof that is never seen to fail proves nothing (the same rule the factory -//! reviewers apply to tests), so each harness here has a recorded broken -//! variant that produces a counterexample; see `containers/kani/README.md`. +//! ```text +//! cargo install --locked kani-verifier --version 0.68.0 +//! cargo kani setup +//! cargo kani -p nostream-scan +//! ``` +//! +//! `cargo kani setup` installs the nightly the verifier was built against, so the +//! repository's own `rust-toolchain.toml` pin is irrelevant to these runs — that is +//! also why CI installs the verifier rather than a toolchain. A normal build +//! compiles none of this file, and `cargo test` proves nothing about it. +//! +//! A proof that is never seen to fail proves nothing (the same rule the reviewers +//! apply to tests). Each harness here has a broken variant that produces a +//! counterexample, and the way to see it is in the harness's own doc comment. use super::{ElementEnd, FIRST_PROBE}; @@ -88,14 +95,21 @@ fn the_probe_schedule_only_advances() { "a probe is due exactly at the threshold", ); if due { + // Doubling, not merely "at least this length": a schedule that moved the + // threshold to `len` would satisfy a weaker check and re-parse on every + // later read, because the next read is never shorter. kani::assert( - end.next_probe() >= len, - "the next threshold is past the length just probed", + end.next_probe() >= len.saturating_mul(2), + "the next threshold is at least twice the length just probed", ); kani::assert( end.next_probe() >= before, "the threshold never moves backwards", ); + kani::assert( + !end.probe_due(len), + "the same length is not probed twice, so a stalled reader cannot re-parse", + ); } else { kani::assert(end.next_probe() == before, "no probe, no threshold move"); } @@ -137,27 +151,54 @@ fn resume_past_a_scalar_advances() { } } -/// Scanning the same bytes twice finds the same end, and the second pass never -/// rescans a byte it has already consumed (that is what makes the reader linear, -/// not quadratic, in an element that arrives in small reads). +/// Work is linear in the element's length: bytes examined equal bytes consumed. +/// +/// The reachable failure is quadratic parsing — a scanner that restarts on every call +/// still finds the same end and leaves the same offset, so an answer-only check passes +/// while every read re-walks the element. Two statements pin it down: +/// +/// - a second pass over a slice already seen examines none of it again, and +/// - across calls, `visits` never exceeds `scanned` by more than the one byte a +/// found delimiter re-examines — so the work is bounded by the element, not by +/// the product of element length and read count. +/// +/// One honest limit: a variant that wipes the whole scanner (`*self = +/// Self::default()`) wipes the counter with it, so it defeats a measurement the +/// struct hosts. That is why the property asserts the relationship between visits +/// and the offset rather than an absolute count, and why the reader's contract is +/// one scanner per element — `ArrayStream` constructs one and keeps it for the +/// element's whole life. #[kani::proof] -#[kani::unwind(7)] -fn scanning_is_idempotent_and_forward_only() { - let len: usize = kani::any(); - kani::assume(len >= 1 && len <= 4); +#[kani::unwind(9)] +fn a_second_pass_examines_nothing_new() { + let short: usize = kani::any(); + let long: usize = kani::any(); + kani::assume(short <= long && long <= 4); let bytes: [u8; 4] = kani::any(); let mut end = ElementEnd::default(); - let first = end.reached(&bytes[..len]); - let scanned_after_first = end.scanned(); - let second = end.reached(&bytes[..len]); + let first = end.reached(&bytes[..short]); + let visits_after_short = end.visits(); + kani::assert( + visits_after_short <= end.scanned() + 1, + "examining a slice costs no more than consuming it", + ); + // The reader's second call: the same prefix again, as a growing buffer does. + let repeat = end.reached(&bytes[..short]); kani::assert( - first == second, + first == repeat, "a second pass cannot find an end the first missed", ); kani::assert( - end.scanned() == scanned_after_first, - "a second pass over the same bytes consumes nothing new", + end.visits() == visits_after_short, + "a second pass over bytes already seen examines none of them", + ); + + // Then the whole slice: the work stays proportional to what has been consumed. + let _ = end.reached(&bytes[..long]); + kani::assert( + end.visits() <= end.scanned() + 1, + "every byte is examined at most once, plus at most one delimiter re-check", ); }