Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/kani-element-scan-proofs.md
Original file line number Diff line number Diff line change
@@ -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.
27 changes: 27 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down Expand Up @@ -87,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"
Expand Down
22 changes: 22 additions & 0 deletions crates/nostream-scan/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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
177 changes: 177 additions & 0 deletions crates/nostream-scan/src/element_end.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/// 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,
/// 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 {
fn default() -> Self {
Self {
scanned: 0,
depth: 0,
in_string: false,
escaped: false,
scalar: false,
found: false,
next_probe: FIRST_PROBE,
#[cfg(kani)]
visits: 0,
}
}
}

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;
}

#[cfg(kani)]
{
self.visits += 1;
}

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
}

/// 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.
fn ends_scalar(byte: u8) -> bool {
byte.is_ascii_whitespace() || matches!(byte, b',' | b']' | b'}' | b'[' | b'{' | b'"')
}
27 changes: 27 additions & 0 deletions crates/nostream-scan/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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;
Loading
Loading