Skip to content

fix(socket): render the session peer in a TLS frontend's SOCKET line - #1364

Merged
FlorentinDUBOIS merged 3 commits into
mainfrom
fix/tls-socket-log-peer
Sep 20, 2026
Merged

FlorentinDUBOIS merged 3 commits into
mainfrom
fix/tls-socket-log-peer

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Completes the one divergence #1360 (c8f8b92f) documented rather than fixed.

The divergence

#1360 stopped the H2 log macros from calling a live getpeername(2) per expansion, added
SocketHandler::peer_addr() and gave FrontRustls the configured_peer field it was the only
handler to lack. It left the SOCKET line of a TLS frontend still showing the kernel's peer, and
recorded that in doc/observability.md as a follow-up — because nothing asserted the peer= slot of
a SOCKET line.

So on a PROXY-protocol HTTPS frontend the MUX-H2 line named the client and the SOCKET line named
the load balancer, for one and the same connection.

The split fell along the handler, not the layer: log_socket_context! has exactly one production
caller, impl SocketHandler for FrontRustls, whose expansions are every SOCKET line a TLS frontend
emits. Every plaintext frontend and every backend socket reaches the free function
log_socket_module_prefix, which already preferred the cached address.

The change

-            peer = $self.socket_ref().peer_addr().ok(),
+            peer = crate::socket::SocketHandler::peer_addr($self),

Same cached-then-live preference as the rest of the stack. local, rtt, state and protocol are
untouched and the format! template is not in the diff.

Written fully qualified deliberately, against a latent hazard. No current expansion sits on a raw
mio::TcpStream — all of them are in the FrontRustls impl, which has no inherent peer_addr — so
the unqualified $self.peer_addr() compiles and behaves identically today. The qualification exists
so that a future expansion on a raw stream cannot silently pick up mio's inherent
TcpStream::peer_addr and render an io::Result where every other slot renders an Option.
Measured with a throwaway probe: expanding the macro on a bare mio::TcpStream renders
peer=Ok(127.0.0.1:43441) beside local=Some(..).

Tests — this is where the work is

A one-word change that nothing asserts is precisely the failure mode this repository has been burned
by, so both directions are pinned.

e2e tests::socket_log_context_tests::test_tls_socket_log_peer_is_the_advertised_client:
PROXY-v2 → TLS (ALPN h2) → h2_handshake (proving the mux holds a FrontRustls) → one undecryptable
TLS record written straight onto the socket, bypassing rustls.

That provocation is load-bearing for which half is proven. It lands on process_new_packets's
DecryptError arm while the connection is still ESTABLISHED, so the live lookup succeeds and is
simply wrong. A provocation that killed the connection first would still redden the first
assertion — peer=None is also "not the advertised client" — but it would not exercise the second,
raw_peer_lines != 0, which is the one that discriminates this fix from the ENOTCONN half #1360
already covered. Note also that every log_socket_context! expansion is an error!, so
a healthy TLS session emits no SOCKET line at any level: raising the level cannot help, the test
has to provoke.

[RED, unfixed tree]
TLS SOCKET peer - stopped=true, SOCKET lines=1, with a peer= slot=1,
  advertised(peer=Some(127.0.0.1:9974))=0, raw(peer=Some(127.0.0.1:40328))=1
ERROR TLS-SOCK-PEER	[...]	SOCKET	Session(peer=Some(127.0.0.1:40328), local=Some(127.0.0.1:20000),
  rtt=Some(643µs), state=Some("ESTABLISHED"), protocol=Tls1_3)	 >>> could not process read TLS packets: DecryptError
test result: FAILED. 0 passed; 1 failed

[GREEN, all 3 repeat_until_error_or iterations]
TLS SOCKET peer - ... advertised=1, raw=0   (x3)
test result: ok. 1 passed; 0 failed

unit socket::tests::log_socket_context_renders_the_cached_peer_not_a_live_lookup expands the
macro over a live loopback connection whose cache disagrees with the kernel, and also asserts local=
is still getsockname(2) — the scope guard for "peer only".

The production change introduces no string literal at all and the template carrying peer= is
unchanged, so the fix is not test-shaped.

Validation

BUILD=0 CLIPPY=0 TEST=0 FMT=0, test result: ok. 864 passed; 0 failed.
lib/tests/log_layout.rs green. The sibling
h2_log_context_tests::test_h2_proxy_protocol_peer_is_the_advertised_client re-run green to confirm
the MUX-H2 path was not disturbed.

One prose claim in doc/observability.md is labelled derived, not measured: that a SOCKET line
after a peer reset now carries the cached address instead of peer=None. The e2e test deliberately
keeps the connection ESTABLISHED, so it does not measure that; it follows from the slot now calling
the same accessor, whose fallback arm is covered by two pre-existing tests.

517 `file.rs:NNN` anchors across `bin/src/command/LIFECYCLE.md`,
`lib/src/protocol/kawa_h1/LIFECYCLE.md`, `lib/src/protocol/mux/LIFECYCLE.md`,
`lib/src/protocol/proxy_protocol/LIFECYCLE.md` and
`lib/src/protocol/udp/LIFECYCLE.md` were read against the code they point at.
310 did not need a line number and are now symbol anchors; of the 207 that
name a specific statement or branch, 171 had to be renumbered and 36 were
already right.

A line number has no anchor, so it rots the moment anyone edits above it, and
nothing resolves it: a mechanical scan for a missing target, a line past EOF or
a blank line flagged only 27 of the 517. The two drift patterns measured in
issue #1335 account for nearly all of the rest — single-line anchors off by +1
from the `//!` module-doc line added at the top of each source file after the
documents were written, and ranges off by tens to thousands of lines from the
TigerStyle `debug_assert!` campaign and the growth of
`lib/src/protocol/mux/h2.rs`, where the drift reaches +2165.

The convention now matches `lib/src/protocol/tcp_preread/LIFECYCLE.md`, which
was already written this way and is why it needed no repair. Where the prose
names an item the anchor is that item plus its file, with a method qualified
`Type::method` so it is greppable; a line or range survives only where the
claim is about a statement or a branch inside an item. Bare basenames that were
ambiguous repo-wide (`server.rs`, `backends.rs`, `upgrade.rs`) are now
repo-root-relative. Each of the five preambles states the convention and the
date the surviving numbers were refreshed.

No prose claim was rewritten to match code. Four stale claims surfaced on the
way — `Server::run`, `upgrade_main`'s file, `ListenerAnswers` / `ClusterAnswers`
and the mux "inline removal" list — and are anchored correctly but left for a
separate pass. `doc/` is untouched.

