Skip to content

fix(h2): render the session peer, not a live getpeername(2) - #1360

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-peer-addr-snapshot
Sep 19, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/h2-peer-addr-snapshot

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Answers Q5 of #1341. Q4 of that issue is decided and correctly blocked on #1340; nothing here touches it.

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.

Defect 1: the address vanishes exactly when it matters. getpeername(2) answers ENOTCONN once the peer has reset, so the lines rendering peer=None are the error lines an operator reads during an incident.

Defect 2: 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 it into SessionTcpStream::configured_peer — 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.

The fix

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, not 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 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-H2 lines. The CHANGELOG carries the operator note; briefly: peer=None after a reset becomes the cached address (a rule matching peer=None to 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 by peer=); and a backend-facing H2 connection shows the configured backend address where a failed connect() left peer=None.

No wire byte, metric, control-flow decision or log layout changes. lib/tests/log_layout.rs makes no peer assertion.

Nothing changes on a plaintext frontend, and an operator watching one should not go looking. Connection::new_h2_server has 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 a MuxClear session has no MUX-H2 frontend line to change — it renders through MUX-H1, untouched here.

A known, documented inconsistency

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 (socket.rs:177). Aligning socket.rs:133 is a one-word change that compiles and leaves the suite green, but nothing currently asserts the peer= slot of a SOCKET line, 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, and server.rs:684 says so).

There is no e2e test, and e2e/COVERAGE.md records 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.

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
FlorentinDUBOIS merged commit c8f8b92 into main Sep 19, 2026
23 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/h2-peer-addr-snapshot branch September 19, 2026 17:26
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant