Skip to content

feat(http): opt-in HTTP/2 prior knowledge (h2c) on HTTP listeners - #1917

Merged
FlorentinDUBOIS merged 16 commits into
mainfrom
feat/h2c-prior-knowledge
Nov 3, 2026
Merged

FlorentinDUBOIS merged 16 commits into
mainfrom
feat/h2c-prior-knowledge

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1911.

Problem

HttpListener refuses cleartext HTTP/2: a client that opens with the PRI * HTTP/2.0 preface gets a 400. Cleartext gRPC with prior knowledge is common inside a cluster, and the Kubernetes Gateway API GRPCRoute conformance suite dials the Gateway's HTTP port that way. A proxy built on Sōzu could not serve it.

Change

A new per-listener option, h2c_prior_knowledge, off by default:

  • proto HttpListenerConfig.h2c_prior_knowledge (field 38) and UpdateHttpListenerConfig.h2c_prior_knowledge (field 44); TOML h2c_prior_knowledge = true; CLI sozu listener http add --h2c-prior-knowledge, sozu listener http update --h2c-prior-knowledge / --no-h2c-prior-knowledge.
  • When on, a session starts in a new H2cPrefaceSniff state (lib/src/protocol/h2c.rs). It peeks (MSG_PEEK) up to 24 bytes and consumes nothing:
    • all 24 bytes are the preface → an HTTP/2 mux frontend (Connection::new_h2_server) with the listener's H2 flood thresholds and tuning, the same as an ALPN h2 connection on HttpsListener;
    • the first byte that diverges → HTTP/1.x, exactly as today;
    • a strict prefix so far → wait for more bytes within request_timeout.
  • The mux reads the peeked bytes itself. On the switch, READABLE and WRITABLE are re-armed, because the peeked bytes raise no new epoll edge.
  • It composes with expect_proxy: the PROXY header comes first, then the sniff.
  • The scheme stays http (:scheme, X-Forwarded-Proto, Forwarded: proto). tls_alpn stays unset, so the router's ALPN-h2 coalescing branch does not apply. Upgrade: h2c (deprecated by RFC 9113) is still not supported.
  • Buffer size: an h2c listener now counts for the load-time buffer_size >= 16393 H2 check (BufferSizeTooSmallForH2). Otherwise a small buffer would deadlock the H2 mux on full-size frames. As with HTTPS ALPN, a runtime listener update is not checked against buffer_size.
  • New metrics: http.h2c.prior_knowledge and http.upgrade.h2c.failed. A new log tag, HTTP-H2C.

Protocol / security impact

  • Flag off: nothing changes. No sniff runs, a preface still gets 400, and an unset key stays absent from saved state.
  • Flag on: a client that sends nothing, or only part of the preface, before request_timeout is closed without the 408 an HTTP/1-only listener sends. This is documented in doc/configure.md. H2 frontends on such a listener get the same H2 flood protections as HTTPS (Rapid Reset, CONTINUATION, MadeYouReset, …).
  • A listener update reaches new connections only. sozu reload does not toggle the flag on an existing listener (the same as every other listener field today), so use listener update.
  • Setting the flag on an HTTPS listener has no effect.

Tests

  • Unit: classify_preface (full, partial, divergent at each byte, empty), sniff state, TOML parsing, state patch, and buffer_size_below_h2_minimum_rejected_for_an_h2c_http_listener. That last one was seen red with the h2c clause disabled.
  • E2E h2c_prior_knowledge_tests (6): h2c → HTTP/1 backend, h2c → h2 backend (proto headers checked), HTTP/1.1 still works with the flag on, a preface split across two writes, h2c behind PROXY protocol, and flag off → 400. Seen red: with the flag forced off in session creation, 4 fail and the 2 controls pass.

Commands run

  • cargo +nightly fmt --all -- --check: exit 0
  • cargo clippy --all-targets --locked -- -D warnings: exit 0
  • cargo +1.93.1 check --workspace --all-targets --locked (MSRV): exit 0
  • cargo build --all-features --locked: exit 0
  • python3 .github/scripts/check_doc_citations.py --root .: exit 0
  • cargo test --workspace --locked -- --skip tests::fuzz_tests::: exit 0, 3431 passed, 0 failed (e2e 674 passed)

Docs

doc/configure.md (option, h2c behaviour, buffer-size rule), doc/configure_admin_ops.md, doc/observability.md (metrics), doc/lifetime_of_a_session.md, doc/architecture.md, doc/hot_path_zero_copy.md, mux LIFECYCLE.md, CLAUDE.md (log tag list), bin/config.toml, e2e/COVERAGE.md, CHANGELOG Unreleased › Added.

Dependencies

Stacked on #1916, #1918 and #1915 (this branch merges them), so CI runs on exactly the tree this PR lands on main. Until those merge, the commit list and diff also show their changes; the squash merge carries only this PR's own. #1919 (lockfile) and #1914 are already on main. Merge order: #1915 → #1918 → #1916 → #1917.

With `rewrite_host` on a frontend, `apply_request_rewrites_and_headers`
(`lib/src/protocol/mux/router.rs`) rewrote the request authority and then
added a synthetic `Host` header block. The HTTP/1.1 converter
(`kawa::protocol::h1::converter`) already writes `Host: <authority>` right
after the request line, so an HTTP/1.1 backend received two `Host`
headers, and servers that reject a duplicate (Go's `net/http`) answered
400. The HTTP/2 converter filters every `host` block, so the block was
useless there.

An operator request header named `Host` had the same root cause and
worse: the backend received the client's authority and the operator's
value as two different `Host` lines, the smuggling primitive the code
comment claimed to prevent.

The authority is now the only carrier of the backend `Host`: no `Host`
header block is ever inserted. A non-empty `Host` request header edit
replaces the authority (last one wins) unless `rewrite_host` is set,
which keeps precedence; an empty one still drops header blocks only.
An HTTP/2 backend therefore now receives that edit as `:authority`.

The H1→H1 rewrite test now requires exactly one `Host`; new e2e tests
cover the operator `Host` edit (H1→H1) and `rewrite_host` from an HTTP/2
frontend to an HTTP/1.1 backend.

Fixes #1908

Signed-off-by: Florentin Dubois <[email protected]>
A `REGEX` path rule is matched against the request path together with its
query string, so `/api/.+` matches `/api/?x=1` and `^/api/v2$` does not
match `/api/v2?x=1`. There was no way to match a regex against the path
only, which is what the Gateway API HTTPRoute `RegularExpression` path
match (and Traefik `PathRegexp`, Envoy `safe_regex`) expects.

Add a new path rule kind, `REGEX_PATH` (`PathRuleKind::REGEX_PATH = 3`,
TOML `path_type = "REGEX_PATH"`, CLI `--path-regex-path`). It is anchored
and compiled exactly like `REGEX` and ranks as `REGEX` does, but it is
tested against the request-target up to its first `?`. `REGEX`, `PREFIX`
and `EQUALS` are unchanged.

With `rewrite_path`, a `REGEX_PATH` frontend's `$PATH[n]` captures,
`$PATH[0]` included, come from the path alone. The original `?query` is
appended to the rewritten path unless that path carries a `?` of its own,
and a redirect `Location` follows it. The frontend gets its own
`ConfigState` key letter (`Q`), so a `REGEX` and a `REGEX_PATH` frontend
on the same pattern don't collide.

Library API: `PathRule::from_cli_options` takes a fourth argument, and
`PathRule` (sozu-lib) and `PathRuleType` (sozu-command-lib) gain a
`RegexPath` variant. A worker that predates the kind refuses such a
frontend with `RouterError::InvalidPathRule`.

Fixes #1909

Signed-off-by: Florentin Dubois <[email protected]>
`HttpListener` refused cleartext HTTP/2: a client opening with the
`PRI * HTTP/2.0` preface got a 400, so cleartext gRPC (e.g. the Kubernetes
Gateway API `GRPCRoute` conformance suite, which dials with insecure
credentials) could not be served.

Add a per-listener `h2c_prior_knowledge` option (HttpListenerConfig field
38, UpdateHttpListenerConfig field 44, TOML key, `listener http add/update`
CLI flags), off by default. When on, a new session first goes through an
`H2cPrefaceSniff` state (`lib/src/protocol/h2c.rs`) that peeks up to 24
bytes without consuming them: the full preface makes it an HTTP/2 mux
frontend with the listener's H2 settings, as an ALPN `h2` connection is on
HTTPS; the first diverging byte makes it HTTP/1.x; a strict prefix waits
within `request_timeout`. The mux reads the peeked bytes itself, and the
upgrade re-arms READABLE and WRITABLE since peeking raises no new edge.
It composes with `expect_proxy` (PROXY header, then sniff). The scheme
stays `http` and `tls_alpn` stays unset. `Upgrade: h2c` stays unsupported.

Such a listener is held to the H2 minimum `buffer_size` at configuration
load, like an HTTPS listener advertising `h2`. New metrics
`http.h2c.prior_knowledge` and `http.upgrade.h2c.failed`.

Closes #1911

Signed-off-by: Florentin Dubois <[email protected]>
…losing it

A large Content-Length response was cut at a random offset (the client
reported "Premature end of Content-Length delimited message body"), on
plaintext and TLS listeners alike; the ALPN list played no part.

CAUSE: `Mux::ready_inner` counts every inner-loop iteration against
`MAX_LOOP_ITERATIONS` (10,000), whether or not it moved bytes. When the
client and the backend both keep up, no socket answers WouldBlock, so one
`ready()` call reaches the budget after about 160 MiB with 16 KiB
buffers. `Mux::wait_for_client_at_loop_limit` then finds nothing queued,
because the frontend has just drained, and returns `SessionResult::Close`:
a clean close in the middle of the body. 2.2.1 has the same defect,
without a log at the default level.

A new `Context::stream_bytes_out` counts the stream bytes written to
either peer (`ConnectionH1::writable`, `H2Shell::write_streams`). A call
that reaches the budget after it moved now yields instead. It keeps every
readiness bit, sets a flag, and counts `http.mux.loop_budget_yield`. The
HTTP/HTTPS sessions report the flag through a new
`ProxySession::yielded` (default `false`). The server queues the session
and resumes it after its next poll with no new event (edge-triggered
epoll would not deliver one), using a non-blocking poll while anything
is queued. A session that closed in between is skipped by weak-reference
and slab-identity checks. A fast transfer is therefore neither cut nor
allowed to hold the single-threaded worker for more than one budget per
turn. A call that forwarded nothing keeps the existing
`http.infinite_loop.error` path.

Tests: a mux unit test drives the resumed passes with no
`update_readiness` and fails on the old close; server unit tests cover
resumption and a session closed before it; e2e `large_response_tests`
(256 MiB downloads/uploads, plaintext and TLS with ALPN h2,http/1.1)
cut 4/40, 5/60 and 10/20 trials on main and none with the fix.

Fixes #1906

Signed-off-by: Florentin Dubois <[email protected]>
`RUSTDOCFLAGS=-D warnings cargo doc --all-features` (CI msrv-full)
refused the intra-doc link from `PathRule::RegexPath` to the private
`split_query` helper. Name it as code instead.

Signed-off-by: Florentin Dubois <[email protected]>
The yield at `MAX_LOOP_ITERATIONS` fired when any stream byte moved
during the call. A spin that trickled a few bytes would then yield on
every event-loop turn instead of reaching the spin path, burning a
full budget of CPU per turn. That fails open.

`progressed_through_loop_budget` now requires the call to have moved at
least one stream byte per budgeted iteration (wrapping difference of
`Context::stream_bytes_out`). A real transfer forwards up to a buffer per
iteration, so it still yields; a trickle falls back to
`Mux::wait_for_client_at_loop_limit` and `http.infinite_loop.error`.

Refs #1906

Signed-off-by: Florentin Dubois <[email protected]>
…nse up

`back_timeout` and `front_timeout` bound the inactivity of one socket
each, yet both cut a response held up by the other peer:

- A client that paused longer than `back_timeout` left Sōzu holding
  response bytes, so Sōzu stopped reading the backend itself; the
  backend timer then fired and force-terminated the response
  (`backend_response_timeout`).
- A backend that paused longer than `front_timeout` left a client that
  had taken every byte waiting; the frontend timer then took the
  "response fully proxied" arm, because kawa's `is_completed` only means
  nothing is queued, and the session closed silently mid-body.

`response_waits_on_client` (stream bytes queued, or the H1 frontend's
own pending write) now decides. The backend timeout defers to the
frontend while it holds, re-arming only the backend and returning
before the shared tail, which would re-arm the frontend. The frontend
timeout defers to the backend while it does not, and the "fully
proxied" arm requires a terminated or errored response. The two
conditions are complementary, so a client that stops reading still
meets `front_timeout` and a silent backend still meets `back_timeout`.

Unit tests cover both deferrals and the frontend complement; two e2e
tests pause 4 s against 2 s timeouts and were cut at 4.0 and 6.0 of
8 MiB before the fix.

Refs #1906

Signed-off-by: Florentin Dubois <[email protected]>
`cargo audit --deny warnings` (CI "cargo audit") fails on main's
lockfile with two findings published after its last green run:

- RUSTSEC-2026-0433: pulldown-cmark 0.13.5, quadratic parsing of nested
  image wikilinks with ENABLE_WIKILINKS. Fixed in 0.13.6. A build
  dependency only, through prost-build.
- async-executor 1.14.0 is yanked. Moved to 1.14.1.

Lockfile-only: both are patch updates within the existing requirements.
Signed-off-by: Florentin Dubois <[email protected]>
`cargo audit --deny warnings` (CI "cargo audit") fails on main's
lockfile with two findings published after its last green run:

- RUSTSEC-2026-0433: pulldown-cmark 0.13.5, quadratic parsing of nested
  image wikilinks with ENABLE_WIKILINKS. Fixed in 0.13.6. A build
  dependency only, through prost-build.
- async-executor 1.14.0 is yanked. Moved to 1.14.1.

Lockfile-only: both are patch updates within the existing requirements.
Signed-off-by: Florentin Dubois <[email protected]>
`cargo audit --deny warnings` (CI "cargo audit") fails on main's
lockfile with two findings published after its last green run:

- RUSTSEC-2026-0433: pulldown-cmark 0.13.5, quadratic parsing of nested
  image wikilinks with ENABLE_WIKILINKS. Fixed in 0.13.6. A build
  dependency only, through prost-build.
- async-executor 1.14.0 is yanked. Moved to 1.14.1.

Lockfile-only: both are patch updates within the existing requirements.
Signed-off-by: Florentin Dubois <[email protected]>
`cargo audit --deny warnings` (CI "cargo audit") fails on main's
lockfile with two findings published after its last green run:

- RUSTSEC-2026-0433: pulldown-cmark 0.13.5, quadratic parsing of nested
  image wikilinks with ENABLE_WIKILINKS. Fixed in 0.13.6. A build
  dependency only, through prost-build.
- async-executor 1.14.0 is yanked. Moved to 1.14.1.

Lockfile-only: both are patch updates within the existing requirements.
Signed-off-by: Florentin Dubois <[email protected]>
Brings in #1919 (lockfile) and #1914 (command channel error) and keeps
both CHANGELOG slots, each followed by a blank line.

Signed-off-by: Florentin Dubois <[email protected]>
Stacks this branch on #1915, itself up to date with main after #1919
(lockfile) and #1914, so CI runs on the tree this PR lands. Keeps every
CHANGELOG slot, each followed by a blank line.

Signed-off-by: Florentin Dubois <[email protected]>
Stacks this branch on #1918 and #1915, up to date with main after #1919
(lockfile) and #1914, so CI runs on the tree this PR lands. Keeps every
CHANGELOG slot, each followed by a blank line.

Signed-off-by: Florentin Dubois <[email protected]>
Stacks this branch on #1916, #1918 and #1915, up to date with main after
#1919 (lockfile) and #1914, so CI runs on the tree this PR lands. Keeps
every CHANGELOG slot, each followed by a blank line.

Signed-off-by: Florentin Dubois <[email protected]>
main now carries #1916 as a squash commit, whose CHANGELOG insertion
conflicts with the stacked original. Keeps every CHANGELOG slot; the
tree is unchanged.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 2c3b43e into main Nov 3, 2026
46 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the feat/h2c-prior-knowledge branch November 4, 2026 10:54
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.

HttpListener: opt-in HTTP/2 prior knowledge (h2c) for cleartext gRPC

1 participant