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
18 changes: 18 additions & 0 deletions .changeset/fuzz-targets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
---

feat(fuzz): a cargo-fuzz target per untrusted-input parser

The rewrite's four hand-written parsers — the NIP-01 client frame, the REQ/COUNT filter, the
settings loader and the NIP-11 identity/document pair — take bytes from a socket or an
operator's file, and the existing suite only replays cases its author thought of. `fuzz/` is a
cargo-fuzz crate with its own nightly pin (`nightly-2026-08-21`) because cargo-fuzz emits
`-Zsanitizer` and the repository pin is a stable; it path-depends on `nostream-core`,
`nostream-config` and `nostream-relay` rather than copying a parser, so a campaign exercises the
crate that ships. Each of the four targets calls its parser on every input, asserts the
invariant named in its doc comment, and runs from committed seeds drawn from the crates' own
tests. `docs/rewrite/fuzz.md` is the runbook: install, environment, build and run commands, what
a 60 s smoke test does and does not reach, what a finding means, and the longer campaign that is
gated on #871's tauceti runbook and not started here. CI gains `fuzz/**` in the Rust path filter, a
format gate over the crate, and one `cd fuzz && cargo check`, so the crate cannot rot between
campaigns; no campaign runs in CI. Rust only: no published package changes, so this entry carries no version bump.
11 changes: 11 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ jobs:
- 'rust-toolchain.toml'
- 'resources/default-settings.yaml'
- 'scripts/rust.sh'
- 'fuzz/**'
- '.github/workflows/checks.yml'

commit-lint:
Expand Down Expand Up @@ -300,6 +301,16 @@ jobs:
run: cargo check -p nostream-storage --no-default-features --all-targets
- name: Release build
run: cargo build --workspace --all-features --release
# The fuzz crate is its own workspace, so none of the checks above see it — the job's own
# `cargo fmt --all --check` skips `fuzz/`, and naming its manifest is what brings it under
# the same pinned rustfmt.
- name: Fuzz crate formatting
run: cargo fmt --manifest-path fuzz/Cargo.toml --check
# `cargo check` picks up `fuzz/rust-toolchain.toml` (nightly, which cargo-fuzz's
# `-Zsanitizer` needs) and compiles only: no campaign runs here. A parser change that
# breaks the crate fails this step instead of surfacing at the next campaign.
- name: Fuzz crate compiles
run: cd fuzz && cargo check


kani-proofs:
Expand Down
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ coverage-report/
# Rust
/target/

# Fuzz build output, generated corpus and findings. The crate itself is committed:
# fuzz/Cargo.toml, fuzz/Cargo.lock, fuzz/rust-toolchain.toml and fuzz/seeds/**.
/fuzz/target/
/fuzz/corpus/
/fuzz/artifacts/

# A migration target is the dataset: `--target .` writes it here, and this repository is public.
/lmdb/
/migration-manifest.json
264 changes: 264 additions & 0 deletions docs/rewrite/fuzz.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
# Fuzzing the four untrusted-input parsers

`fuzz/` is a cargo-fuzz crate of its own that builds one libFuzzer target per parser this row
covers. It is a development tool: nothing in the daemon, the services or the test suite builds
it, and no campaign runs in CI. Two peer-reachable parsers are not covered yet —
`nip44::validate_payload` (from `strategies/gift_wrap.rs:82`) and
`expiration::get_event_expiration` (from `strategies/mod.rs:174`, and through
`handlers/event.rs:67`) — and #1293 tracks their targets; this row does not add them.

| target | parser | entry point |
|---|---|---|
| `client_frame` | NIP-01 client frame | `nostream_core::messages::decode` (`crates/nostream-core/src/messages.rs:383`) |
| `filter` | REQ/COUNT filter | `nostream_core::filter::validate_filter` (`crates/nostream-core/src/filter.rs:251`) |
| `settings` | settings loader | `nostream_config::load` (`crates/nostream-config/src/load.rs:390`) |
| `nip11` | NIP-11 identity and document | `nostream_relay::nip11::parse_relay_pubkey` and `nostream_relay::nip11::document` (`crates/nostream-relay/src/nip11.rs:198`, `:106`) |

The four are fed what their production callers hand them: `client_frame` a whole websocket text
frame, `filter` one JSON filter document — a single REQ element, not a frame, so a whole frame
is refused by the non-object arm — `settings` the bytes of an operator's settings file, and
`nip11` the string an operator writes into `info.pubkey`/`info.self` plus, from the same bytes,
a settings document for the `document` panic harness. Nothing here is a copy of a parser: each
target path-depends on the workspace crate that owns it (`fuzz/Cargo.toml`), so a change under
`crates/` is what a campaign exercises.

