Skip to content

refactor(mux-h2): extract the flood detector, and remove the module's last self-sampling clock - #1419

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-flood-detector
Sep 22, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/h2-flood-detector

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Step 4 of the H2 sans-io extraction. Steps 1-3 landed as #1403, #1406 and #1415.

H2FloodConfig, H2FloodViolation, H2FloodDetector and check_flood move out of h2.rs into
lib/src/protocol/mux/h2_flood_detector.rs, with the closed pub(super) API and
check_invariants() post-condition the three previous steps established. ConnectionH2.flood_detector
becomes private; the ~14 direct field accesses in h2.rs now go through named methods.

This detector implements CVE mitigations, so the arithmetic was verified mechanically

CVE-2023-44487, CVE-2024-27316 and CVE-2025-8671. A counter that stops counting or a threshold that
stops tripping is a security regression no functional test would notice, so "it compiles and the suite
is green" is not evidence here.

All 13 counters, all 13 H2FloodConfig thresholds, the .max(1) clamp, and the complete 10-clause
check_flood .or_else() chain — RST_STREAM, PING, PING lifetime, SETTINGS, SETTINGS lifetime, empty
DATA, CONTINUATION, WINDOW_UPDATE on stream 0, accumulated header size, glitch — were extracted from
both revisions and diffed: byte-for-byte identical, including every += versus .saturating_add
choice. All 14 call sites and handle_flood_violation's eleven lines likewise. A review re-ran that
comparison independently rather than re-reading the claim.

The only additions are #[cfg(debug_assertions)] ones: the check_invariants() sweep, and five
symmetric debug_assert!s on record_glitch that every sibling counter already had.

The last self-sampling clock in this module is gone

impl Default for H2FloodDetector called Instant::now() and was LIFECYCLE.md invariant 20's
documented exception. It was verified genuinely unreachable from production — ConnectionH2::new is
the sole constructor path, and every default() call site lived in #[cfg(test)] mod tests — so
rather than relocating the exception, it is removed. Each former call site now passes its own
sample explicitly.

test_flood_detector_default_matches_new_default is deleted rather than adapted: its only purpose was
comparing two constructors, and there is no longer a second one.

Re-running invariant 20's own verification command over h2.rs now returns exactly one production hit
— ConnectionH2::new's sanctioned sample — with every other match inside the test module.
h2_flood_detector.rs has none.

Determinism: none, and structurally so

The two previous steps each found a real leak, both times by reading rather than grepping, because
for (&k, &v) in &map is invisible to any grep for .iter()/.keys()/.values()/.drain().

This one has nothing to iterate. Every field was read: 13 scalar counters, one Instant, one Copy
config — no Vec, no HashMap, no HashSet, no BTreeMap. check_flood's .or_else() chain, which
decides which violation is reported when several trip at once, is a fixed sequence in the source text
rather than an iteration, so it cannot vary between runs.

That is a stronger result than "I looked and found none", and it is recorded in the module doc.

One CI-script change, and why it is not a weakened check

.github/scripts/check_doc_citations.py gains one NOT_A_TEST entry for
total_abusive_rst_received_lifetime.

A changeset that edits the check it must satisfy deserves suspicion, so this was verified rather than
asserted. The identifier is a pub(super) field and is never a fn anywhere in the tree. The
suppression is exact-string dictionary equality, not a regex or prefix, so it blinds the checker to
nothing else. Two entries of identical shape already existed before this changeset, and none of the
three prior extraction steps needed to touch this file.

The root cause is structural: prose_blocks() treats a Rust file's entire contiguous //! run as one
block, so a 112-line module header whose sub-paragraphs legitimately discuss tests makes an unrelated
field-name bullet read as a test citation.

A review deleted that one line, confirmed the gate fails for exactly that reason, and restored it.

A citation defect this changeset introduced, found in review and fixed

The first revision re-anchored roughly 120 citations. Eight of them, all in LIFECYCLE.md's clock
section, pointed at the enclosing function's signature rather than the self.now = context.now;
assignment the prose describes — 1 to 8 lines off. The previous citations had been exact, so this was a
precision regression, not inherited drift.

CI cannot catch this by design: rule 1 only proves a cited line is non-blank and in range, and a
signature six lines above the right statement satisfies that; the drift rule then exempts any
(path, spans) pair absent at the base, so every re-anchor is exempt by construction. A wrong
re-anchor passes every gate, permanently and silently.

All eight are corrected, each verified by printing the line:

h2.rs:1956                    self.now = context.now;
h2.rs:3312                    self.now = context.now;
h2.rs:3761                    self.now = context.now;
h2.rs:6194                    self.now = context.now;
h2_flood_detector.rs:433      window_start: Instant,
h2_flood_detector.rs:729      if now.saturating_duration_since(self.window_start) >= FLOOD_WINDOW_DURATION {

Two adjacent citations legitimately are about signatures — the prose is about check_flood and
maybe_reset_window taking now as a parameter — and stayed that way.

Worth recording: while adding the module-doc paragraph below, the fix reproduced its own bug class
— the inserted paragraph shifted six of the just-corrected citations by 13 lines, and rule 1 still
passed. It was caught by re-running the sweep before reporting done, not by CI.

An automated sweep over every single-line citation in LIFECYCLE.md and the touched doc/*.md now
confirms none lands on a signature outside those two legitimate cases. The commit message states
accurately which citations were verified by content-diff mapping and which paragraph was not.

A pre-existing gap this surfaced, documented but not fixed here

H2FloodConfig keeps public fields because lib/src/http.rs and lib/src/https.rs build it via a
raw struct literal from listener configuration. Every sibling module in this series made its fields
private — that is what turned a documented invariant into a compile error in #1415 — and this one does
not, deliberately, to avoid widening a relocation step into the listener code.

The consequence is that H2FloodConfig::new's .max(1) clamp has no production caller, so an
operator-set threshold reaches the detector unvalidated. Filed as #1418, with a sentence added to
the module doc so the next reader does not have to rediscover it.

Validation, both feature shapes

cargo +1.93.1 build --all-features --locked                       -> exit 0
cargo +1.93.1 build --locked                                      -> exit 0
cargo +1.93.1 clippy --all-targets --all-features -- -D warnings  -> exit 0
cargo +1.93.1 clippy --all-targets --locked -- -D warnings        -> exit 0
cargo +nightly fmt --all -- --check                               -> exit 0
cargo +1.93.1 test -p sozu-lib --locked protocol::mux             -> 368 passed, 0 failed, plus 24 new
python3 .github/scripts/check_doc_citations.py --base origin/main -> exit 0
python3 .github/scripts/check_doc_citations.py --self-test        -> exit 0

Refs #1336, #1339, #1418.

…ctor.rs

Move H2FloodConfig, H2FloodViolation, H2FloodDetector and check_flood into
lib/src/protocol/mux/h2_flood_detector.rs, behind the same closed-API shape
hpack_state.rs, h2_flow_control.rs and h2_stream_table.rs established in the
three prior extraction steps. ConnectionH2 keeps a single private
flood_detector: h2_flood_detector::H2FloodDetector field and now calls
record_glitch / record_continuation_frame / begin_header_block_if_new /
record_empty_data_frame / record_rst_stream_window / record_settings_frame /
record_ping_frame / record_window_update_stream0 / config /
accumulated_header_size / total_rst_received_lifetime /
total_rst_streams_emitted_lifetime instead of touching thirteen raw
counter/config fields directly at fourteen call sites across six frame
handlers. MAX_HEADER_LIST_SIZE stays declared in h2.rs (converter.rs and
pkawa.rs reference it directly as a general HPACK safety ceiling, independent
of any one connection's configured value) and is reached from the new module
via super::h2::MAX_HEADER_LIST_SIZE.

Every counter's increment operator (+= vs .saturating_add) moved verbatim per
field, and every check_flood threshold comparison is character-for-character
the same count > threshold check against the same field and H2FloodConfig
value - this is a pure relocation of the CVE-2023-44487 (Rapid Reset),
CVE-2024-27316 (CONTINUATION flood) and CVE-2025-8671 (MadeYouReset)
mitigations. record_glitch's five call sites gain a symmetric before/after
debug_assert they previously lacked, matching every sibling counter; this is
debug-only and cannot change release behaviour.

H2FloodDetector holds no map, set or Vec - every field is a scalar counter, a
Copy config, or a single Instant - so unlike the two prior extraction steps
this one found no ordering leak to fix: check_flood's .or_else() chain is a
fixed sequence written into the source text, not an iteration whose order
could vary between runs. See the new module's doc comment for the full
enumeration.

impl Default for H2FloodDetector sampled Instant::now() for test convenience
and was LIFECYCLE.md invariant 20's one other clock-sampling exception under
ConnectionH2 besides its own constructor. Verified test-only and reachable
from nowhere else (H2FloodDetector::new(flood_config, now), called once from
ConnectionH2::new's own accept-time sample, is the sole production
construction path), this extraction removes impl Default outright instead of
moving it: every former H2FloodDetector::default() call site now reads
H2FloodDetector::new(H2FloodConfig::default(), Instant::now()). The one test
whose entire premise was comparing default() against new() is deleted along
with the impl it was pinning, rather than adapted, because there is no longer
a second constructor left for it to compare against. LIFECYCLE.md invariant 20
now has zero exceptions under ConnectionH2 beyond its own constructor.

H2FloodDetector carries debug_assert pre/post-conditions on every mutating
method plus a check_invariants() sweep (the abusive-RST lifetime counter is a
subset of the total-RST lifetime counter) run as a post-condition of each,
exactly as H2FlowControl, H2StreamTable and protocol::udp::manager::UdpManager
do. Its 24 unit tests moved into the new module's own test module alongside
the type.

Noted, but deliberately not fixed here: H2FloodConfig keeps fully-pub fields
because lib/src/http.rs and lib/src/https.rs build it via struct literal from
listener config, not H2FloodConfig::new - so the .max(1) clamp is bypassed on
that production path. Pre-existing, fail-closed, not attacker-reachable; the
module doc now says so.

Re-anchored every LIFECYCLE.md, doc/testing.md and doc/lifetime_of_a_session.md
h2.rs:/mod.rs: line citation this diff shifted. The bulk of the sweep (87
citations) was verified by diffing this branch's h2.rs/mod.rs against
origin/main with difflib.SequenceMatcher and checking each mapped line's text
against the citation's recorded content, not by arithmetic offset. The
clock-section paragraph (LIFECYCLE.md's readable/writable/
cancel_timed_out_streams/start_stream/window_start/maybe_reset_window/
check_flood citations) was instead re-anchored by locating each function or
field and citing its enclosing declaration - which is wrong when the prose
describes a specific assignment, field, or comparison inside that item, not
the item itself. Eight citations landed on a signature line one to eight
lines above the statement the sentence actually describes. Corrected all
eight to the exact statement, verified by printing each cited line; the two
citations in the same paragraph that are legitimately about a function
signature (check_flood and maybe_reset_window both documented as "taking now
as a parameter") were left as signature citations, and a full sweep of every
single-line h2.rs:/h2_flood_detector.rs: citation in LIFECYCLE.md and doc/
found no other instance of this pattern.

Also updated doc/h2_mux_internals.md's flood-detection section (file table,
struct diagram, access pattern, threshold table, check_flood order) and
doc/rate-limit-design.md's stale file reference in the same changeset. Added
one NOT_A_TEST entry to check_doc_citations.py for a field name the
extraction's own doc comment brought into a test-mentioning prose block.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit c042cea into main Sep 22, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant