Repository navigation
fix(h2): render the session peer, not a live getpeername(2) - #1360
Merged
Merged
Conversation
The two `log_context!` macros in `lib/src/protocol/mux/h2.rs` built their `peer=` slot from `$self.socket.socket_ref().peer_addr().ok()` — a live `getpeername(2)` on every expansion. Two defects follow from that, and the first is the one that bites during an incident. `getpeername(2)` answers `ENOTCONN` once the peer has reset, so the lines that render `peer=None` are exactly the error lines an operator reads when something has gone wrong. The address is least available precisely when it matters most. Second, the raw socket is the wrong address behind PROXY protocol. `upgrade_expect` already adopts the PROXY-advertised source into the session's `peer_address`, and the plaintext side already threads that into `SessionTcpStream::configured_peer`, but the H2 macros read past both. For one request id the `HTTPS` line named the client and the `MUX-H2` line named the load balancer. `SocketHandler` gains `peer_addr()`, implemented for all three handlers, and `FrontRustls` gains the `configured_peer` field it was the only handler to lack. The trait method has no default body on purpose: a new handler must decide what its peer is rather than inherit a live lookup by omission. Every implementation falls back to `getpeername(2)` when it holds nothing cached, so no working `peer=` becomes `None`. `FrontRustls` is seeded from `self.peer_address` and NOT from `stream.peer_addr()`. That is one word and it is the whole fix: the raw form compiles, passes every other test in the repository, and silently leaves the PROXY defect in place. Measured — with the substitution applied, the suite is green except the one test written for it, and green outright when that test is filtered out. BEHAVIOUR: this changes rendered log content on `MUX-H2` lines, in three ways enumerated in `CHANGELOG.md`. Anyone alerting on the `peer=` slot should read that entry. No wire byte, metric, control-flow decision or log layout changes, and `lib/tests/log_layout.rs` makes no `peer` assertion. Nothing changes on a plaintext frontend. `Connection::new_h2_server` has exactly one caller, on the TLS ALPN branch, and h2c is deliberately unimplemented on the cleartext listener, so a `MuxClear` session has no `MUX-H2` frontend line to change; it renders through `MUX-H1`, untouched here. An earlier draft of this changeset told operators otherwise, and cited as its evidence a line whose immediate neighbour refutes it. The `SOCKET` line of a TLS frontend still shows the kernel's peer, so on a PROXY frontend it disagrees with the `MUX-H2` line. That is an artefact of `FrontRustls` having carried no cached address until now, not a deliberate split between layers — every other `SOCKET` line already prefers `configured_peer`. Aligning it needs its own test, because nothing currently asserts that slot. Seven tests, each seen red under a named mutation. One of them exists solely to catch the seeding substitution above; another guards the fallback arm, whose doc comment used to call it unreachable — it is reachable on the direct route, where the accept-time `peer_addr()` is best-effort. `e2e/COVERAGE.md` records why this has no end-to-end test: the fix moves no wire byte, so a log line is its only observable, and the e2e harness cannot assert on log content. The worker's log target and level are hardcoded, the stdout backend bypasses the capture libtest reads, and the logger is thread-local with a one-shot guard. The note names the change that would falsify it, and warns against the obvious wrong implementation: the UDP drain used by the unit-test helper only reads after the run and would silently drop lines at H2 volume. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 19, 2026 15:16
This was referenced Sep 20, 2026
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 25, 2026
## The defect `log_context!` and `log_context_lite!` (`lib/src/protocol/mux/mod.rs`) built their `peer=` slot as: ```rust peer = $self.frontend.socket().peer_addr().ok(), ``` `$self.frontend` is a `Connection<Front>`, and `Connection::socket()` (`lib/src/protocol/mux/connection.rs`) returns a **mio** `&TcpStream`, obtained through `SocketHandler::socket_ref`. A concrete `&mio::net::TcpStream` has an *inherent* `peer_addr`, and an inherent method wins method resolution over a trait method — so that slot resolved to mio's live `getpeername(2)` returning `io::Result<SocketAddr>`, and **never** reached `SocketHandler::peer_addr` at all. Measured on the tree, both symptoms reproduce: - after the peer's RST, `getpeername(2)` answers `ENOTCONN`, so `.ok()` yields `None` and the `error!` lines an operator reads during an incident render `peer=None`; - on a PROXY-protocol frontend the advertised source (cached in `configured_peer` / `FrontRustls`' field) is ignored, so the `MUX` line names the load balancer while the `HTTPS` and `SOCKET` lines name the real client — for the same ULID. This is the same defect class already corrected three times — by #1360 for the `h2.rs` macros, `504f0528` for `log_socket_context!` in `lib/src/socket.rs`, and #1524 for the `h1.rs` macros. `mod.rs` was left behind by all three, because it holds a `Connection` rather than a core and `Connection` exposed no route to the snapshot the cores already carry. ## The fix `ConnectionH1::peer_address` and `ConnectionH2::peer_address` already exist — an `Option<SocketAddr>` filled once at construction from `SocketHandler::peer_addr`. The only thing missing was an accessor on `Connection`. New `Connection::peer_address`, built on the existing `forward!` macro exactly like `readiness()` and `position()`: ```rust pub fn peer_address(&self) -> Option<SocketAddr> { *forward!(&self, peer_address) } ``` Both macro definitions now interpolate `$self.frontend.peer_address()`. All **52** expansions — 34 `log_context!`, 18 `log_context_lite!` — go through those two definitions, so **no callsite changed**. Reading the field rather than calling the trait per line preserves the property `log_context_reads_the_peer_address_once_per_connection` pins one layer down: rendering a `MUX` line now costs no socket access at all, and it cannot drift from what the per-protocol envelopes print for the same session. ### Why the `h2.rs` hunk is one keyword `lib/src/protocol/mux/h2.rs` carries **one line, zero line delta**: `peer_address` widens from private to `pub(super)`, the visibility `ConnectionH1::peer_address` already carried. `Connection::peer_address` is its only reader outside `h2.rs`. It is kept to a single keyword with no added doc comment on purpose. Any line inserted in `h2.rs` shifts the pinned code blocks in `doc/h2_mux_internals.md` and breaks `check_doc_citations.py` — measured on this branch: a 5-line doc comment broke 8 of 16 pinned blocks. The rationale lives on the accessor in `connection.rs` instead. For the same reason the production hunks in `lib/src/protocol/mux/mod.rs` are three **one-line substitutions** with zero line delta: `LIFECYCLE.md` and `doc/testing.md` pin 33 citations into that file, and a 5-line bullet shifted every one of them. This branch was rebased onto `fa11f549` (#1534) after that merged; the rebase was clean and the whole battery below was re-run on the rebased tree, not carried over from the earlier base. ## Behaviour change This changes rendered log content. A rule matching `peer=None` on a `MUX` line to detect a reset stops firing, and grouping a dashboard by `peer=` may see a large cardinality increase behind a PROXY-protocol frontend. No wire byte, metric, control-flow decision or log *layout* changes. `doc/observability.md` and `CHANGELOG.md` are updated in the same changeset. ## Regression tests, seen red Two tests in `lib/src/protocol/mux/mod.rs`: - `log_context_renders_the_snapshotted_peer_not_a_live_lookup` - `log_context_lite_renders_the_snapshotted_peer_not_a_live_lookup` Both assert the rendered **value**, not a call count. A counting `SocketHandler` cannot discriminate here: before the fix the macros never reached `SocketHandler::peer_addr`, so a counter reads zero on both sides of the change and the test would be green either way. The frontend snapshots `10.0.0.42:12345` while its socket is genuinely connected to a live loopback listener, and each test asserts that healthy, *disagreeing* live lookup as an explicit premise so it cannot pass for the wrong reason. **To SEE THIS RED** (the recipe is also a comment on each test): in `log_context!` / `log_context_lite!` (`mod.rs`), put `peer = $self.frontend.socket().peer_addr().ok(),` back in place of `peer = $self.frontend.peer_address(),`. Both were run red before the fix, green after, red again with production reverted to the base revision, and green again on restore: ``` # before the fix log_context_renders_the_snapshotted_peer_not_a_live_lookup ... FAILED the MUX peer= slot must render the snapshotted address; rendered: [01M3CS1YZNCC63SVXQPMDGE942 - - -] MUX Session(frontend=0, peer=Some(127.0.0.1:39001), streams=0, ...) log_context_lite_renders_the_snapshotted_peer_not_a_live_lookup ... FAILED the lite MUX peer= slot must render the snapshotted address; rendered: [01M3CS1YZNA4S0XVJZ0WVX0H4Q - - -] MUX Session(frontend=0, peer=Some(127.0.0.1:37353), readiness=...) # after the fix test result: ok. 2 passed; 0 failed ``` A grep of the production diff (connection.rs + h2.rs + the mod.rs hunks above the tests module) for every literal shared with the test fixture — `10.0.0.42`, `12345`, `SNAPSHOT_PEER`, the two test names, `connected_loopback_stream`, `mux_with_snapshotted_peer`, `live_peer`, `127.0.0.1`, `SessionTcpStream`, `TestListener`, `Pool::with_capacity` — returns 0 for each. `peer_address` appears on both sides by necessity: it is the field and accessor under test, not a shared fixture. ## Validation Base: `fa11f549c02722a378b983a0b3cb716187f54e14` (#1534, merged). | Command | Result | |---|---| | `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd` | exit 0 | | `cargo +nightly fmt --all -- --check` | exit 0 | | `cargo clippy --all-targets --locked --no-default-features --features … -- -D warnings` | exit 0 | | `cargo test -p sozu-lib --locked --no-default-features --features …` | 1141 passed, 0 failed | | `cargo test -p sozu --locked --no-default-features --features …` | 113 passed, 0 failed | | `cargo test -p sozu-e2e --locked --no-default-features --features … -- --skip tests::fuzz_tests::` | 447 passed, 0 failed | | `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` | 30 passed, 0 failed | | `RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings` | exit 0 | | `check_doc_citations.py --self-test` | exit 0 | | `check_doc_citations.py --root .` | exit 0 | | `check_doc_citations.py --base fa11f54` | exit 0, 0 of 256 citations drifted | | `check_doc_citations.py --audit --root .` | exit 0 | | `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` | exit 0 | ## Scope This PR closes no issue. It handles one part of the `MUX`-family log-context work; **#1341 remains open**, and its remaining Q4 item is a different piece of work — #1534 landed one instalment of it and the rest continues on its own branch. 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.
Answers Q5 of #1341. Q4 of that issue is decided and correctly blocked on #1340; nothing here touches it.
The two
log_context!macros inlib/src/protocol/mux/h2.rsbuilt theirpeer=slot from$self.socket.socket_ref().peer_addr().ok()— a livegetpeername(2)on every expansion.Defect 1: the address vanishes exactly when it matters.
getpeername(2)answersENOTCONNonce the peer has reset, so the lines renderingpeer=Noneare the error lines an operator reads during an incident.Defect 2: the raw socket is the wrong address behind PROXY protocol.
upgrade_expectalready adopts the PROXY-advertised source into the session'speer_address, and the plaintext side already threads it intoSessionTcpStream::configured_peer— the H2 macros read past both. For one request id theHTTPSline named the client and theMUX-H2line named the load balancer.The fix
SocketHandlergainspeer_addr(), implemented for all three handlers, andFrontRustlsgains theconfigured_peerfield it was the only handler to lack. The trait method has no default body on purpose: a new handler must decide what its peer is rather than inherit a live lookup by omission. Every implementation falls back togetpeername(2)when it holds nothing cached, so no workingpeer=becomesNone.FrontRustlsis seeded fromself.peer_address, notstream.peer_addr(). That is one word and it is the whole fix — the raw form compiles, passes every other test in the repository, and silently leaves defect 2 in place. Measured: with the substitution applied the suite is green except the one test written for it, and green outright when that test is filtered out.Behaviour — read this if you alert on
peer=This changes rendered log content, in three ways, all on
MUX-H2lines. The CHANGELOG carries the operator note; briefly:peer=Noneafter a reset becomes the cached address (a rule matchingpeer=Noneto detect resets stops firing); a PROXY-protocol HTTPS frontend shows the real client instead of the balancer (which may be a large cardinality increase on a dashboard grouping bypeer=); and a backend-facing H2 connection shows the configured backend address where a failedconnect()leftpeer=None.No wire byte, metric, control-flow decision or log layout changes.
lib/tests/log_layout.rsmakes nopeerassertion.Nothing changes on a plaintext frontend, and an operator watching one should not go looking.
Connection::new_h2_serverhas exactly one caller,https.rs:702, on the TLS ALPN branch, and h2c is deliberately unimplemented on the cleartext listener (http.rs:710-728), so aMuxClearsession has noMUX-H2frontend line to change — it renders throughMUX-H1, untouched here.A known, documented inconsistency
The
SOCKETline of a TLS frontend still shows the kernel's peer, so on a PROXY frontend it disagrees with theMUX-H2line. That is an artefact ofFrontRustlshaving carried no cached address until now, not a deliberate split between layers — every otherSOCKETline already prefersconfigured_peer(socket.rs:177). Aligningsocket.rs:133is a one-word change that compiles and leaves the suite green, but nothing currently asserts thepeer=slot of aSOCKETline, so it would be an unguarded behaviour change on a second prefix. It belongs in its own changeset with its own test.Tests
Seven, each seen red under a named mutation. Lib suite 878 → 885. Two are worth naming: one exists solely to catch the seeding substitution above, and one guards the fallback arm whose doc comment used to call it unreachable — it is reachable on the direct route, where the accept-time
peer_addr()is best-effort (https.rs:229, andserver.rs:684says so).There is no e2e test, and
e2e/COVERAGE.mdrecords why. The fix moves no wire byte, so a log line is its only observable, and the harness cannot assert on log content: the worker's log target and level are hardcoded (worker.rs:164), the stdout backend bypasses the capture libtest reads, and the logger is thread-local with a one-shot guard. The note names the change that would falsify it, and warns off the obvious wrong implementation — the UDP drain used by the unit-test helper reads only after the run and would silently drop lines at H2 volume, producing exactly the load-sensitive flake this suite already has a family of.