## Environment

Every `cargo fuzz` command on this host runs with the rustup proxies first on `PATH`, the
rustup home that holds the nightly, and no `CARGO_TARGET_DIR`:

```
export PATH=/home/node/.cargo/bin:$PATH
export RUSTUP_HOME=/home/node/.cargo/rustup
unset CARGO_TARGET_DIR
```

- `/home/node/.cargo/bin` holds the `cargo`/`rustc` proxies: they are what read the
`rust-toolchain.toml` of the directory a command starts in. Putting the pinned stable
toolchain's own `bin` directory first instead makes `cargo fuzz build` fail with "the option
`Z` is only accepted on the nightly compiler".
- `RUSTUP_HOME` must be exported. Unset, rustup resolves the profile home, which holds only the
repository pin, and reports that `nightly-2026-08-21` is not installed.
- `CARGO_TARGET_DIR` must be unset. With it set, the target executables land under
`$CARGO_TARGET_DIR/x86_64-unknown-linux-gnu/release/` instead of `fuzz/target`, and the paths
below are wrong.

`cargo install` puts `cargo-fuzz` in `$CARGO_HOME/bin` (`~/.cargo/bin` by default), which has to
be on `PATH` as well.

## Install the tool

Once per machine:

```
cargo install cargo-fuzz --version 0.13.2 --locked
```

The tool is cargo-fuzz 0.13.2, the version these runs were taken with; `cargo fuzz --version`
prints it. Recon could not install it and the red team's probes ran a throwaway copy, so the
campaigns recorded in the job's `build.md` are the tool's first real use in this repository.

## Why every command runs from `fuzz/`, and never names a version

`cd fuzz` first, always. rustup resolves a toolchain pin from the working directory, so
`fuzz/rust-toolchain.toml` is what selects the nightly, and a command started at the repository
root never sees it.

The crate carries its own pin because cargo-fuzz always emits `-Zsanitizer=address`, and the
repository pin (`rust-toolchain.toml` → `1.99.1`) is a stable rustc that rejects `-Z` and has
no `-Csanitizer` at all. The channel is `nightly-2026-08-21`; it is named here once, in
`fuzz/rust-toolchain.toml`. No command passes a toolchain name or `+toolchain` — the
repository's rule is that the pin file is the one place a toolchain moves.

## Seeds

`fuzz/seeds/<target>/` holds the hand-written inputs each target starts from, and each is a
case the crate's own tests already use (the target's doc comment names the invariant). The
generated corpus is not committed: `fuzz/corpus/` is ignored, and the runbook's commands copy
the seeds into it, one directory per target:

```
cd fuzz
for t in client_frame filter settings nip11; do
mkdir -p corpus/$t
cp -n seeds/$t/* corpus/$t/
done
```

`fuzz/Cargo.toml`, `fuzz/Cargo.lock`, `fuzz/rust-toolchain.toml` and `fuzz/seeds/**` are
committed; `fuzz/target/`, `fuzz/corpus/` and `fuzz/artifacts/` are ignored.

## Build

From `fuzz/`, with the environment above:

```
cargo fuzz build client_frame
cargo fuzz build filter
cargo fuzz build settings
cargo fuzz build nip11
```

`cargo fuzz list` prints exactly those four names. The binaries land under
`fuzz/target/x86_64-unknown-linux-gnu/release/`. A cold build compiles the whole dependency
graph — 2 m 01 s for `client_frame` on this host — and each later target links in seconds.

### The lock

`fuzz/Cargo.lock` is a second resolution of the same crates: 228 packages against the
workspace's 335, with newer patches on roughly sixty shared crates. Refresh it in the same
change that moves the root `Cargo.lock`, so a campaign's finding speaks about the graph the
relay ships rather than the one this crate happens to resolve.

## Run a short campaign

From `fuzz/`, after the seeds are copied:

```
cargo fuzz run client_frame corpus/client_frame -- -max_total_time=60 -max_len=524288 -timeout=10 -rss_limit_mb=2048 -print_final_stats=1
cargo fuzz run filter corpus/filter -- -max_total_time=60 -max_len=524288 -timeout=10 -rss_limit_mb=2048 -print_final_stats=1
cargo fuzz run settings corpus/settings -- -max_total_time=60 -max_len=524288 -timeout=10 -rss_limit_mb=2048 -print_final_stats=1
cargo fuzz run nip11 corpus/nip11 -- -max_total_time=60 -max_len=524288 -timeout=10 -rss_limit_mb=2048 -print_final_stats=1
```

The flags are the bounds, enforced by libFuzzer rather than by a timer in the harness:

- `-max_len=524288` is the payload bound the shipped configuration sets:
`resources/default-settings.yaml:212` ships `network.maxPayloadSize: 524288`, and
`nostream_relay::transport::max_payload_size` returns it
(`crates/nostream-relay/src/transport.rs:50-56`). The bound is configured, not constant:
`DEFAULT_MAX_PAYLOAD` = 131 072 applies only when that key is absent (`transport.rs:28`),
which is why a command copied from the constant — `-max_len=131072` — fuzzed a quarter of
the range the shipped file admits. Raising `maxPayloadSize` must move this flag with it;
- `-timeout=10` and `-rss_limit_mb=2048` turn a hang or an unbounded allocation into a finding
instead of a run that is merely slow. Both are coupled to the payload bound: at
`-max_len=524288` the measured peak RSS was `settings` 495 MB, `nip11` 405 MB, `filter` 86 MB
and `client_frame` 49 MB, so raising `network.maxPayloadSize` must raise `-rss_limit_mb` and
`-timeout` with it.

A clean run exits 0, prints a `Done <N> runs in <S> second(s)` line and leaves an empty
`fuzz/artifacts/<target>/`. A finding is a **file** in that directory, not the directory
itself: `cargo fuzz run` creates the empty directory on a clean run.

### What 60 s is, and is not

It is a smoke test: every committed seed is executed, then the mutator explores for a minute.
It is not a campaign. libFuzzer grows its input length limit from the seeds, so a 60 s run
reaches a few KiB of input — measured 87 to 4190 across the four targets — nowhere near the
configured 512 KiB `-max_len` bound. The flag bounds the run; the smoke test does not approach
it.

The `INITED cov:`/`ft:` figures on the first line are recorded for trend, not as a guard: a
stub body (`let _ = data.len();`) already measures `INITED cov: 14`, so a figure above zero
proves nothing on its own. What proves the parser is reached is the target body itself (the
job's criteria grep for the call), and a figure near the stub baseline is the signal that the
call was optimised away or gated off.

### A wide pass, when the size bound matters

The short campaign never approaches `-max_len`: libFuzzer's length controller grows inputs a
little at a time from the seeds' size, which is why the runs above ended with `lim` under 4 KiB
while the bound is 512 KiB. Inputs near the bound are exercised only with the controller off:
`-len_control=0` lets the mutator jump straight for `-max_len`-sized inputs instead of crawling
up to them.

```
cargo fuzz run client_frame corpus/client_frame -- -max_total_time=60 -max_len=524288 -len_control=0 -timeout=10 -rss_limit_mb=2048 -print_final_stats=1
cargo fuzz run filter corpus/filter -- -max_total_time=60 -max_len=524288 -len_control=0 -timeout=10 -rss_limit_mb=2048 -print_final_stats=1
cargo fuzz run settings corpus/settings -- -max_total_time=60 -max_len=524288 -len_control=0 -timeout=10 -rss_limit_mb=2048 -print_final_stats=1
cargo fuzz run nip11 corpus/nip11 -- -max_total_time=60 -max_len=524288 -len_control=0 -timeout=10 -rss_limit_mb=2048 -print_final_stats=1
```

Every target reached `lim: 524288` within the minute on this host: `client_frame` 1 549 209
runs, `filter` 2 053 925, `settings` 7 210, `nip11` 24 538; no artifacts, and libFuzzer printed
`slowest_unit_time_sec: 0` for all four. The cost is the parser's: `settings` and `nip11` parse
a document of up to the bound on every execution, so they complete thousands of runs where the
frame targets do millions, and the peak-RSS coupling above is unchanged: memory scales with the
bound. All four are worth running — none is slow enough to be left out — but a wide pass is
still a smoke test of the size range, not an exploration of it; exhaustive work at 512 KiB
belongs to the gated long campaign.

## What a finding means

An artifact file under `fuzz/artifacts/<target>/` is a crashing or hanging input. It is never
committed. Either the parser is fixed in the same change with the input added as a regression
case (and then the artifact becomes part of the explanation in the PR), or the input's bytes,
its sha256 and the issue filed for it are recorded and the artifact attached to that issue.

A finding above the configured payload bound (`network.maxPayloadSize`, 512 KiB in the shipped
file) is not production-reachable: the transport refuses a larger frame before any parser sees
it. It is still a bug worth fixing, but it cannot be a denial of service against the relay.

`settings` and `nip11` feed documents of up to the 512 KiB bound to `serde_yaml`, which parses
through `unsafe-libyaml` (RUSTSEC-2024-0449: unmaintained, no upstream fix, already in the root
lock). A finding inside that stack cannot be patched by a version bump, so the remedy may have
to be a bound in our caller — a size or nesting-depth pre-check before the document reaches the
parser.

## The longer campaign (written, not run)

The 24-hour campaign is deliberately not started here: this sandbox has no spare cores for it,
and the host that does — `tauceti` — is the subject of #871's runbook, which has not been
agreed with its owner. The gate is that runbook and the operator's word, in that order. Nothing
in this document starts it.

When the gate opens, the procedure is the short campaign with the budget raised and the corpus
kept: the same four commands, `-max_total_time` replaced by a wall-clock budget the host can
afford (start with `-max_total_time=86400`), run one target at a time, each in its own
`screen`/`systemd` unit, with `fuzz/artifacts` watched for files. The corpus directories
accumulate across runs, so copy them back into the tree only as `fuzz/seeds/` additions that a
review has seen; `fuzz/corpus/` stays ignored.

## CI: a format gate and a compile check

`rust-checks` runs two steps over the crate, after its existing checks:

```
cargo fmt --manifest-path fuzz/Cargo.toml --check
cd fuzz && cargo check
```

The crate is its own workspace, so the job's own `cargo fmt --all --check` cannot see it —
naming the manifest is what brings `fuzz/` under the same pinned rustfmt the workspace uses.
The second step compiles it under the crate's own pin. Neither runs a campaign: that costs
minutes per target and is nondeterministic, which is not what a PR gate is for. The steps exist
so the crate cannot rot between campaigns — a parser or dependency change that breaks it, or a
file that stops being formatted, fails the PR that made it instead of surfacing at the next
campaign.

The same change adds `fuzz/**` to the `rust` path filter, so a PR that touches only the fuzz
crate runs the Rust jobs (it previously ran none). The cost is stated: a `fuzz/**`-only PR now
triggers `rust-checks` and, because `kani-proofs` and `windows-cli-check` gate on the same
`rust` filter, both of those too; `rust-checks` installs `nightly-2026-08-21` on any run —
including PRs that change `crates/**`.

## The two premises this replaced

1. **The NIP-11 generator is not reachable from a socket.** `nostream_relay::nip11::document`
has one non-test caller, the MCP server's `status_payload`
(`crates/nostream-mcp/src/server.rs:1045`), and that server is served over stdio only
(`crates/nostreamd/src/mcp_stdio.rs:109`); the module's own docs say the HTTP surface is
shut. Its input is a typed `Settings`. So the fourth target is not a byte parser: it fuzzes
the one string the module parses — `info.pubkey`/`info.self` through `parse_relay_pubkey` —
and uses the same bytes as a settings document for a panic harness over `document`.
2. **`cargo fuzz build` cannot succeed on the repository's pinned toolchain.** cargo-fuzz emits
`-Zsanitizer`, the pin is a stable, and the stable rejects `-Z`. Hence the crate's own
`nightly-2026-08-21` pin, which changes nothing outside `fuzz/`.

## The four targets, one line each

- `client_frame`: `decode` never panics; an accepted REQ/COUNT carries a 1..=256-character
subscription id and 1..=10 filters.
- `filter`: `validate_filter` never panics; an accepted filter's `ids`/`authors` are 4..=64
lowercase-hex characters and its tag keys are `#` plus one ASCII letter; a refusal carries at
least one issue.
- `settings`: `load` returns `Ok` and never reports issues without having substituted the
defaults; a document the loader cannot parse, or one that is neither null nor a mapping, must
come back with `used_defaults = true` — the liveness check that a harness planting the file
where `load` does not read it cannot pass. The document is planted in a 0700 directory the
harness creates per execution and removes when the execution ends, so a killed campaign can
leave at most one such directory (and its input) in `TMPDIR`.
- `nip11`: `parse_relay_pubkey` accepts only 64 hex characters or an `npub1…` form (and the key
round-trips), refuses everything else, and errors only on a malformed `npub`; `document`
never panics or fails to serialise, and its advertised `min_pow_difficulty` lies within
`[floorBits, ceilingBits]` when adaptive proof-of-work is enabled.
Loading
Loading