Repository navigation
feat(listener): make forwarded headers configurable per listener - #1685
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 29, 2026 14:19
FlorentinDUBOIS
force-pushed
the
feat/forwarded-headers
branch
from
September 29, 2026 14:57
fb1ec5e to
9581ba9
Compare
FlorentinDUBOIS
force-pushed
the
feat/forwarded-headers
branch
from
September 29, 2026 16:27
9581ba9 to
a339a45
Compare
This was referenced Sep 29, 2026
listener: hot updates of send_x_real_ip and elide_x_real_ip are not recorded in the main state
#1688
Closed
Sōzu added both forwarding header families to every forwarded request,
unconditionally. HTTP and HTTPS listeners gain a `forwarded_headers`
enum (wire: `ForwardedHeaders`, TOML: `ForwardedHeadersMode`):
- `both` (default): the previous behaviour, byte for byte.
- `x_forwarded`: only X-Forwarded-For/-Proto/-Port, client chains
handled as in `both`; a client `Forwarded` passes through.
- `rfc7239`: only `Forwarded`, a client chain extended with this hop
(RFC 7239 §4). A client X-Forwarded-For/-Proto/-Port/-Host is
elided: RFC 7239 §8.1 says a client-supplied forwarding field cannot
be trusted, and passing one through without Sōzu's hop after it is
weaker than `both`. No §7.4 conversion is attempted, since the order
of mixed pre-existing headers cannot be known.
- `none`: nothing added, client headers untouched (documented trust
caveat).
The editor gates emission only: `ForwardingHop` still renders every
value once per connection, so `send_x_real_ip` keeps working in every
mode and the default path allocates exactly as before. A `rewrite_host`
injects `X-Forwarded-Host` only in `both` and `x_forwarded`. The access
log's `xff_chain` is recorded in every mode.
In `both` and `rfc7239`, the modes that extend a client `Forwarded`
chain, a client line that is not a well-formed RFC 7239 §4 list is
elided instead of extended (`is_valid_forwarded`): an unclosed
quoted-string such as `for="6.6.6.6` used to swallow Sōzu's element.
A well-formed chain is extended byte for byte as before. H2 trailers
now also drop X-Forwarded-Proto/-Port/-Host, like the other
forwarding headers they already dropped.
The mode is captured per stream in `Context::create_stream`, like
`send_x_real_ip`. It is hot-updatable through
`UpdateHttp(s)ListenerConfig`, and both the main-process state and the
worker refuse an unknown wire value on add and on update. The CLI gains
`sozu listener {http,https} {add,update} --forwarded-headers <mode>`.
Tests: editor unit tests for all four modes on bare and client-chained
requests, malformed client `Forwarded`, the RFC 7239 grammar, H2
trailer drops, router X-Forwarded-Host per mode, TOML parse/default/
rejection, state and worker add/update validation, CLI parse, e2e H1
(`rfc7239`, malformed `Forwarded`, `none`), H2 protocol-pair matrix
(`rfc7239`) and a live listener patch.
Closes #322
Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
feat/forwarded-headers
branch
from
September 29, 2026 18:03
a339a45 to
1076a24
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 29, 2026
## Problem While Sōzu shuts down (`HttpContext::closing`, set by `Mux::shutting_down_inner`), `HttpContext::on_request_headers` and `HttpContext::on_response_headers` (`lib/src/protocol/kawa_h1/editor.rs`) overwrote every `Connection` value with `close`. That dropped the other options: a field the peer nominated as hop-by-hop (`Connection: x-custom`) was forwarded as end-to-end (RFC 9110 §7.6.1), a request's `Upgrade` field reached the backend without the `upgrade` option that must accompany it (§7.8), and, on the response side, the backend's own `close` was no longer recorded in `keep_alive_backend`. An HTTP/1.1 final response without a `Connection` line got no `close` at all. ## Fix - Both header loops now always record the `close` decision from the original value (`keep_alive_frontend` / `keep_alive_backend`); nothing is rewritten inside the loop. - The HTTP/1.0 merge from #1683 moves into `merge_connection_options_into_close`: every `Connection` line is elided and one line is pushed with the other options followed by a single `close`; `keep-alive` (and an already listed `close`) is dropped. A lone `close` stays a static value (no allocation). - Request side: under `closing`, the merge runs (it replaces the old push-if-absent), so `Connection: close` is still added when the client sent none. - Response side: the merge runs for every final response under `closing` (HTTP/1.1 as well as HTTP/1.0), and as before for a non-persistent HTTP/1.0 response. A 1xx is left alone, as the HTTP/1.0 branch already did. - Docs: `lib/src/protocol/kawa_h1/LIFECYCLE.md` (both callbacks), `CHANGELOG.md` (Unreleased / Fixed). ## Decision: a request asking for `Upgrade` during shutdown Options: (a) keep `Connection: Upgrade, close` and let the backend decide; (b) refuse the upgrade. This PR takes **(b)**: the `upgrade` option is dropped along with every `Upgrade` field (a nominated field must not go end-to-end, §7.6.1). The backend then answers in HTTP/1.1, which a server may always do (§7.8: accepting an upgrade is optional), and the client gets a normal response with `Connection: close` and can retry the upgrade on a new connection. Why not (a): `ConnectionH1::writable` (`lib/src/protocol/mux/h1.rs`) checks `stream.context.closing` **before** the `101` arm, so while draining Sōzu never completes an upgrade. Under (a), a 101 would reach the client and the connection would close right after it. Refusing is the only choice consistent with the existing drain semantics (finish in-flight work, start no long-lived work). Before this PR the request already went out as `Connection: close` + `Upgrade: websocket` (see RED below), which was broken in its own way. If you would rather keep the upgrade, `writable` has to change too; please say so on this PR. ## `lib/src/protocol/kawa_h1/answers.rs` whole-value `Connection: close` match: left as is That match (in the template parser) sets the template's own `keep_alive` flag. It reads operator-authored answer templates, not peer traffic, and every shipped default template carries a lone `Connection: close` line (checked: all 15 `Connection:` lines of the built-in default templates in `answers.rs`, outside its test module, are exactly `Connection: close`), so no default answer is affected. It is the same kind of defect as #1687 (a list such as `x, close` would read as keep-alive), but it is outside this shutdown fix. It deserves its own small follow-up that exposes `has_connection_option` to `answers.rs`. ## Tests New unit tests in `editor.rs`, run with `closing = true`: - `a_shutting_down_request_keeps_its_connection_options`: no Connection → `close`; `x-custom` → `x-custom, close`; `keep-alive, x-custom` → `x-custom, close`; `close` stays a single `close` and clears `keep_alive_frontend`; two lines merged; HTTP/1.0. - `a_shutting_down_request_does_not_upgrade`: `Upgrade` → `close` with no `Upgrade:` field; `keep-alive, Upgrade, x-custom` → `x-custom, close`. - `a_shutting_down_response_keeps_its_connection_options`: the same matrix on HTTP/1.1 responses plus a persistent HTTP/1.0 one; the backend `close` clears `keep_alive_backend`. - `a_shutting_down_interim_response_is_left_alone`: a 101 keeps `Connection: Upgrade`; a 100 gets no line. **RED** (tests added on `origin/main` 3ed6e8a before the fix, `cargo test -p sozu-lib --lib a_shutting_down`): ``` test protocol::kawa_h1::editor::tests::a_shutting_down_request_does_not_upgrade ... FAILED test protocol::kawa_h1::editor::tests::a_shutting_down_request_keeps_its_connection_options ... FAILED test protocol::kawa_h1::editor::tests::a_shutting_down_interim_response_is_left_alone ... FAILED test protocol::kawa_h1::editor::tests::a_shutting_down_response_keeps_its_connection_options ... FAILED websocket: the Upgrade field is not forwarded, got "GET /chat HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\nUpgrade: websocket\r\n..." nominated field: ... left: ["Connection: close"] right: ["Connection: x-custom, close"] 101: ... left: ["Connection: close"] right: ["Connection: Upgrade"] no Connection: ... got "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nSozu-Id: ...\r\n\r\nabcd" left: [] right: ["Connection: close"] test result: FAILED. 0 passed; 4 failed; 0 ignored; 0 measured; 1349 filtered out ``` **GREEN** (`cargo test -p sozu-lib --lib kawa_h1`): ``` test protocol::kawa_h1::editor::tests::a_shutting_down_request_does_not_upgrade ... ok test protocol::kawa_h1::editor::tests::a_shutting_down_interim_response_is_left_alone ... ok test protocol::kawa_h1::editor::tests::a_shutting_down_response_keeps_its_connection_options ... ok test protocol::kawa_h1::editor::tests::a_shutting_down_request_keeps_its_connection_options ... ok test result: ok. 71 passed; 0 failed ``` ### Why there is no e2e test The request-side shutdown branch is unreachable today, and no known sequence reaches the response-side one: the fix is defensive. The e2e harness cannot reach either. `Mux::shutting_down_inner` sets `closing` only on an `Unlinked` stream, whose headers were already edited, and an idle keep-alive session is closed rather than marked (see `try_msg_close`). Measured: with an `eprintln!` probe in both merge branches, the whole `sozu-e2e` suite (fuzz skipped) got **0 probe hits** (493 passed / 7 failed; the 7 are load flakes, see below). The probe was then removed. This shows only that the harness does not reach the branches; whether production traffic can reach them (for example via a retried or H2 stream) is not established here. The unit tests are the coverage, and LIFECYCLE.md says so. ## Validation (each by its own exit code) - `cargo build --all-features` → 0 - `cargo clippy --all-features --all-targets -- -D warnings` → 0 - `cargo +nightly fmt --all -- --check` → 0 - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` → 0 - `cargo test -p sozu-lib` → 0 (1363 passed); `-p sozu` → 0 (238); `-p sozu-command-lib` → 0 (195) - e2e: `http10` 5/5, `close_delimited` 12/12, `keep_alive` 4/4, `connection` 20/20, `upgrade` 14/14, `websocket` 4/4, `soft_stop` 2/2, all exit 0 - `check_doc_citations.py` `--self-test`, `--root .`, `--base origin/main`, `--audit --root .` → all 0 Flake triage for the 7 failures in the full probe run (host load average 43–63 from concurrent builds): `test_h1_smuggling_te_cl_trailing_tab`, `e2e_h2_flow_per_stream_idle_timeout`, `test_upgrade` and `test_upgrade_multiple_in_flight` passed on their first isolated rerun. `test_h2_graceful_shutdown_completes_large_transfer` and `test_issue_806` failed once in isolation, then passed 3 more isolated runs. `test_h1_to_h2_basic_request` (H1 client → H2 backend, `closing` never set) then went 8/8 on this branch and 8/8 on an `origin/main` worktree in interleaved runs. None of these paths enter the changed branches: the probe fired 0 times. ## Revision 2 (after review) - Rebased on `origin/main` d9ce2a0 (#1686). - MSRV clippy (1.93.1, `clippy::nonminimal_bool`) flagged the option filter in `merge_connection_options_into_close`: it is now a named `dropped` disjunction, with no `allow`. `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` → 0 (0 warning/error lines); stable clippy → 0. - Dropped the tautological shutdown `debug_assert!` in `on_response_headers`. - LIFECYCLE.md now states that the request-side shutdown branch is unreachable today (`Mux::shutting_down_inner` sets `closing` only on an `Unlinked`, non-quiesced stream whose heads were both edited) and that both branches are defensive. - Rerun: build, nightly fmt, doc `-D warnings`, `cargo test -p sozu-lib` (1372 passed), `kawa_h1` 71 passed, e2e `http10` 5/5, `connection` 20/20, `upgrade` 15/15, `websocket` 4/4, four citation checks → all 0. ## Residual risks - Textual conflict with #1685 (`feat/forwarded-headers`) in the `on_request_headers` header loop: adjacent lines only, trivial to resolve. The first PR to merge leaves a one-hunk rebase for the other. - The shutdown branches are covered by unit tests only (see above). Closes #1690 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 29, 2026
…1699) Closes #1692 ## What Follow-up to #1685. In the `both` (default) and `rfc7239` `forwarded_headers` modes, Sōzu removes a client `Forwarded` line that is not a well-formed RFC 7239 §4 list (`is_valid_forwarded`), including common non-conforming values such as `for=1.2.3.4:80` or `for=2001:db8::1`. The only trace was a `debug!` line. - New proxy counter `http.forwarded_malformed_elided` (`names::http::FORWARDED_MALFORMED_ELIDED`), incremented once per removed line in `HttpContext::on_request_headers`, on the elision branch only. No allocation added; a well-formed line pays nothing. `x_forwarded` and `none` pass the line through and count nothing. - Fixed the comment above the H2 trailer drop list in `pkawa::handle_trailer`: it claimed each managed header is "either synthesised or removed" on the HEADERS pass, which is untrue in `none` mode and for `Forwarded` in `x_forwarded` mode. Kept the edit to the inline comment only, to keep the conflict surface with #1695 small; the `///` docstring above `handle_trailer` and the `handle_trailer_drops_each_spoof_header_individually` docstring also omit `none` and are left for #1695 / a follow-up. - Docs: `doc/configure.md` (forwarded_headers section + "Other" metrics table), `doc/observability.md` (new subsection), `lib/src/protocol/kawa_h1/LIFECYCLE.md`, CHANGELOG (Unreleased / Added). ## Test `a_malformed_client_forwarded_elision_is_counted_once_per_line` (editor.rs): for `both`/`rfc7239`, a valid chain counts 0, one malformed line counts 1, two malformed lines around a valid one count 2; for `x_forwarded`/`none` nothing is counted. RED (test added, `incr!` absent): ``` test protocol::kawa_h1::editor::tests::a_malformed_client_forwarded_elision_is_counted_once_per_line ... FAILED thread '...a_malformed_client_forwarded_elision_is_counted_once_per_line' panicked at lib/src/protocol/kawa_h1/editor.rs:3785:13: assertion `left == right` failed: Both: one malformed line left: 0 right: 1 test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 1370 filtered out; finished in 0.01s ``` GREEN (with the `incr!`): ``` test protocol::kawa_h1::editor::tests::a_malformed_client_forwarded_elision_is_counted_once_per_line ... ok test protocol::kawa_h1::editor::tests::a_malformed_client_forwarded_is_elided_where_the_chain_is_extended ... ok test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1370 filtered out; finished in 0.06s ``` ## Validation (each by its own exit code, all 0) - `cargo build --all-features` - `cargo clippy --all-features --all-targets -- -D warnings` - `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` - `cargo +nightly fmt --all -- --check` - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` - `cargo test -p sozu-lib` (lib: 1372 passed, incl. `lib/tests/metric_names.rs`), `cargo test -p sozu`, `cargo test -p sozu-command-lib` - `cargo test -p sozu-e2e forward` (23 passed) - `python3 .github/scripts/check_doc_citations.py` `--self-test`, `--root .`, `--base origin/main`, `--audit --root .` Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 29, 2026
#1695) Closes #1689 ## Problem (reproduced) kawa's H1 parser pushes a chunked request's trailer fields after its last chunk with no callback, so `HttpContext::on_request_headers` never sees them. On `main` (`3ed6e8a6`) the new e2e test shows the backend receiving them verbatim: ``` TRAILER-SPOOF: backend received "POST /api HTTP/1.1\r\n...X-Forwarded-For: 127.0.0.1\r\n...\r\n\r\n5\r\nHello\r\n0\r\nX-Forwarded-For: 6.6.6.6\r\nForwarded: for=6.6.6.6\r\nX-Real-IP: 6.6.6.6\r\nX-Request-Id: 6.6.6.6\r\nX-Forwarded-Proto: 6.6.6.6\r\nX-Forwarded-Port: 6.6.6.6\r\nX-Forwarded-Host: 6.6.6.6\r\nGrpc-Status: 0\r\n\r\n" ``` A backend that merges trailers into its header view then sees a forged client address (RFC 9110 §6.5.1, CWE-348). ## Fix - `TRAILER_SPOOF_VECTOR_HEADERS` (`lib/src/protocol/kawa_h1/editor.rs`) is now the **single list** for both frontends: `x-real-ip`, `x-forwarded-for`, `forwarded`, `x-request-id`, `x-forwarded-proto`, `x-forwarded-port`, `x-forwarded-host`. `pkawa::handle_trailer` reads it instead of the inline seven-name `matches!` that #1685 (merged as `5471bfba`) added, so H1 and H2 cannot drift. H2 behaviour is unchanged. This branch is rebased on `origin/main` (`a6419607`), which includes #1685, #1696, #1697 and #1699. The `editor.rs` conflict with #1696 (both appended tests at the end of the test module) keeps both sets of tests, and the `pkawa.rs` comment keeps #1699's mode wording while naming the shared constant. The `pkawa.rs` conflict was resolved in favour of the shared constant, keeping #1685's `forwarded_headers`-mode wording in the doc comments, the test rationale and the `doc/configure.md` paragraph (which now also names the H1 path). - `elide_request_trailer_spoof_vectors` (same file) runs after both frontend `kawa::h1::parse` sites of `ConnectionH1`: `readable`, and the keep-alive branch of `writable` that parses a pipelined request. Each call site reads `kawa.blocks.len()` just before the parse and passes it as `first_new_block`. The walk goes back only over the blocks that parse appended (closing `Flags` + trailer fields), stopping at the `end_body` marker or at `first_new_block`. It elides matching names in any case with `Pair::elide`. - **Linear cost (review item):** a parse only appends blocks and `prepare` only drains from the front between parses, so every older field was already examined by the call after the parse that queued it. A client that trickles one trailer line per segment while the backend isn't writable costs one block per line, not an O(n²) re-walk. This holds when earlier trailer fields were already drained to the backend. - **Framing:** kawa's H1 and H2 converters skip elided pairs. The last chunk and the closing empty line are still written, so the framing stays valid even when every field is dropped. The e2e test asserts `...0\r\nGrpc-Status: 0\r\n\r\n` on the wire. - **Cost:** the function returns on the `kind` / `body_size == Chunked` / `parsing_phase ∈ {Trailers, Terminated}` checks before reading any block. Requests without trailers pay three field compares. - **Responses are not filtered.** A response trailer goes to the client, which does not take client attribution from it, so the spoofing risk this issue describes does not apply. - New counter `http.trailer.spoof_vector_elided` (one increment per elided H1 field), documented in `doc/configure.md`. - Docs: `doc/configure.md` (anti-spoof paragraph + metric row), `lib/src/protocol/kawa_h1/LIFECYCLE.md` §2.3, `CHANGELOG.md` (Unreleased / Security). ## Tests (red, then green) New tests: `a_chunked_request_trailer_section_loses_its_spoof_vector_fields`, `a_trailer_section_parsed_after_the_last_chunk_was_forwarded_is_filtered`, `a_trailer_section_split_across_reads_is_filtered_in_each_part`, `a_trailer_walk_stops_at_the_blocks_queued_before_the_parse`, `trailer_elision_leaves_headers_and_responses_alone` (editor unit tests). The e2e tests are `test_h1_trailer_spoof_headers_dropped`, `test_h1_trailer_spoof_headers_dropped_split` (trailers in a separate write), `test_h1_trailer_spoof_headers_dropped_split_inside_trailers` (`X-Forwarded-For` in one write, the rest in the next) and `test_h1_pipelined_trailer_spoof_headers_dropped`. `handle_trailer_drops_each_spoof_header_individually` now iterates the shared list. RED, e2e on unfixed code: ``` TRAILER-SPOOF: FAIL — a spoofed forwarding trailer reached the backend test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped ... FAILED TRAILER-SPOOF-SPLIT: FAIL — a spoofed forwarding trailer reached the backend test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped_split ... FAILED test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 504 filtered out ``` RED, unit tests: `elide_request_trailer_spoof_vectors` stubbed to `return 0`, and pkawa restored to its old four-name `matches!`: ``` test protocol::mux::pkawa::tests::handle_trailer_drops_each_spoof_header_individually ... FAILED test protocol::kawa_h1::editor::tests::a_trailer_section_parsed_after_the_last_chunk_was_forwarded_is_filtered ... FAILED test protocol::kawa_h1::editor::tests::a_chunked_request_trailer_section_loses_its_spoof_vector_fields ... FAILED test protocol::kawa_h1::editor::tests::trailer_elision_leaves_headers_and_responses_alone ... ok trailer with only x-forwarded-proto should leave no surviving block test result: FAILED. 1 passed; 3 failed; 0 ignored; 0 measured; 1348 filtered out ``` RED, pipelined path: only the keep-alive call site in `mux/h1.rs` disabled: ``` TRAILER-SPOOF-PIPELINED: FAIL — a spoofed forwarding trailer reached the backend test tests::h1_security_tests::test_h1_pipelined_trailer_spoof_headers_dropped ... FAILED ``` RED, review items after the rebase: Walk ignoring `first_new_block` (`range_mut(0..)`). The function's own post-condition `debug_assert!` ("only blocks appended by the last parse are elided") fires before the test's assertion: ``` test protocol::kawa_h1::editor::tests::a_trailer_section_split_across_reads_is_filtered_in_each_part ... ok test protocol::kawa_h1::editor::tests::a_trailer_walk_stops_at_the_blocks_queued_before_the_parse ... FAILED test result: FAILED. 1 passed; 1 failed ``` Elision disabled (`return 0`): ``` test protocol::kawa_h1::editor::tests::a_trailer_section_split_across_reads_is_filtered_in_each_part ... FAILED assertion `left == right` failed: the first trailer part is filtered on its own left: 0 right: 1 TRAILER-SPOOF-SPLIT-INSIDE: FAIL — a spoofed forwarding trailer reached the backend test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped_split_inside_trailers ... FAILED ``` GREEN: ``` test protocol::mux::pkawa::tests::handle_trailer_drops_each_spoof_header_individually ... ok test protocol::kawa_h1::editor::tests::a_chunked_request_trailer_section_loses_its_spoof_vector_fields ... ok test protocol::kawa_h1::editor::tests::a_trailer_section_parsed_after_the_last_chunk_was_forwarded_is_filtered ... ok test protocol::kawa_h1::editor::tests::trailer_elision_leaves_headers_and_responses_alone ... ok test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped ... ok test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped_split ... ok test tests::h1_security_tests::test_h1_trailer_spoof_headers_dropped_split_inside_trailers ... ok test protocol::kawa_h1::editor::tests::a_trailer_section_split_across_reads_is_filtered_in_each_part ... ok test protocol::kawa_h1::editor::tests::a_trailer_walk_stops_at_the_blocks_queued_before_the_parse ... ok test tests::h1_security_tests::test_h1_pipelined_trailer_spoof_headers_dropped ... ok ``` ## Validation (each by its own exit code) - `cargo build --all-features`: 0 - `cargo clippy --all-features --all-targets -- -D warnings`: 0 - `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` (MSRV): 0 - `cargo +nightly fmt --all -- --check`: 0 - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`: 0 - `cargo test -p sozu-lib`: 0 (1381 passed) - `cargo test -p sozu`: 0 - `cargo test -p sozu-command-lib`: 0 - `cargo test -p sozu-e2e -- trailer h1_security mux_tests forward connection`: 0 (104 passed) - `check_doc_citations.py` `--self-test` / `--root .` / `--base origin/main` / `--audit --root .`: all 0 (the audit's three advisory findings are in files this PR does not touch) ## Residual risks - The advisory `Trailer:` request header still lists the dropped names. It is informational only, and this PR leaves it as sent. - An H2-frontend request forwarded to an H1 backend goes through `pkawa::handle_trailer`, not this walk. It uses the same list. - The bounded walk assumes kawa 0.7.2's invariants: parsing only appends blocks, and draining happens only from the front between parses. A debug post-condition guards this. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 29, 2026
…1694) ## Problem `UpdateHttpListenerConfig` / `UpdateHttpsListenerConfig` carry `elide_x_real_ip` and `send_x_real_ip`, and the workers apply them (`HttpListener::update_config` in `lib/src/http.rs`, and its HTTPS counterpart), but `ConfigState::update_http_listener` / `ConfigState::update_https_listener` (`command/src/state.rs`) never patched either field. On `origin/main` (`3ed6e8a6`; still true after #1686 re-keyed the listener maps): ``` $ git grep -n 'send_x_real_ip\|elide_x_real_ip' origin/main -- command/src/state.rs (no output) ``` So the main state kept the creation-time value: `sozu listener list` and `SaveState` showed it, and the state replayed to a new worker on upgrade/restart restored it, silently reverting the hot change. ## Fix Patch both flags in both functions, next to the other shared per-connection knobs (after `request_timeout`), with the same `if let Some(v)` form the worker uses. Absent fields preserve the recorded value. Control-plane only: no hot-path allocation or syscall. The insertion point is deliberately away from the tail of the two functions, where #1685 adds `forwarded_headers`, to keep rebasing trivial. ## Tests Rebased onto `05ac4f9c` (#1686 listener-by-interface, #1693). The field writes sit after `listener_key_for_update` resolves the listener, and the tests look listeners up by `ListenerKey::from(addr)`. RED/GREEN below re-run on the rebased tree. - `command/src/state.rs`: `update_http_listener_x_real_ip_patch_applied`, `update_http_listener_x_real_ip_absent_preserves_existing`, `update_https_listener_x_real_ip_patch_applied`, `update_https_listener_x_real_ip_absent_preserves_existing`, `update_listener_x_real_ip_survives_generate_requests_replay`. - `e2e/src/tests/tests.rs`: `test_x_real_ip_hot_update_survives_upgrade` — an HTTP listener starts with both flags off, a hot `UpdateHttpListener` turns both on, a spoofed `X-Real-IP: 1.2.3.4` request is checked on the old worker, then `Worker::upgrade` seeds a new worker from the harness's mirror `ConfigState` (the same `ConfigState::update_http_listener` the main process runs) and the same request is checked again. ### RED (fix reverted) ``` $ cargo test -p sozu-command-lib --locked x_real_ip test state::tests::update_https_listener_x_real_ip_patch_applied ... FAILED test state::tests::update_https_listener_x_real_ip_absent_preserves_existing ... FAILED test state::tests::update_http_listener_x_real_ip_absent_preserves_existing ... FAILED test state::tests::update_http_listener_x_real_ip_patch_applied ... FAILED test state::tests::update_listener_x_real_ip_survives_generate_requests_replay ... FAILED left: None right: Some(true) test result: FAILED. 0 passed; 5 failed; 0 ignored; 0 measured; 199 filtered out $ cargo test -p sozu-e2e --locked test_x_real_ip_hot_update_survives_upgrade test tests::tests::test_x_real_ip_hot_update_survives_upgrade ... FAILED after upgrade: spoofed X-Real-IP was not elided: left: Fail right: Success test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 506 filtered out ``` (The e2e "before upgrade" check passes on `main`: the worker applies the patch; only the upgraded worker reverts it.) ### GREEN ``` $ cargo test -p sozu-command-lib --locked x_real_ip test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 199 filtered out $ cargo test -p sozu-e2e --locked test_x_real_ip_hot_update_survives_upgrade test tests::tests::test_x_real_ip_hot_update_survives_upgrade ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 506 filtered out ``` ## Validation (each by its own exit code, all 0) - `cargo build --all-features` - `cargo clippy --all-features --all-targets -- -D warnings` - `cargo +nightly fmt --all -- --check` - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` - `cargo test -p sozu-command-lib` (204 passed), `cargo test -p sozu` (121 passed), `cargo test -p sozu-lib` (1358 passed) - e2e: `x_real_ip` (10 passed), `listener_update` (14 passed), `upgrade` (16 passed) - `check_doc_citations.py` `--self-test`, `--root .`, `--base origin/main`, `--audit --root .` ## Docs - `doc/configure.md`: the X-Real-IP section now states that the main state records the patch, so `listener list`, `SaveState` and upgrade replay carry it. - `CHANGELOG.md`: Unreleased / Fixed entry. ## Out of scope `sozu listener http|https update` exposes no CLI flag for either knob (only the protobuf patch does); unchanged here. Closes #1688 Signed-off-by: Florentin Dubois <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Sōzu added both forwarding header families (
X-Forwarded-*and RFC 7239Forwarded) to every forwarded request, unconditionally. This PR adds a per-listener enum for HTTP and HTTPS listeners:both(default)X-Forwarded-For,-Proto,-Port,ForwardedForwardedchains extended, client-Proto/-Portkeptx_forwardedX-Forwarded-For,-Proto,-Portbothfor that family;Forwardedpasses throughrfc7239ForwardedonlyForwardedextended (RFC 7239 §4);X-Forwarded-For/-Proto/-Port/-HostremovednoneDesign
enum ForwardedHeaders { BOTH = 0; X_FORWARDED; RFC7239; NONE }(command/src/command.proto:824).BOTH = 0means an absent field, or a state file written before this change, keeps today's behaviour. The field isoptional ForwardedHeaders forwarded_headersonHttpListenerConfig(36),HttpsListenerConfig(49),UpdateHttpListenerConfig(42) andUpdateHttpsListenerConfig(43). The TOML-sideForwardedHeadersMode(command/src/config.rs:1773) issnake_caseand uses theMetricDetailLevel↔MetricDetailpattern, becausebuild.rsputsSCREAMING_SNAKE_CASEon every prost enum.send_x_real_ippath throughL7ListenerHandler::get_forwarded_headers(lib/src/lib.rs:661,lib/src/http.rs:975,lib/src/https.rs:1423) andupdate_config, and is captured per stream inContext::create_stream(lib/src/protocol/mux/mod.rs:1206), likestrict_sni_binding. An H2 stream picks up a patch at its next HEADERS, an H1 connection when it opens (mux/LIFECYCLE.md§2.5). Unlikesend_x_real_ip/elide_x_real_ip, whichConfigState::update_http(s)_listenerdoes not apply (see Residual risks), the main-process state records the patched mode. The state (command/src/state.rs:874,999) and the worker (lib/src/http.rs:1460,lib/src/https.rs:1744) both runvalidate_forwarded_headers(command/src/state.rs:3226) and refuse an unknown wire value.lib/src/protocol/kawa_h1/editor.rs, shared by H1 and H2 frontends):emits_x_forwarded/emits_rfc7239/strips_x_forwarded(L240–L254) only gate emission: the chain extensions (L1324), the synthesis (L1343, L1395) and therfc7239elision branch (L1147).ForwardingHopstays mode-agnostic and renders every value once per connection. That keepssend_x_real_ipworking in every mode, keeps therenders()cache andreset()invariants unchanged, and keeps the allocation-count tests for the default path unchanged.X-Real-IPis injected at the same position as before, sobothstays byte-exact (header_editing_output_is_byte_exact_across_keep_alive_requestsis unchanged and green). A debug postcondition (L1478) checks thatrfc7239forwards no managedX-Forwarded-*header.xff_chain(access log) is still recorded in every mode. Thehttp.trusting.x_{proto,port}counters count only inbothandx_forwarded.X-Forwarded-Hostonrewrite_host(lib/src/protocol/mux/router.rs:1539): injected, replacing a client one, only inbothandx_forwarded. Inrfc7239andnonenothing is injected, and undernonea clientX-Forwarded-Hostpasses through as sent. Sōzu'sForwardedelement keeps its current parameters (proto,for,by); adding RFC 7239 §5.3host=would change the wire format for every rewrite, so it is left as a possible follow-up. As a result the pre-rewrite authority is not conveyed inrfc7239, which the docs state.X-Real-IPindependence:elide_x_real_ip/send_x_real_ipare untouched by the mode.X-Real-IPbelongs to neither family, andsend_x_real_ip = truestill injects it undernoneandrfc7239. Unit and e2e tests assert this.pkawa::handle_traileralready dropsX-Forwarded-For,ForwardedandX-Real-IPfrom trailer blocks in every mode.sozu listener {http,https} {add,update} --forwarded-headers <both|x_forwarded|rfc7239|none>(clapValueEnumwith the TOML spellings).listener listshows the mode, and the patch audit diff renders it by name.What "strict" means for
rfc7239In
rfc7239mode, client-suppliedX-Forwarded-For,X-Forwarded-Proto,X-Forwarded-PortandX-Forwarded-Host(the four Sōzu itself manages) are elided. They are neither passed through nor converted. The reasons:RFC 7239 §8.1 (Header Validity and Integrity): the header "cannot be relied upon to be correct, as it may be modified, whether mistakenly or for malicious reasons, by every node on the way to the server, including the client making the request". Its caveat that "the chain of IP addresses listed before the request came to the proxy cannot be trusted" applies equally to
X-Forwarded-*.Pass-through would be weaker than today. In this mode Sōzu no longer appends its hop to
X-Forwarded-For, so a backend still reading the rightmostX-Forwarded-Forwould trust a client-forged value with nothing Sōzu wrote after it. Elision leaves the backend one forwarding family, whose last element is Sōzu's.No §7.4 conversion. RFC 7239 §7.4 (Transition) only encourages converting
X-Forwarded-*intoForwarded"if it can be done in a sensible way". It warns that when severalX-Forwarded-*fields coexist "it may not be possible to do a conversion, since it is not possible to know in which order the already existing fields were added". Converted elements would also be exactly as untrusted as the originals.RFC 7239 §4 lets a proxy remove forwarding fields ("A proxy MAY remove all "Forwarded" header fields from a request"). Removing the non-standard family in a mode that promises the standard one is within that intent. The client
Forwardedchain itself is preserved and extended, following §4 ("append it to the last existing "Forwarded" header field after a comma separator") and §7.2 ("A directly forwarded request should preserve and possibly extend it").RFC 7239 §7.1 (HTTP Lists): a list "may be split over multiple header fields", so several
Forwardedlines form one list. Appending Sōzu's element to the last clientForwardedline therefore extends the whole list, which is why the editor keeps only the lastForwardedheader it sees. The same list semantics are whyrfc7239elides every clientX-Forwarded-Forline, not only the last (the editor unit test sends two).Other
X-Forwarded-*names (for exampleX-Forwarded-Prefix) are not attestations Sōzu manages and pass through in every mode.noneis the RFC 7239 §8.2 (Information Leak) option of "preventing the internal nodes from updating the HTTP header field", for operators who do not want Sōzu to disclose the peer or its own address.In
x_forwardedmode a clientForwardedpasses through untouched. The owner's decision was that this mode keeps exactly the current handling of the family it emits. The docs carry the same trust caveat for it as fornone.Review follow-ups (folded into this commit)
Forwarded: MEDIUM, fixed. Inbothandrfc7239, a client line such asForwarded: for="6.6.6.6(unclosed quoted-string) was extended intofor="6.6.6.6, proto=http;for="10.0.0.1:54321";by=127.0.0.1. That swallowed Sōzu's element, and I reproduced it in both modes, so the bug predates this PR inboth. The client value is now checked against the RFC 7239 §4 grammar byis_valid_forwarded(lib/src/protocol/kawa_h1/editor.rs): a list of;-separatedtoken=valuepairs, where a value is a token or an RFC 9110 §5.6.4 quoted-string. Empty list elements and OWS around,/;are tolerated, as RFC 9110 §5.6.1 asks of recipients. A malformed line is elided, which RFC 7239 §4 permits. Sōzu's element then goes to an earlier well-formed line or into a synthesisedForwarded, so it is always parseable and last.both: it is the other mode that extends the chain and had the same corruption. Well-formed input is byte-identical; every existing byte-exact editor test is unchanged and green.x_forwardedandnone: they do not touchForwarded, so the line passes through as sent.a_malformed_client_forwarded_is_elided_where_the_chain_is_extended(the probe input, plus a well-formed line followed by a malformed one) andis_valid_forwarded_follows_the_rfc7239_grammar(unit), andtest_forwarded_headers_rfc7239_malformed_client_forwarded_h1(e2e).pkawa::handle_trailernow also dropsx-forwarded-proto,x-forwarded-portandx-forwarded-host. The drop is unconditional, matching the existing semantics there: every header the initial-HEADERS pass rewrites is dropped from trailers regardless of listener flags, and in every mode each of these three is either synthesised (both/x_forwarded) or removed (rfc7239), so a trailer copy is a spoof vector in all of them. Test:handle_trailer_drops_each_spoof_header_individually, extended.validate_forwarded_headersnow runs onAddHttpListener/AddHttpsListenerinConfigState::add_http(s)_listener(before anything is stored) and in the worker'sHttpListener::new/HttpsListener::try_new. Tests:add_listener_rejects_an_unknown_forwarded_headers_value(state), anda_listener_with_an_unknown_forwarded_headers_value_is_refused(http.rs and https.rs).Follow-up RED, then GREEN:
true(the pre-fix behaviour):a_malformed_client_forwarded_is_elided_where_the_chain_is_extended ... FAILEDwith left["for=\"6.6.6.6, proto=http;for=\"10.0.0.1:54321\";by=127.0.0.1"], right["proto=http;for=\"10.0.0.1:54321\";by=127.0.0.1"]; the grammar test also FAILED. With the fix: bothok.test_forwarded_headers_rfc7239_malformed_client_forwarded_h1 ... FAILED. Restored:ok.trailer with only x-forwarded-proto should leave no surviving block ... FAILED. After:ok(all 4handle_trailertests).called Result::unwrap_err() on an Ok value ... FAILED. After:ok.a_listener_with_an_unknown_forwarded_headers_value_is_refusedFAILED (an unknown mode must be refused). After:ok.Tests (seen RED, then GREEN)
RED runs were produced by removing the behaviour under test (for the editor, before the gating existed; otherwise by temporarily reverting the named line), never by a compile error.
Editor, before gating (
bothpasses from the start because it pins today's behaviour):After gating:
test result: ok. 5 passed; 0 failed.Router, with
synthesises_xfh = rewriting_hostalone:a_host_rewrite_discloses_x_forwarded_host_only_in_x_forwarded_modes ... FAILED(left:[b"rewrite.example.com"], right:[]). Restored:ok.Config, with
to_http/to_tlsnot setting the field:forwarded_headers_parses_every_mode_defaults_to_both_and_rejects_others ... FAILED(left(None, None), right(Some(0), Some(0))). Restored:ok. The test also covers every spelling, the absent key (both) and serde'sunknown varianterror forRFC7239,x-forwarded,forwardedand"".State, without the patch arm:
update_listener_forwarded_headers_applies_and_rejects_unknown_values ... FAILED(leftBoth, rightRfc7239). Restored:ok.CLI, without
#[value(name = "x_forwarded")]:listener_https_update_parses_forwarded_headers ... FAILED. Restored:ok.e2e, without
http_context.forwarded_headers = listener.get_forwarded_headers()inContext::create_stream:The
*_h1backend cells pass here because, as for the existing X-Real-IP matrix feature,AsyncBackendexposes no request bytes; those cells only check forwarding. The H2 frontend is proved byh2_h2. Without the worker'supdate_configarm,test_forwarded_headers_hot_changefails withpatch_ok=true before_ok=true after_ok=false. Restored:test result: ok. 7 passed; 0 failed.Validation
Run on head
1076a246, rebased ontoorigin/maind9ce2a02(after #1686):cargo build --all-features: exit 0cargo clippy --all-features --all-targets -- -D warnings: exit 0cargo +nightly fmt --all -- --check: exit 0RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked: exit 0cargo test -p sozu-lib: exit 0 (1368 passed; 0 failed)cargo test -p sozu: exit 0 (122 passed)cargo test -p sozu-command-lib: exit 0 (202 passed)forward(23),x_real_ip(9),listener_update(15),listener(28),protocol_pair_matrix(28),trailer(5)python3 .github/scripts/check_doc_citations.py--self-test,--root .,--base origin/mainand--audit --root .: all exit 0508 passed; 0 failed) was run on the previous heada339a456, before feat(listener): bind listeners to a network interface #1686Rebase onto #1686 (listener
interface):command.proto: feat(listener): bind listeners to a network interface #1686 took field numbers 35 (HttpListenerConfig) and 48 (HttpsListenerConfig) forinterface, the numbers this PR had used.interfacekeeps them, andforwarded_headersmoves to 36 and 49. The Update messages keep 42 and 43. No release has shipped the old numbers.state.rs:add_http(s)_listenerkeeps feat(listener): bind listeners to a network interface #1686'svalidated_listener_keyand runsvalidate_forwarded_headersbefore it.cli.rs/request_builder.rs: both new CLI tests are kept, and theaddbuilders chain.with_interface(interface)after the optionalwith_forwarded_headers.CHANGELOG.md: both new entries are kept.doc/configure_admin_ops.md: kept this PR's symbol citation in place of the renumberedhttps.rs:515.interface: Nonein itsActivateListener, as feat(listener): bind listeners to a network interface #1686 did for the sibling helpers.Docs
doc/configure.md(new "Forwarding headers" section with the security note and trust caveat, an updatable-fields row, and thesend_proxyparagraph),doc/configure_admin_ops.md(patch boundary list),doc/lifetime_of_a_session.md,lib/src/protocol/kawa_h1/LIFECYCLE.md§2 and §4,lib/src/protocol/mux/LIFECYCLE.md§2.5 capture table,bin/config.toml(both listener examples),e2e/COVERAGE.md, andCHANGELOG.md(Unreleased).Residual risks
rfc7239andnone, arewrite_hostconveys no pre-rewrite authority. The RFC 7239 §5.3host=parameter is the natural follow-up.none(and forForwardedunderx_forwarded) is documented, not enforced.X-Real-IP,X-Forwarded-ForandForwardedincluded); only H2 trailers are filtered.ConfigState::update_http(s)_listenerdoes not applyelide_x_real_ip/send_x_real_ippatches, so after a hot update the main-process state (listener list,SaveState, upgrade replay) still shows the old values for those two knobs.forwarded_headersis applied there.Closes #322