Skip to content
Open
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
204 changes: 204 additions & 0 deletions docs/FUZZING-PLAN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# Fuzzing Plan: Extending the existing `h3` cargo-fuzz setup

Worktree: `/home/franck-ws/projects/h3-wt-fuzz` (branch `feat/fuzz-qpack-frame`)
Goal: add QPACK field-section and HTTP/3 frame parsing fuzz targets to the repo's existing
`fuzz/` setup without recreating it.

## 1. Existing setup

The repo already ships a standalone cargo-fuzz crate under `fuzz/` (it declares its own
`[workspace] members = ["."]` so it is excluded from the main workspace). Files:

- `fuzz/Cargo.toml` — package `h3-fuzz`, deps `libfuzzer-sys = "0.4"` and `bytes = "1.5"`,
plus one `[[bin]]`:
```toml
[[bin]]
name = "fuzz_varint"
path = "fuzz_targets/fuzz_varint.rs"
test = false
doc = false
```
- `fuzz/fuzz_targets/fuzz_varint.rs` — `#![no_main]`, pulls the two small, self-contained
modules in via `#[path = "../../h3/src/..."]`:
```rust
#[path = "../../h3/src/proto/varint.rs"] mod varint;
#[path = "../../h3/src/proto/coding.rs"] mod coding;
fuzz_target!(|data: &[u8]| { let mut input = Bytes::from(data.to_vec()); let _ = VarInt::decode(&mut input); });
```
- `fuzz/corpus/fuzz_varint/` — tracked seed inputs.
- `fuzz/.gitignore` — ignores `target` and `artifacts`.

The `#[path]` include pattern is only practical for tiny leaf modules. The QPACK decoder and
the HTTP/3 frame parser depend on the whole `crate::proto::*` tree, the `http` crate and
`bytes`; inlining them via `#[path]` into a fuzz crate would break their internal
`crate::...` paths. So the new targets use a **path dependency on the `h3` crate** instead.

## 2. Public API to fuzz

The needed symbols are already `pub` but only reachable when the crate is built with the
existing feature
`i-implement-a-third-party-backend-and-opt-into-breaking-changes` (this feature just turns the
otherwise-private `proto`/`qpack`/`frame` modules public; no behavior change). We enable it via
the path dependency.

### QPACK field-section decoder
`h3/src/qpack/decoder.rs`:

- `pub fn decode_stateless<T: Buf>(buf: &mut T, max_size: u64) -> Result<Decoded, DecoderError>`
— stateless (no dynamic table). Rejects any dynamic-table reference with `MissingRefs(0)`,
exercises prefixed-integer parsing, Huffman decoding, static-index bounds and the
header-too-long limit.
- `pub fn decode_header<T: Buf>(&self, buf: &mut T) -> Result<Decoded, DecoderError>` on
`pub struct Decoder` — stateful path that resolves **dynamic-table indexes** (relative and
post-base), the required insert count / blocked-decode check (`MissingRefs`), prefixed ints
and Huffman. This is the path that covers dynamic-table out-of-bounds index resolution.

`Decoder` is currently declared `pub` but the `decoder` module is private, so `Decoder` is
**not reachable** outside the crate, and there is no public constructor (its
`From<DynamicTable>` impl is `#[cfg(test)]`). To fuzz `decode_header` we make two minimal
additions to the crate (documented, no behavior change):

1. Re-export `Decoder` from `h3/src/qpack/mod.rs` (alongside the already-exported
`decode_stateless`, `Decoded`, `DecoderError`).
2. Add `impl Default for Decoder` in `decoder.rs` that constructs a decoder backed by an empty
dynamic table (`DynamicTable::new()`). With an empty table any dynamic reference in the
input yields an out-of-bounds `DecoderError`, which is exactly the OOB coverage we want; the
corpus can also hold encoder-instruction bytes if we later want to seed a populated table.

### HTTP/3 frame parser
`h3/src/proto/frame.rs`:

