Skip to content

feat(mux-h2): refuse new streams before the pre-response RST_STREAM cap - #1798

Merged
FlorentinDUBOIS merged 5 commits into
mainfrom
feat/h2-refuse-streams-under-flood
Oct 2, 2026
Merged

FlorentinDUBOIS merged 5 commits into
mainfrom
feat/h2-refuse-streams-under-flood

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Fixes #1797

What

The pre-response RST_STREAM cap (h2_max_rst_stream_abusive_lifetime) ends the connection with GOAWAY(ENHANCE_YOUR_CALM), and every stream in flight on it goes with it. This adds a soft state below the cap. New client streams are refused with RST_STREAM(REFUSED_STREAM), which RFC 9113 §8.7 makes safe to retry, and the streams already open keep being served. The cap itself is unchanged.

Design

H2FloodDetector::refuses_new_streams returns true only when all three of these hold:

  • the pre-response resets are past h2_stream_refusal_percent of the cap's floor (default 50);
  • pre-response resets already outnumber the backend-routed streams. This is the cap's own ratio, so a client that would never trip the cap is never refused;
  • the last pre-response reset is less than one flood window (1 s) old. The pre-response count never decays, and refused streams cannot raise the answered count, so this condition is what ends the refusal once the client stops cancelling.

ConnectionH2::handle_header_state checks it after the drain check and before the MAX_CONCURRENT_STREAMS check, on server connections only. The refusal goes through enqueue_rst with RstOrigin::Local. It records no glitch and does not trigger the SETTINGS back-pressure, which would halve MAX_CONCURRENT_STREAMS for the rest of the connection over a state that decays. A refused stream is never registered, so its id never enters rst_sent. The refusal therefore feeds no flood counter, and in particular not the provoked-RST (MadeYouReset) cap.

A refused stream never got a response. ConnectionH2::flood_refused_streams keeps the latest contiguous run of refused ids. When the client resets one of them, the reset counts as a pre-response reset, and flood_refusal_ignored ends soft refusal for that connection. A client that ignores REFUSED_STREAM then meets the cap exactly as it does today, with no extra RST_STREAM frames in front of the GOAWAY.

Config: h2_stream_refusal_percent (u32; 0 disables; 100 or more never refuses before the cap). It is available in TOML, in command.proto (HttpListenerConfig 37, HttpsListenerConfig 50, UpdateHttpListenerConfig 43, UpdateHttpsListenerConfig 44) and as --h2-stream-refusal-percent on sozu listener http|https update. Every value has a meaning, so it has no floor and no clamp. New counter: h2.flood.stream_refused. H2FloodConfig::new / from_optional take a fourteenth argument (library API).

Trade-offs

  • The per-window RST_STREAM rate has no soft state. I implemented it first and dropped it. That counter counts every reset, answered streams included, and it half-decays every window, so a client sustaining half the rate never reaches the limit. In practice it refused streams from test_h2_cancels_during_a_backend_outage_keep_the_connection, a client the limit never cuts off.
  • PING, SETTINGS, empty DATA, CONTINUATION and stream-0 WINDOW_UPDATE floods are unchanged. They open no streams.
  • The provoked-RST cap has no soft threshold of its own. Provoked resets still count toward the shared pre-response ratio.
  • A cancel that races its own refusal ends soft refusal for that connection. This happens when the client resets a stream before the REFUSED_STREAM reaches it. The connection then falls back to today's behaviour.
  • While refusing, Sōzu still decodes each refused HEADERS block (HPACK) and queues one RST_STREAM. This is bounded by the pending-RST queue bound per pass and by the one-window lifetime of the soft state.

Tests