Rebased onto 95c5f37 (#1369), whose H2 timer-ownership move drifted five more
citations in these same documents. Four were caught by the guard landing in
#1371 -- `editor.rs:561-621`, `h2.rs:6045-6047` and `manager.rs:555-567` twice,
each now resolving to a blank line -- and are re-anchored on
`HttpContext::on_request_headers`, the three `ConnectionH2` frame handlers that
decrement `active_requests`, and `UdpManager::handle_timeout`.

The fifth the guard cannot see, and it is the more instructive one:
`shrink_trailing_recycle`'s "single call site at `mod.rs:616`" now lands on
`HttpContext::new`, 58 lines short of the real call at `mod.rs:674`. A citation
that drifts onto a different non-blank line passes the check -- the checker says
so in its own output -- which is why the anchor is now `Mux::create_stream`.

The rebase also took the `mux/LIFECYCLE.md` backend-timeout tracker from
95c5f37, whose description is current, but symbolised its two citations rather
than keeping either side's numbers: `mod.rs:773` had come to land on unrelated
doc prose and `mod.rs:1279` on a `gauge_add!` call.

Refs #1335

Signed-off-by: Florentin Dubois <[email protected]>
A line number carries no anchor, so a `file.rs:NNN` citation rots the moment
anyone edits the file it points into. The pull request that breaks it is almost
never the pull request that contains it, so no reviewer is ever shown both
halves. #1335 measured 29 of 35 citations wrong in one audited
document.

Add `.github/scripts/check_doc_citations.py` and wire it as the
non-experimental `Doc citations` CI cell. It resolves every citation under
`doc/**` and `**/LIFECYCLE.md` and fails on a missing file, an ambiguous
basename, a line below 1 or past end of file, a blank line at either end of a
range, an inverted range, or the same line repeated inside one citation group --
the last being what a `/` or `,` continuation renumbered on one half only looks
like. Its extraction pattern keeps a digit in the character class, without which
every citation naming a file whose name contains one is skipped: on
`lib/src/protocol/mux/LIFECYCLE.md` the digitless class sees 78 of the 201
occurrences that are there. A cited path resolves against the document's own
directory first, so a module `LIFECYCLE.md` keeps citing its siblings by bare
name.

`--self-test` asserts the exact failures a deliberately broken fixture must
produce, and the exact citation total, and -- because classifying a failure and
acting on it are different lines -- runs the real command line in a subprocess
requiring exit 1 on that fixture and exit 0 on a clean one. The cell asserts
that exit code in a step of its own. The fixtures carry a digit-bearing `h2.rs`
and a `mod/LIFECYCLE.md` whose citations resolve only through the
sibling-directory rule, so each of the four one-line ways to make this checker
report a clean run over a quietly smaller surface -- `if failures:` -> `if
False:`, dropping the digit from the pattern, dropping `**/LIFECYCLE.md` from
the scan, dropping sibling-directory resolution -- fails the self-test.

Repair `doc/`: all 106 citation groups across 9 files were read against the code
they point at. 74 became symbol anchors, which cannot drift; of the 32 that
survive as line anchors, 24 were renumbered and 8 were already right. Five
landed on a blank line -- the only class a mechanical scan sees. The rest
resolved to a valid line in the wrong place, which is what actually misleads a
reader and what the checker cannot catch: `doc/README.md` now states that limit,
and the two narrower ones, next to the local run instructions.

Correct three stale citations outside the guarded surface, where nothing will
catch them later: `CLAUDE.md`'s logging bullet cited ten surviving
`macro_rules!` definition sites and every one had moved, `socket.rs:86/133`
included -- a trait method declaration and a line inside a macro body.
`command/src/channel.rs` and `bin/README.md` cited a UDP-frontend invariant
comment and a `ChannelError` variant for the state-file save format and the
`max_buffer_size` ceiling. The comment in `lib/src/protocol/mux/h2.rs` pointing
at the inbound `stream_last_activity_at` refreshes named SETTINGS-ACK tracking
instead of `handle_data_frame` and `handle_headers_frame`; it is rewritten at
its original line count, because two anchors elsewhere name lines below it.

No prose claim was rewritten to match the code; four that have gone stale are
recorded in the changelog entry instead. Line anchors were refreshed against
`main` at `ba7fa5f9` on 2026-09-20.

Signed-off-by: Florentin Dubois <[email protected]>
`log_socket_context!` built its `peer=` slot from
`$self.socket_ref().peer_addr().ok()` — a live `getpeername(2)` — while its
module-level twin `log_socket_module_prefix` already preferred the address the
handler had cached. The split fell along the handler, not the layer: the macro
has exactly one production caller, `impl SocketHandler for FrontRustls`, whose
thirteen expansions are every SOCKET line a TLS frontend emits, while every
plaintext frontend and every backend socket reaches the free function through
`SessionTcpStream`.

So on a PROXY-protocol HTTPS frontend the MUX-H2 line named the client and the
SOCKET line named the load balancer, for one and the same connection. That was
an artefact of `FrontRustls` having carried no cached address before
`SocketHandler::peer_addr` and `FrontRustls::configured_peer` landed, not a
deliberate split; `doc/observability.md` recorded it as a follow-up rather than
fixing it, because nothing asserted the `peer=` slot of a SOCKET line.

The slot is now `SocketHandler::peer_addr`, same cached-then-live preference as
the rest of the stack. It is spelled as a fully-qualified trait call to
foreclose a latent hazard, not to fix a present one: `$self.peer_addr()`
compiles clean today and passes every test, because no current expansion sits
on a raw `mio::TcpStream` and `FrontRustls` has no inherent `peer_addr` for
method resolution to prefer. Add an expansion on a bare `TcpStream` and the
unqualified form silently picks mio's inherent method — measured on a probe,
that slot renders `peer=Ok(127.0.0.1:33587)` beside `local=Some(..)`, an
`io::Result` where every other expansion renders an `Option`. `local`, `rtt`,
`state` and `protocol` are untouched.

The missing assertions are the substance of the change, and there are three.
Two unit tests pin the macro's slot, one per half of the defect:
`socket::tests::log_socket_context_renders_the_cached_peer_not_a_live_lookup`
covers a live lookup that succeeds and disagrees, and also asserts `local=`
stays `getsockname(2)`;
`socket::tests::log_socket_context_renders_the_cached_peer_when_the_live_lookup_fails`
covers one that fails, staged with a never-connected socket because only that
refuses `getpeername(2)` deterministically — a socket waiting on an RST is a
race this suite already declines to assert on. Against the pre-fix macro they
render the loopback address and `peer=None` respectively.

`e2e::tests::socket_log_context_tests::test_tls_socket_log_peer_is_the_advertised_client`
drives a real PROXY-v2 header through the real accept path. It provokes rather
than raises a level — the opposite of its MUX-H2 sibling — because every
`log_socket_context!` expansion is an `error!` and a healthy TLS session emits
no SOCKET line at any level: it corrupts one TLS record once the mux is
established. Keeping the connection ESTABLISHED, now asserted rather than
assumed, is what makes the negative assertion discriminate: only while
`getpeername(2)` still succeeds can a slot name the raw TCP peer. Measured
against the unfixed tree: 1 SOCKET line, 0 naming the advertised client, 1
naming the raw TCP source.

The same edits shifted `lib/src/socket.rs` by +13 lines at `udp_connect`, which
moved `udp/LIFECYCLE.md`'s `socket.rs:1081-1083` anchor onto a blank line. That
anchor never pointed at `udp_connect`: on `origin/main` those lines are a
`BrokenPipe` arm inside `FrontRustls::socket_write`, so this was pre-existing
rot that the shift merely made detectable. Re-anchored to the symbol the prose
already names, per `doc/README.md#citing-code-from-these-documents` — a symbol
survives every edit above it. Spelled identically to the same line on
`docs/lifecycle-citation-repair` so the two land without a conflict.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit e9804c7 into main Sep 20, 2026
24 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/tls-socket-log-peer branch September 20, 2026 20: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.

1 participant