- `pub fn decode<T: Buf>(buf: &mut T) -> Result<Self, FrameError>` on
`pub struct Frame<PayloadLen>`, exported as `h3::proto::frame::Frame`. Covers frame-type
validation, varint length overflow (`Incomplete`/`Malformed`), reserved/unknown frame types
(`UnknownFrame`), forbidden H2 frames (`UnsupportedFrame`), and per-frame payload parsing
(Settings, Goaway, CancelPush, MaxPushId, PushPromise).

The sequence-level `H3_FRAME_UNEXPECTED` rules (DATA-before-HEADERS, HEADERS-after-trailing-
HEADERS, GOAWAY-on-request-stream) are **stateful** checks implemented in the connection /
request-stream code (`h3/src/server/request.rs`, `h3/src/client/stream.rs`, etc.) and are not
pure byte->result functions; they are not directly fuzzable as a stateless `&[u8]` target.
`Frame::decode` is the pure byte-level frame parser and is the right fuzz surface. This is
documented as a limitation.

### QPACK encoder (optional)
`h3/src/qpack/encoder.rs`:

- `pub fn encode_stateless<W, T, H>(block: &mut W, fields: T) -> Result<u64, EncoderError>` where
`H: AsRef<HeaderField>` — encodes a field section from an iterator of `HeaderField`s. The
target synthesizes `HeaderField`s from arbitrary bytes, encodes, then round-trips the output
back through `decode_stateless` to check wire validity.

## 3. New targets

| Target file | Entry point fuzzed | Coverage |
|---|---|---|
| `fuzz/fuzz_targets/qpack_decode.rs` | `Decoder::decode_header` (first bytes fed to `on_encoder_recv` to populate/size the table; rest decoded as a field section) + `decode_stateless` | prefixed-int overflow, dynamic/static index OOB, Huffman, required insert count / blocked decode, header-too-long |
| `fuzz/fuzz_targets/frame_parse.rs` | `Frame::<PayloadLen>::decode` | frame-type validation, varint length overflow, reserved/forbidden/unknown types, per-frame payloads |
| `fuzz/fuzz_targets/qpack_encode.rs` | `encode_stateless` + round-trip `decode_stateless` | encoder wire output validity |

Each follows the `fuzz_varint` conventions: `#![no_main]` + `libfuzzer_sys::fuzz_target!`,
guaranteeing the target returns (an error or a valid value) and never panics/hangs.

## 4. Wiring in `fuzz/Cargo.toml`

Add the path dependency and three `[[bin]]` entries mirroring `fuzz_varint`:

```toml
[dependencies]
libfuzzer-sys = "0.4"
bytes = "1.5"
h3 = { path = "../h3", features = ["i-implement-a-third-party-backend-and-opt-into-breaking-changes"] }

[[bin]]
name = "qpack_decode"
path = "fuzz_targets/qpack_decode.rs"
test = false
doc = false

[[bin]]
name = "frame_parse"
path = "fuzz_targets/frame_parse.rs"
test = false
doc = false

[[bin]]
name = "qpack_encode"
path = "fuzz_targets/qpack_encode.rs"
test = false
doc = false
```

## 5. Seed corpora

Seeds are hand-crafted bytes placed under `fuzz/corpus/<target>/`:

### `fuzz/corpus/qpack_decode/`
- `static_get` — `:method: GET` static-index reference (valid static-section example).
- `dynamic_oob` — a field block whose post-base index references a dynamic entry on an
empty table → `BadPostbaseIndex`.
- `literal_dynamic_ref` — a literal-with-name-ref to a dynamic entry → `BadRelativeIndex`
(stateful) and `MissingRefs(0)` (stateless).
- `all_ones_overflow` — prefixed integer with all-ones continuation (integer-overflow probe).
- `huffman_invalid` — invalid/truncated Huffman sequence.
- `header_too_long` — many literal fields exceeding the size limit.
- `empty` — empty input.

### `fuzz/corpus/frame_parse/`
- `settings` — a valid SETTINGS frame.
- `empty_headers` — an empty HEADERS frame.
- `zero_data` — a zero-length DATA frame.
- `reserved_type` — reserved frame type `0x00`.
- `varint_overflow` — length field varint overflow.
- `forbidden_h2` — an H2 PRIORITY/PING frame (unsupported).
- `grease` — a grease / unknown frame type.
- `empty` — empty input.

### `fuzz/corpus/qpack_encode/`
- `simple_field` — a normal name/value pair (round-trips).
- `empty` — empty input (no fields).
- `large_value` — a large literal value (name-prefix bit-width path).

(Seed files are generated programmatically as documented in this report; the exact bytes are
listed there.)

## 6. CI integration

- GitHub Actions already runs cargo workflows in `.github/workflows/` (cargo-fuzz is not
currently wired). Proposed: a nightly-only job that uses `rustup` to install
`nightly-<version>` + `cargo-fuzz` and runs `cargo fuzz build` (or, if no corpus run is
wanted, at least `cargo fuzz check`/`cargo build`) for each target so the targets stay
compilable on every PR. Optionally a short bounded `cargo fuzz run <target> -- -runs=0`
smoke check that imports the seed corpus and runs a fixed number of executions to catch
panics. Note `libfuzzer-sys` requires nightly; the stable toolchain cannot build the fuzz
crate.
- Keep the fuzz crate standalone (its own `[workspace]`) so it does not slow down the main
workspace's stable builds.

## 7. Verification

Toolchain available on this machine: **stable only** (cargo 1.98.1, no nightly / no
`cargo-fuzz`), so `cargo fuzz run`/`build` cannot run here. Verification approach:

- `cargo check --features i-implement-a-third-party-backend-and-opt-into-breaking-changes`
in `h3/` to confirm the `Decoder` re-export and `Default` impl compile and the public API
surface the targets rely on exists.
- Attempt `cargo build` inside `fuzz/`; record what fails (expected: libfuzzer-sys needs
nightly / clang sanitizer).
- Confirm the fuzz-target Rust code type-checks against the public API by keeping the usage
minimal and mirroring the existing target's structure.

## 8. Files changed

- `h3/src/qpack/mod.rs` — re-export `Decoder`.
- `h3/src/qpack/decoder.rs` — add `impl Default for Decoder`.
- `fuzz/Cargo.toml` — add `h3` path dep + 3 `[[bin]]` entries.
- `fuzz/fuzz_targets/qpack_decode.rs` (new)
- `fuzz/fuzz_targets/frame_parse.rs` (new)
- `fuzz/fuzz_targets/qpack_encode.rs` (new)
- `fuzz/corpus/qpack_decode/*` (new seeds)
- `fuzz/corpus/frame_parse/*` (new seeds)
- `fuzz/corpus/qpack_encode/*` (new seeds)
- `docs/FUZZING-PLAN.md` (this file)
- `fuzz/.gitignore` — reviewed; existing `target`/`artifacts` entries already cover
fuzzer-generated artifacts (corpus seeds are intentionally kept tracked).
19 changes: 19 additions & 0 deletions fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"
bytes = "1.5"
h3 = { path = "../h3", features = ["i-implement-a-third-party-backend-and-opt-into-breaking-changes"] }

# Prevent this from interfering with workspaces
[workspace]
Expand All @@ -21,3 +22,21 @@ name = "fuzz_varint"
path = "fuzz_targets/fuzz_varint.rs"
test = false
doc = false

[[bin]]
name = "qpack_decode"
path = "fuzz_targets/qpack_decode.rs"
test = false
doc = false

[[bin]]
name = "frame_parse"
path = "fuzz_targets/frame_parse.rs"
test = false
doc = false

[[bin]]
name = "qpack_encode"
path = "fuzz_targets/qpack_encode.rs"
test = false
doc = false
Empty file added fuzz/corpus/frame_parse/empty
Empty file.
Binary file added fuzz/corpus/frame_parse/empty_headers
Binary file not shown.
Binary file added fuzz/corpus/frame_parse/forbidden_h2_priority
Binary file not shown.
Binary file added fuzz/corpus/frame_parse/grease
Binary file not shown.
Binary file added fuzz/corpus/frame_parse/reserved_type
Binary file not shown.
Binary file added fuzz/corpus/frame_parse/settings
Binary file not shown.
Binary file not shown.
1 change: 1 addition & 0 deletions fuzz/corpus/frame_parse/varint_overflow
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
���������
Binary file added fuzz/corpus/frame_parse/zero_data
Binary file not shown.
Binary file added fuzz/corpus/qpack_decode/all_ones_overflow
Binary file not shown.
Binary file added fuzz/corpus/qpack_decode/dynamic_oob
Binary file not shown.
Empty file added fuzz/corpus/qpack_decode/empty
Empty file.
Binary file added fuzz/corpus/qpack_decode/header_too_long
Binary file not shown.
Binary file added fuzz/corpus/qpack_decode/huffman_invalid
Binary file not shown.
Binary file added fuzz/corpus/qpack_decode/literal_dynamic_ref
Binary file not shown.
Binary file added fuzz/corpus/qpack_decode/static_get
Binary file not shown.
Empty file added fuzz/corpus/qpack_encode/empty
Empty file.
Empty file.
1 change: 1 addition & 0 deletions fuzz/corpus/qpack_encode/simple_field
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
4namevalue
35 changes: 35 additions & 0 deletions fuzz/fuzz_targets/frame_parse.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#![no_main]

use bytes::Buf;
use bytes::Bytes;
use h3::proto::frame::{Frame, PayloadLen};
use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
let mut buf = Bytes::from(data.to_vec());

// Decode a *stream* of frames: repeatedly parse a frame header + payload until the
// buffer is exhausted or a decode error is returned. This exercises varint / frame
// type / length parsing across frame boundaries and under arbitrary truncation,
// including a frame type 0x00 (reserved), a varint length that overflows u64, and a
// DATA/SETTINGS/HEADERS frame of arbitrary length.
//
// NOTE on scope: HTTP/3 frame *ordering* rules (DATA before HEADERS, HEADERS after a
// trailing HEADERS, GOAWAY on a request stream => H3_FRAME_UNEXPECTED, a SETTINGS
// frame in the wrong position, etc.) are enforced by the connection layer's stream
// state machine in h3/src/connection.rs, not by the frame codec. They require a QUIC
// connection to drive and are therefore NOT reachable from this isolated frame-codec
// fuzz target. That sequencing logic must be fuzzed or covered by tests separately.
while buf.has_remaining() {
let before = buf.remaining();
if Frame::<PayloadLen>::decode(&mut buf).is_err() {
// Exhausted / truncated / malformed: stop rather than spin on the same bytes.
break;
}
if buf.remaining() == before {
// Guard against a decode that returns Ok() without consuming input, which
// would otherwise loop forever.
break;
}
}
});
46 changes: 46 additions & 0 deletions fuzz/fuzz_targets/qpack_decode.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#![no_main]

use bytes::Bytes;
use libfuzzer_sys::fuzz_target;
use h3::qpack::{decode_stateless, Decoder};

// Arbitrary header-section size cap used by the stateless decoder.
const MAX_SIZE: u64 = 4096;

fuzz_target!(|data: &[u8]| {
// Path 1: stateful decoder. The first bytes are treated as QPACK *encoder-stream*
// instructions (table size updates / insertions), and the remainder as an encoded
// field section. This exercises:
// - dynamic-table insertion and size updates,
// - dynamic-table index resolution (relative & post-base) incl. out-of-bounds,
// - required insert count / blocked decoding (MissingRefs when the table cannot
// satisfy the required count),
// - prefixed-integer parsing (incl. overflow),
// - Huffman decoding (invalid/truncated sequences),
// - base-index handling.
let mut decoder = Decoder::default();
if data.is_empty() {
let mut block = Bytes::new();
let _ = decoder.decode_header(&mut block);
} else {
// data[0] is reserved purely as the split control byte, so the fuzzer can
// independently vary "how long the setup is" vs "what opcode it starts with".
// split ∈ [0, len-1]; data[1..] has len-1 bytes, so setup may be empty and the
// first encoder-instruction byte is data[1], decoupled from the split value.
let split = (data[0] as usize) % data.len();
let (setup, section) = data[1..].split_at(split);

let mut enc = Bytes::from(setup.to_vec());
let mut enc_out = Vec::new();
// Feed encoder-stream instructions; errors (e.g. unknown prefix) are fine.
let _ = decoder.on_encoder_recv(&mut enc, &mut enc_out);

let mut block = Bytes::from(section.to_vec());
let _ = decoder.decode_header(&mut block);
}

// Path 2: stateless decoder (no dynamic table). Exercises static-index bounds, Huffman,
// prefixed-integer parsing, and the header-too-long limit.
let mut buf = Bytes::from(data.to_vec());
let _ = decode_stateless(&mut buf, MAX_SIZE);
});
44 changes: 44 additions & 0 deletions fuzz/fuzz_targets/qpack_encode.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#![no_main]

use h3::qpack::{decode_stateless, encode_stateless, HeaderField};
use libfuzzer_sys::fuzz_target;

// Header-section size cap used when round-tripping the encoder output through the decoder.
const MAX_SIZE: u64 = 4096;

fuzz_target!(|data: &[u8]| {
if data.len() < 2 {
return;
}

// Split the arbitrary input into a field name and value. data[0] is reserved purely
// as the split point so the name/value bytes are decoupled from the control byte.
// mid ∈ [1, len], so the value may be empty (mid == len) and the name may be empty
// (mid == 1) — both are valid encoder inputs.
let mid = (data[0] as usize) % data.len() + 1;
let raw_name = &data[1..mid];
let raw_value = &data[mid..];

// Field names are lowercased by the QPACK/HTTP layer (RFC 9114 §4.2 rejects
// uppercase in field names). Encode a lowercase name so encode_stateless accepts it
// and the round-trip assertion below compares like-for-like instead of failing on a
// name that is legal to the encoder but illegal on the wire.
let mut name = raw_name.to_vec();
name.make_ascii_lowercase();
let field = HeaderField::new(name, raw_value.to_vec());

let mut out = Vec::new();
if encode_stateless(&mut out, [&field]).is_ok() {
// Round-trip the encoded field section through the decoder and ASSERT the output
// matches the input. This is what actually catches an encoder bug such as the
// historical name-prefix bit-width error (encoder emits a name/value of the wrong
// length) — a mismatch that would silently pass if the decode result were ignored.
let mut buf = std::io::Cursor::new(out);
match decode_stateless(&mut buf, MAX_SIZE) {
Ok(decoded) => {
assert_eq!(decoded.fields, vec![field], "encoder output did not round-trip")
}
Err(e) => panic!("encode_stateless produced undecodable bytes: {e:?}"),
}
}
});
8 changes: 8 additions & 0 deletions h3/src/qpack/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,14 @@ pub struct Decoder {
table: DynamicTable,
}

impl Default for Decoder {
fn default() -> Self {
Self {
table: DynamicTable::new(),
}
}
}

impl Decoder {
// Decode field lines received on Request of Push stream.
// https://www.rfc-editor.org/rfc/rfc9204.html#name-field-line-representations
Expand Down
5 changes: 5 additions & 0 deletions h3/src/qpack/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ pub use self::{
field::HeaderField,
};

// `Decoder` is used externally (e.g. by fuzz targets); only re-export it when the
// public-facing `proto`/`qpack` modules are exposed so default builds stay warning-free.
#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
pub use self::decoder::Decoder;

mod block;
mod dynamic;
mod field;
Expand Down