Red runs were made against a git archive origin/main copy with only the test file copied in, or against a scratch copy carrying the named mutation. Green runs were made in the branch.

  • test_h2_cancels_past_the_soft_threshold_refuse_new_streams (e2e, new). The client keeps an upload open, cancels one past the soft threshold and under the floor, then opens a probe stream. Red on origin/main: probe RST_STREAM code=None. Green: code=Some(7), the upload completes with 200, there is no GOAWAY, and a stream opened after 1.5 s is served.
  • resets_of_streams_refused_under_flood_count_as_pre_response (h2.rs unit). Red when refused-stream resets are not counted as pre-response. With the same mutation, test_h2_rapid_reset_triggers_goaway and e2e_h2_flood_rapid_reset_abusive_lifetime both go red (no GOAWAY).
  • Detector unit tests: entering and leaving the soft state, the ratio condition, the hard limits unchanged, 0 and 100 inert, and the RST rate ignored.
  • Rapid-reset attacker tests still end in GOAWAY(ENHANCE_YOUR_CALM).

Validation

  • cargo +nightly fmt --all -- --check: ok
  • cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings: ok
  • RUSTDOCFLAGS="-D warnings" cargo doc --all-features --no-deps: ok
  • cargo test -p sozu-lib --all-features: 1536 passed
  • cargo test -p sozu-command-lib -p sozu --all-features --locked: 527 passed
  • cargo test -p sozu-e2e --locked --features opentelemetry,splice,simd -- --test-threads=4 flood rapid_reset goaway h2spec: 43 passed
  • cargo +nightly fuzz build: ok
  • check_doc_citations.py --self-test, --root ., --root . --base origin/main, --audit --root .: all ok

Docs: doc/configure.md (new section, reference row, metric), doc/h2_mux_internals.md, lib/src/protocol/mux/LIFECYCLE.md, bin/config.toml, CHANGELOG.md.

The pre-response RST_STREAM cap (h2_max_rst_stream_abusive_lifetime)
ends the connection with GOAWAY(ENHANCE_YOUR_CALM), and every stream in
flight on it. Add a soft state below it: once a connection's
pre-response resets are past h2_stream_refusal_percent (default 50, 0
disables) of the cap's floor, already outnumber its backend-routed
streams, and the last one is less than a flood window old, each new
client stream is refused with RST_STREAM(REFUSED_STREAM), retryable per
RFC 9113 §8.7, while the open streams keep being served.

The refusal feeds no flood counter: it is a local reset, records no
glitch, and skips the SETTINGS back-pressure. A reset of a refused stream
counts as a pre-response reset and ends the refusals on that connection,
so a client that ignores them meets the cap exactly as before. The
per-window RST_STREAM rate has no soft state: it counts every reset, and
with its half-decay a client at half the rate never reaches the limit.

New listener key h2_stream_refusal_percent (TOML, protobuf, sozu ctl)
and counter h2.flood.stream_refused.

Fixes #1797

Signed-off-by: Florentin Dubois <[email protected]>
… a glitch

A refused stream moves `highest_peer_stream_id` but not `last_stream_id`,
so HEADERS on an id between the two was taken for a new stream: after
refusing 65 under flood pressure, HEADERS on 55 was refused too and left
the refused run inverted (65, 55), tripping a debug assertion. HEADERS on
a client id that was refused or skipped, never opened, is now a
connection error PROTOCOL_ERROR (RFC 9113 §5.1.1).

Soft refusals now count one glitch once the client acknowledged our
SETTINGS, like the draining and SETTINGS_MAX_CONCURRENT_STREAMS
refusals, so a client that keeps opening refused streams without
resetting any is bounded by the glitch budget.

Document that a reset of a refused stream also costs a glitch through
the closed-stream branch, that only the latest refused run is tracked,
that a benign cancel race disables the refusals for the connection, and
how fast-retrying clients meet them.

Covered by headers_below_a_refused_stream_id_is_a_protocol_error,
soft_refusals_count_toward_the_glitch_budget and
a_client_reset_of_a_refused_stream_on_the_wire_ends_the_refusals.

Refs #1797

Signed-off-by: Florentin Dubois <[email protected]>
A refused stream is never registered, so `enqueue_rst` keeps its id out
of `rst_sent` and the frames a client sent on it before reading its
REFUSED_STREAM are not ignored: each DATA frame costs a glitch and a
RST_STREAM(STREAM_CLOSED), and request trailers end the connection with
GOAWAY(PROTOCOL_ERROR), or GOAWAY(STREAM_CLOSED) once a later stream was
accepted. This holds for every refusal kind, including a graceful drain,
which then ends with PROTOCOL_ERROR instead of NO_ERROR. Browsers and
standard gRPC send no request trailers; trailer-forwarding clients can.
The behaviour is kept and documented as a rare, accepted case.

Correct the two comments in `ConnectionH2::handle_header_state` that
claimed reset streams never reach these branches, and state which ids
get PROTOCOL_ERROR and which keep STREAM_CLOSED.

Refs #1797

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit c81ded1 into main Oct 2, 2026
23 checks passed
FlorentinDUBOIS added a commit that referenced this pull request Oct 2, 2026
Bring in the squash of this branch's base, #1789, with
#1775, #1798 and #1802.

The squash carries the same changes as the base branch head this branch
had merged, so lib/src/protocol/mux/mod.rs, lib/src/protocol/mux/LIFECYCLE.md,
doc/lifetime_of_a_session.md, e2e/src/tests/tls_tests.rs and CHANGELOG.md
are resolved by keeping this branch's edits to that content over main:
the net change of this branch against origin/main is the same as it was
against the base branch head. The CHANGELOG keeps one copy of the
#1779 entry and one blank line between entries.

Re-pin the `readable()`, `writable()` and `flush_output_to_socket()`
code blocks of doc/h2_mux_internals.md to their lines in the merged
h2.rs.

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Oct 3, 2026
…1809)

Audit of the docs, `bin/config.toml` and `os-build/config.toml` against everything merged on `main` from 2026-10-01 to 2026-10-03 (43 commits, #1724 through #1808). Most of the new keys were already documented by their own PRs (`max_connection_attempts`, `h2_stream_refusal_percent`, health check `mode`/`accepted_statuses`, the raised flood defaults, the 16 MiB connection window). This PR fixes what was still stale.

| Area | Where | Was | Now |
|---|---|---|---|
| #1806 | `bin/config.toml`, `os-build/config.toml` answer comments | 503 only for "no backend available"; "504 means the backend timed out" | 503 also when every attempt failed; 504 = connected backend silent or frontend timeout while waiting; connect timeout fails over |
| #1806 | `bin/config.toml` `max_connection_attempts` | connect timeout always fails over | a TCP session whose connect times out is closed |
| #1806 | `doc/debugging_strategies.md` | 503 after a circuit breaker of 3 failed connections; ERROR log lines, one that no longer exists | `max_connection_attempts` (default 5), `backend.connect.retries_exhausted`, real TCP log levels and text |
| #1806 | `doc/configure.md` `front_timeout` / `connect_timeout` rows | "inactivity for a request to connect" | time to establish a backend connection; HTTP fails over, TCP closes; H1 failover bound by `front_timeout` |
| #1806 | `doc/configure.md` `client_timeout_during_response`, `backend_timeout`, `http.503.errors` | "connection-level slowness", "circuit breaker" | failover case included; established connection only; attempt budget |
| #1806 | `LIFECYCLE.md` backend timer | 504 for any linked stream | established connection only |
| #1806 | `cli.rs` help, `doc/configure_cli.md` | "answered 503" | "or a TCP session is closed" |
| #1756 | `doc/configure.md` flood metrics | RST lifetime rows described as absolute ceilings; no `window_update_stream0_window` row | floor-and-ratio semantics; row added |
| #1756/#1798 | `doc/architecture.md`, `doc/h2_mux_internals.md` | 6 / 13 `H2FloodConfig` thresholds | 14, with `h2_stream_refusal_percent` |
| #1756 | `doc/configure_admin_ops.md` | "halve" example 50/25 (old defaults); H2 knobs HTTPS only | 1000/500; HTTP and HTTPS; `h2.flood.stream_refused` |
| #1752 | `doc/configure.md` glitch tuning | "1 MiB window ... about 64" frames | 64 KiB stream window, about four |
| #1805 | `doc/health_checks.md` | `remove` resets backends to healthy; DOWN logs an error; `load_balancing.rs::BackendList::healthy` | backends keep their last state (see note); warning; `BackendList::select_tiers` in `backends.rs` |
| #1805 | `doc/metrics.md` | health-check counters "per cluster" | unlabelled |
| #1805 | `doc/configure_cli.md` | no health-check section | short section, `--mode`, `--probe-timeout` vs global `--timeout` |
| #1746 | `cli.rs` `--load-balancing-policy`, `bin/config.toml`, proto comment | HRW/MAGLEV key = UDP flow key | UDP affinity key (source IP, or IP and port) |
| UDP | `doc/configure.md` | hot upgrade drains flows bounded by idle timeout; `udp.flows.evicted` reasons | soft-stop closes flows at once; listener removal/soft-stop/abort added |
| #1770 | `doc/udp_simulation.md` | no per-source limits | in reconfig storms and the invariant list |
| #1743 | `doc/lifetime_of_a_session.md` | keep-alive backend always reused | unless its backend was removed |
| older | `command.proto` update messages | `h2_stream_shrink_ratio >= 1` | `>= 2`, as validated in `state.rs` |
| #1806 | e2e shuffle-sharding doc comment | "three connection attempts" | `max_connection_attempts` (5 by default) |

Reported here, not changed in this PR:
- `sozu cluster health-check remove` does not reset backends a probe marked DOWN (`remove_health_check_state` skips the reset that `set_health_check_config(None)` does), so they stay out of rotation until the cluster is added again. The doc now describes this. It looks like a code bug.
- `sozu top`'s H2 pane reads `h2.flood.violation.{rapid_reset,made_you_reset,ping,settings,priority,continuation}`, which the detector never emits (it emits `rst_stream_pre_response_lifetime`, `ping_window`, ...). Only `glitch_window` matches, and `h2.flood.stream_refused` is not shown.
- `h2_flood_detector.rs` comments still refer to a 1 MiB connection window, and the `h2_stream_idle_timeout_seconds` proto comment says "Default: 30" where the value inherits `back_timeout`.
- `connections.rejected_per_cluster_ip` is documented as also counting TCP rejections; only the HTTP 429 path increments it.

Validation:
- `sozu config check` passes on `bin/config.toml`, on a copy with every commented key under review uncommented (global and cluster `max_connection_attempts`, the H2 block, the health check block), and on `os-build/config.toml` with local state/socket paths. Negative controls (`max_connection_attempts = 0`; `expected_status = 200` next to `accepted_statuses`) are rejected.
- `cargo +1.93.1 test -p sozu-command-lib --all-features --locked`: 235 passed.
- `cargo +1.93.1 test -p sozu --bin sozu --locked`: 124 passed (including the `--load-balancing-policy` help tests).
- `cargo +nightly fmt --all --check` and `python3 .github/scripts/check_doc_citations.py --root . --base origin/main` are clean.



Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Oct 3, 2026
Fixes #1810

## What

The `sozu top` H2 pane (tab `6`) read `h2.flood.violation.{rapid_reset,made_you_reset,continuation,ping,settings,priority}`, names the H2 flood detector never emits, so only `glitch_window` could ever leave zero while a mitigation fired. It now reads the thirteen `h2.flood.violation.*` keys `H2FloodDetector` emits, most severe first (a short terminal drops the bottom rows), plus `h2.flood.stream_refused` from #1798, each with its trend sparkline (`H2_TRACKED_KEYS`).

- `lib/src/metrics/names.rs`: the six phantom constants are removed; one constant per emitted key and `FLOOD_VIOLATION_KEYS` are added. **Library API**: code importing the removed constants no longer compiles (they named metrics nothing emitted).
- `test_flood_violation_metric_keys_are_unique_and_namespaced` now also drives the stream-0 WINDOW_UPDATE arm it missed and asserts the emitted keys equal `FLOOD_VIOLATION_KEYS`.
- New `ctl::top::panes::h2::tests::flood_rows_read_the_emitted_flood_metric_names`: every `h2.flood.*` row is emitted, every emitted key (and `stream_refused`) has a row, every row has a trend.
- `snapshot_h2_120x40` regenerated: 17 flood-block rows still fit at 120x40.
- Docs: `doc/sozu-top.md` H2 row names the real keys; CHANGELOG entry under Fixed.

No protocol or security behavior changes: the detector emits exactly what it emitted before; only the TUI and the shared name constants change.

## Seen red before the fix

```
the H2 pane reads h2.flood.violation.rapid_reset, which the flood detector never emits
test result: FAILED. 0 passed; 1 failed   (cargo test -p sozu --features tui --bin sozu flood_rows)

assertion `left == right` failed: names::h2::FLOOD_VIOLATION_KEYS (read by `sozu top`) must list exactly the emitted keys
  (emitted list lacked window_update_stream0_window until the test drove that arm)
```

## Commands run

- `cargo +nightly fmt --all -- --check` -> exit 0
- `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` -> exit 0
- `cargo +1.93.1 test -p sozu --locked` -> 248 passed, 0 failed
- `cargo +1.93.1 test -p sozu --features tui --locked --bin sozu` -> 147 passed, 0 failed (the `top` module is behind the `tui` feature)
- `cargo +1.93.1 test -p sozu-lib --lib --all-features --locked` -> 1586 passed, 0 failed
- `python3 .github/scripts/check_doc_citations.py --base origin/main` -> exit 0



Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Oct 3, 2026
…1817)

Fixes #1815

## What

A stream Sōzu refuses with `RST_STREAM(REFUSED_STREAM)` is never registered, and `ConnectionH2::enqueue_rst` only records registered streams, so the bounded recently-reset set (#1784) did not know it. #1798 documented the result as an accepted limitation. Frames the client sent on the stream before it read the refusal were not ignored:

- request trailers ended the connection with `RST_STREAM(REFUSED_STREAM)`, `RST_STREAM(STREAM_CLOSED)`, `GOAWAY(PROTOCOL_ERROR)` (`GOAWAY(STREAM_CLOSED)` once a later stream was accepted), and every stream in flight went with it. A graceful drain could end with `PROTOCOL_ERROR` instead of `NO_ERROR`;
- each DATA frame cost one glitch and one `RST_STREAM(STREAM_CLOSED)`.

RFC 9113 §5.1 says those frames are ignored. The §5.1.1 `PROTOCOL_ERROR` reasoning only holds for ids the client skipped.

## Design

`H2StreamTable::remember_refused` pushes a refused id onto the `recently_reset` ring. The push/evict block of `H2StreamTable::remove` moves into a shared private helper, so refused ids get the same bound (256), the same eviction, and their allowances are dropped along with them. It is called at every refusal:

- `ConnectionH2::refuse_stream_and_discard`: draining, `SETTINGS_MAX_CONCURRENT_STREAMS`, buffer-pool exhaustion, and the oversized CONTINUATION block. That last one removes its stream before refusing it, so without this it would be the only refusal still unremembered;
- the soft flood refusal branch, which calls `enqueue_rst` itself to skip SETTINGS back-pressure.

HEADERS and DATA on a refused id now take the existing `was_reset_locally` branch of `handle_header_state`. HEADERS blocks are decoded so HPACK stays in sync. DATA is credited to the connection window (`skip_orphaned_data_payload`). The existing allowances apply: two header blocks, and DATA within the stream's initial window. Past them, each frame counts one glitch, and an empty DATA frame without END_STREAM still counts toward the empty-DATA limit.

Unchanged:
- HEADERS on a skipped id still gets `GOAWAY(PROTOCOL_ERROR)`. The ring lookup comes before that branch, and a skipped id is never in the ring (`headers_below_a_refused_stream_id_is_a_protocol_error` stays green).
- RST_STREAM never enters the reset branch, so `flood_refused_streams` / `flood_refusal_ignored` detection works as before.
- No id is added to `rst_sent`.

## Trade-offs

- Refused ids share the 256-entry ring with reset streams. A burst of refusals can evict a reset stream's memory earlier. Its late frames then fall back to the closed-stream rules, which is what already happens past 256 resets.
- A refused id evicted from the ring gets the old behaviour back: trailers on it cost `GOAWAY(PROTOCOL_ERROR)`.
- Each refused stream gets the reset-stream allowance before frames count as glitches. Allowances are held for at most `RESET_ALLOWANCES_CAPACITY` (512) streams, and every refusal still costs its own glitch once SETTINGS are acknowledged. So a client opening refused streams to spend their allowances runs into the glitch budget first.

## Tests

The red runs used the new tests on `origin/main` (`6c3b8e89`) production code:

- `trailers_on_a_refused_stream_are_ignored`: red, `got [RST(5, REFUSED_STREAM), RST(5, STREAM_CLOSED), GOAWAY(PROTOCOL_ERROR)]`. Green: one RST on stream 5, no GOAWAY, streams 1 and 3 survive, a later PING is answered, only the refusal costs a glitch, and an entry indexed by the ignored trailer block resolves in the connection's HPACK decoder.
- `data_on_a_refused_stream_is_ignored_and_credited`: 65535 bytes in 3×16384 + 16383. Red: one `RST_STREAM(STREAM_CLOSED)` per DATA frame. Green: no RST past the refusal, no glitch past the refusal, and stream-0 WINDOW_UPDATE credit exactly equal to the 65535 bytes ignored (a double credit fails).
- `a_drain_with_a_refused_upload_carrying_trailers_ends_with_no_error`: red, the first GOAWAY is `PROTOCOL_ERROR`. Green: `NO_ERROR`.
- `refused_streams_share_the_recently_reset_bound` (`h2_stream_table.rs`): bound, eviction, allowances dropped, dedupe.

Mutation checks:
- dropping the soft-refusal `remember_refused` call fails the first two tests;
- dropping the call in `refuse_stream_and_discard` fails the drain test.

Every existing #1784 / #1798 test stays green and unmodified.

## Validation

- `cargo +nightly fmt --check`: ok
- `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings`: ok
- `RUSTDOCFLAGS="-D warnings" cargo +1.93.1 doc --no-deps --locked -p sozu-lib`: ok
- `cargo +1.93.1 test -p sozu-lib --lib --all-features --locked`: 1592 passed
- `cargo test -p sozu-e2e --locked --features opentelemetry,splice,simd -- --test-threads=4 h2_security flood rapid_reset goaway`: 128 passed, 1 failed. The failure was `test_h2_rapid_reset_triggers_goaway` (no GOAWAY read within the window) at a host load average of about 80. It also fails on `origin/main` under the same load (1 run out of 3), and it passed 3 runs out of 3 on this branch at load ~50. It is load-sensitive and not affected by this change, since RST_STREAM frames do not take the changed path.
- Full e2e suite: not run, the host was too loaded.
- `check_doc_citations.py --self-test` and `--root . --base origin/main`: ok (renumbered the `h2.rs` line citations in `doc/h2_mux_internals.md` that moved)

Docs: `doc/configure.md`, `doc/h2_mux_internals.md`, `lib/src/protocol/mux/LIFECYCLE.md`, and `CHANGELOG.md`. The #1798 entry now points to this fix, and there is a new Fixed entry.



Signed-off-by: Florentin Dubois <[email protected]>
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.

H2: refuse new streams before an RST_STREAM flood limit instead of closing the connection

1 participant