Repository navigation
feat(tcp): SNI+ALPN ClientHello preread passthrough routing (#1279) - #1290
Conversation
Route TCP connections by the SNI (and offered ALPN) read from the TLS ClientHello without terminating TLS: buffer and parse the cleartext ClientHello on an SNI-enabled TCP listener, select a backend cluster by exact/wildcard SNI + client-preference-order ALPN, and forward the original encrypted bytes byte-for-byte, preserving end-to-end TLS and client-cert mTLS (e.g. many Kubernetes API servers multiplexed behind one :443). Architecture mirrors the UDP sans-io work: a pure ClientHello preread core (no I/O, injected time/config, invariant sweeps, no panic on adversarial input) in lib/src/protocol/tcp_preread/, driven by an impure mio shell; a deterministic simulation in sozu-sim, a cargo-fuzz target, and focused e2e. Config: TCP frontends gain optional `sni`/`alpn`; TCP listeners gain `sni_preread_timeout` (default 5s) and `sni_preread_max_bytes` (default 16 KiB, clamped to buffer_size, floored at the 5-byte TLS record header). SNI-enabled listeners reject non-TLS/no-SNI/malformed first bytes; non-SNI TCP listeners are byte-identical to before. Validation is enforced both at config load and at the worker request boundary (dynamic AddTcpFrontend / state replay). Also fixes a general Pipe close-before-flush data-truncation shared by H1/H2/WebSocket/TCP: on frontend EOF with bytes still queued for the backend, Pipe::readable returned Close unconditionally and dropped them, silently truncating any upload racing a frontend close. It now transitions to the half-closed WriteOpen state, arms the backend writable, and defers teardown to check_connections so the queue drains first. Tests: tcp_preread unit + parser fuzz (fuzz_tcp_clienthello) + deterministic simulation (tcp_preread_sim) + SNI/ALPN/mTLS/reject-matrix/PROXY/splice/ counter-conservation e2e. All current TCP e2e unchanged and green; full e2e suite (all protocols) green. CI wired for the new fuzz and simulation targets. Docs: doc/configure.md, doc/testing.md, CHANGELOG.md, and a new lib/src/protocol/tcp_preread/LIFECYCLE.md. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
left a comment
There was a problem hiding this comment.
Automated cross-review (review / review-code / guidelines / simplify / security-review + Codex, adversarially verified). 2 findings survived verification — details inline, batched into one review. (Submitted as COMMENT: GitHub forbids REQUEST_CHANGES on one's own PR.)
…kkeeping Address the PR #1290 CI failure and both inline review findings, plus two defects the local gate and a Codex cross-review caught in the round itself. Pipe::frontend_hup dropped every not-yet-forwarded upload byte when the client FIN arrived as an epoll (RD)HUP event with data still queued -- the HUP-path sibling of the readable()-EOF close-before-flush drain fixed earlier in this branch. It now mirrors backend_hup's drain branch (status stays Closed, READABLE interest retained while the kernel tail is pending, backend armed writable, teardown deferred to check_connections), and TcpSession::ready_inner falls through into its processing loop when front_hup returns Continue instead of returning early: edge-triggered epoll never delivers another event for a silent, fully-closed client, so the drain must run in the same pass. This was deterministic on loaded CI runners (all three crypto cells): the coalesced 1 MiB e2e guard truncated at 980 KiB. Unit-guarded by frontend_hup_drains_inflight_request_bytes_before_closing (seen red); the coalesced e2e guard passes 3/3 under taskset -c 0. splice_readable's SocketResult::Closed arm had the same hole on the splice fast path: unconditional Close on frontend EOF dropped whatever splice_in_pending() bytes still sat in the kernel in_pipe (the local splice-cell gate truncated the same coalesced guard at 978 KiB). It now mirrors the non-splice Closed arm: half-close transition, backend armed writable, teardown deferred to check_connections -- whose request_is_inflight already counts splice_in_pending(). Feature-gated unit test seen red. The exact-key SNI route bookkeeping (validate_new_tcp_front, insert_sni_route, remove_sni_route) looked keys up with accept_wildcard: true, so an exact key with no literal node yet fell back to a sibling wildcard's entries: inserts corrupted the wildcard's route Vec (any other subdomain offering the same ALPN could route to the exact key's cluster) and legitimate exact catch-alls were falsely rejected as duplicates of the wildcard's. The two mutating sites now pass accept_wildcard: false (a wildcard key's own lookup still resolves via lookup_mut's literal-`*` short-circuit); validate_new_tcp_front passes key.starts_with("*.") instead, because the immutable pattern_trie lookup has no such short-circuit and a plain false would let duplicate/overlapping wildcard frontends bypass validation. Three exact-vs-wildcard regression tests plus three wildcard-duplicate validation tests, each seen red. upgrade_sni_preread's four defensive early returns skipped the tcp.sni_preread.duration sample that close() cannot recover later (the SniPreread value is consumed); each arm now records it, symmetric with the success path. Metrics-only. Signed-off-by: Florentin Dubois <[email protected]>
|
CI red root-caused and fixed in 5613f94 ( Not a flaky deadline: two more members of the same close-before-flush class this PR already fixed on the
Both are unit-guarded (each seen red), and the coalesced e2e guard now passes 3/3 under One deliberately deferred follow-up (surfaced by a Codex cross-review): on frontend HUP, responses to a genuinely half-closed client ( |
Zero-trust re-verification of every documentation file and code comment this branch touches, each claim checked against the code as it now exists rather than trusted from when it was written. LIFECYCLE.md: all drifted file:line citations replaced with symbol anchors (function/type/test names, resolvable with grep) so they cannot rot again; the gauge/duration split on upgrade_sni_preread's defensive early returns documented; the two-phase admission section relabeled cluster-agnostic vs post-routing; the listener-update paragraph reconciled with doc/configure.md (UpdateTcpListenerConfig carries no preread fields, so `sozu listener tcp update` is not a validation-bypass path -- add and LoadState replay are). Internal planning vocabulary embedded away everywhere: defect letters, test-matrix numbers, and references to out-of-repo planning documents replaced with the substance they stood for (e.g. "the close-before-flush truncation where bytes queued for the backend were dropped when the frontend closed first"). No local filesystem paths remain. Factual corrections: set_tls_metadata's doc now names both caller classes (the HTTPS-to-WSS upgrade stamping all four fields, and the TCP SNI-preread pipes stamping SNI/ALPN with version/cipher deliberately None since passthrough never sees negotiated parameters); command/src/config.rs cited a nonexistent error-variant name (SniPrereadMaxBytesTooLarge -> SniPrereadMaxBytesExceedsBufferSize); the e2e fuzz wrapper doc claimed two targets where four are registered; a parser debug_assert message miscounted the ClientHello fixed-prefix length composition; doc/configure.md and doc/testing.md defaults, metric names, and command lines re-verified against config.rs and metrics/names.rs. Comments and docs only -- the only non-comment lines changed are three string literals (two e2e test descriptions and one debug_assert message). Verified: cargo clippy --all-targets --locked -D warnings, cargo +nightly fmt --all --check, cargo test -p sozu-lib --locked all exit 0. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
left a comment
There was a problem hiding this comment.
Automated cross-review round 2 (review / review-code / guidelines / simplify / security-review + Codex, adversarially verified) at head 42c08b5. 6 findings survived verification - 2 functional (both low severity), 4 simplifications - details inline, batched into one review. (Submitted as COMMENT: GitHub forbids REQUEST_CHANGES on one's own PR.)
Address the two functional findings of the second automated cross-review on PR #1290, plus the fuzz CI job budget it exposed. SNI patterns could smuggle pattern-trie syntax past validation: the route table is a pattern_trie::TrieNode whose insert treats a leftmost "/.../" label as a REGEX segment, and validate_sni_pattern never rejected '/', so sni = "/[a-z]+/.example.com" silently became a regex-matching route -- wider than the documented "exact host or one leading *. label" contract. Config load now rejects '/' anywhere in the pattern, and the worker request boundary (validate_new_tcp_front) gains the same shape check ('/' anywhere, '*' outside a single leading "*." label) so a direct AddTcpFrontend or LoadState replay cannot bypass it. Access-log tags were keyed by listener address alone, a leftover from one-frontend-per-listener days: with several SNI/ALPN frontends sharing one address, the last-added frontend's tags clobbered every sibling's, and removing any one frontend cleared tags for the whole address. The route decision now carries the matched trie pattern and ALPN matcher (Output::Routed gains matched_sni_pattern + matched_alpn), tags are stored and cleared under a canonical per-route key (address|sni|sorted-alpn; legacy no-SNI frontends keep the bare address key byte-identically), and both the TCP session's and the Pipe's access logs resolve tags through the session's matched-route key. The deterministic simulation folds the new fields into its determinism fingerprint and predicts the winning pattern+matcher per scenario. The fuzz CI job's timeout-minutes goes 30 -> 45: four 300-second targets are ~20 min of fuzzing, but per-target sanitizer builds plus toolchain/cargo-fuzz install pushed the observed wall time to ~30 min, cancelling the last target (run 29088526469). Every new guard was seen red first: trie-syntax patterns accepted at load and at the worker boundary, sibling tags clobbered on add and on remove, before each respective fix. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
left a comment
There was a problem hiding this comment.
Cross-review at 4de880cd: 11 findings survived adversarial verification (3 high, 5 medium, 3 low). Details are batched inline. Submitted as COMMENT because GitHub forbids REQUEST_CHANGES on one's own PR.
…cates Address every remaining review finding on the SNI passthrough routing feature — the four simplification refactors previously deferred as follow-ups are implemented as well, so no open review thread remains untreated. Security / correctness: - The preread deadline is now an absolute first-byte budget: the session no longer re-arms the frontend timeout on every fragment while a route decision is pending, and the sans-io core itself rejects bytes arriving at or after its latched deadline (Fragmented) — a client trickling one byte per read can no longer hold the session and both buffers on a sliding window. - front_timeout is restored the moment routing succeeds instead of after the backend connect completes, so a slow-but-legitimate backend connect is bounded by front_timeout/connect_timeout, never by the short preread budget. The session timeout path is route-aware: a front timeout firing after the route latched no longer replays the decided output through the shell (double-counted tcp.sni_preread.routed in release, debug_assert trip in debug). - validate_sni_pattern is now pub and shared: the worker's validate_new_tcp_front delegates to the same complete shape validator as config load (empty strings, non-ASCII, empty labels — shapes that previously crashed the worker on pattern_trie's release assert_ne! via a leading empty label, or silently installed a dead listener when the ignored trie insert failed). insert_sni_route failures now propagate. - ConfigState admission reaches full worker parity before mutation: cross-cluster duplicate (address, sni, alpn) identity, ALPN canonicalized as a sorted+deduped set (add and remove), no-SNI/SNI mixing bans in both directions, single catch-all per (address, sni), ALPN-set overlap rejection, alpn-without-sni rejection, and shared SNI shape validation — the master no longer persists routes its own workers reject, and removal with reordered ALPN no longer returns NoChange. - The ClientHello parser rejects duplicate server_name/alpn extensions, a server_name_list carrying more than one host_name entry, zero-length ALPN protocol names, and an empty ALPN list (MalformedHandshake) — closing a routing/forwarding parser differential and an allocation/log amplification vector. The routed info-log renders at most 8 offered ALPN protocols with a (+N more) suffix. - The access-log tags key is composed through a single length-prefixed encoder (TcpFrontendTagsKey): two legal disjoint matchers such as alpn = ["a,b"] and alpn = ["a", "b"] no longer collide to one key, so neither clobbers nor clears its sibling's tags. Reliability: - Pipe's deferred close now completes on the drain itself: when the frontend read side already hit EOF/HUP, the buffered and splice backend-writable paths run the close gate on the transition to zero pending bytes instead of returning Continue and stranding the session until an unrelated event (edge-triggered epoll offers no further edge). - The duplicated close-before-flush Closed arms in readable() and splice_readable() are factored into close_frontend_read_side. Tests / docs / dedup: - The e2e per-IP limiter test now actually holds its first connection open behind an explicit release channel and proves both the rejection and the decrement; a permanent differential cell (limit raised) proves the assertion keys off the limiter rather than a dead backend. - upgrade_sni_preread's four early-return guards share one abort helper (single DURATION-recording site); insert/remove_sni_route share one route key+matcher constructor; the TCP frontend identity predicate in ConfigState is a single helper used by add, remove, and its post-condition assert. - fuzz/README.md matches the four-target reality (CI fuzz job, smoke wrapper invocation, corpus inventory); doc/configure.md's validation caveat reflects worker-side enforcement; RejectReason doc enumerates the current MalformedHandshake triggers. All behavior fixes carry regression tests proven red against the pre-fix code. Full gate: cargo test --workspace, clippy -D warnings (default + splice cells), +nightly fmt --check. Signed-off-by: Florentin Dubois <[email protected]>
The helper was gated #[cfg(debug_assertions)] while add_tcp_frontend references it inside debug_assert! expressions — those still typecheck in release builds even though they compile out, so the bench/release profile (CI's Criterion step, the Docker image build) failed with E0599 while every debug-profile gate stayed green. The count is a trivial sum of bucket lengths; compiling it unconditionally keeps the invariant checkable everywhere. Verified: cargo bench --no-run --locked -> exit 0 (the failing CI command), cargo test -p sozu-command-lib --locked -> 132 passed, clippy -D warnings + nightly fmt --check clean. Signed-off-by: Florentin Dubois <[email protected]>
…kkeeping Address the PR #1290 CI failure and both inline review findings, plus two defects the local gate and a Codex cross-review caught in the round itself. Pipe::frontend_hup dropped every not-yet-forwarded upload byte when the client FIN arrived as an epoll (RD)HUP event with data still queued -- the HUP-path sibling of the readable()-EOF close-before-flush drain fixed earlier in this branch. It now mirrors backend_hup's drain branch (status stays Closed, READABLE interest retained while the kernel tail is pending, backend armed writable, teardown deferred to check_connections), and TcpSession::ready_inner falls through into its processing loop when front_hup returns Continue instead of returning early: edge-triggered epoll never delivers another event for a silent, fully-closed client, so the drain must run in the same pass. This was deterministic on loaded CI runners (all three crypto cells): the coalesced 1 MiB e2e guard truncated at 980 KiB. Unit-guarded by frontend_hup_drains_inflight_request_bytes_before_closing (seen red); the coalesced e2e guard passes 3/3 under taskset -c 0. splice_readable's SocketResult::Closed arm had the same hole on the splice fast path: unconditional Close on frontend EOF dropped whatever splice_in_pending() bytes still sat in the kernel in_pipe (the local splice-cell gate truncated the same coalesced guard at 978 KiB). It now mirrors the non-splice Closed arm: half-close transition, backend armed writable, teardown deferred to check_connections -- whose request_is_inflight already counts splice_in_pending(). Feature-gated unit test seen red. The exact-key SNI route bookkeeping (validate_new_tcp_front, insert_sni_route, remove_sni_route) looked keys up with accept_wildcard: true, so an exact key with no literal node yet fell back to a sibling wildcard's entries: inserts corrupted the wildcard's route Vec (any other subdomain offering the same ALPN could route to the exact key's cluster) and legitimate exact catch-alls were falsely rejected as duplicates of the wildcard's. The two mutating sites now pass accept_wildcard: false (a wildcard key's own lookup still resolves via lookup_mut's literal-`*` short-circuit); validate_new_tcp_front passes key.starts_with("*.") instead, because the immutable pattern_trie lookup has no such short-circuit and a plain false would let duplicate/overlapping wildcard frontends bypass validation. Three exact-vs-wildcard regression tests plus three wildcard-duplicate validation tests, each seen red. upgrade_sni_preread's four defensive early returns skipped the tcp.sni_preread.duration sample that close() cannot recover later (the SniPreread value is consumed); each arm now records it, symmetric with the success path. Metrics-only. Signed-off-by: Florentin Dubois <[email protected]>
Address the two functional findings of the second automated cross-review on PR #1290, plus the fuzz CI job budget it exposed. SNI patterns could smuggle pattern-trie syntax past validation: the route table is a pattern_trie::TrieNode whose insert treats a leftmost "/.../" label as a REGEX segment, and validate_sni_pattern never rejected '/', so sni = "/[a-z]+/.example.com" silently became a regex-matching route -- wider than the documented "exact host or one leading *. label" contract. Config load now rejects '/' anywhere in the pattern, and the worker request boundary (validate_new_tcp_front) gains the same shape check ('/' anywhere, '*' outside a single leading "*." label) so a direct AddTcpFrontend or LoadState replay cannot bypass it. Access-log tags were keyed by listener address alone, a leftover from one-frontend-per-listener days: with several SNI/ALPN frontends sharing one address, the last-added frontend's tags clobbered every sibling's, and removing any one frontend cleared tags for the whole address. The route decision now carries the matched trie pattern and ALPN matcher (Output::Routed gains matched_sni_pattern + matched_alpn), tags are stored and cleared under a canonical per-route key (address|sni|sorted-alpn; legacy no-SNI frontends keep the bare address key byte-identically), and both the TCP session's and the Pipe's access logs resolve tags through the session's matched-route key. The deterministic simulation folds the new fields into its determinism fingerprint and predicts the winning pattern+matcher per scenario. The fuzz CI job's timeout-minutes goes 30 -> 45: four 300-second targets are ~20 min of fuzzing, but per-target sanitizer builds plus toolchain/cargo-fuzz install pushed the observed wall time to ~30 min, cancelling the last target (run 29088526469). Every new guard was seen red first: trie-syntax patterns accepted at load and at the worker boundary, sibling tags clobbered on add and on remove, before each respective fix. Signed-off-by: Florentin Dubois <[email protected]>
…, PROXY half-close and relay source fixes (#1934) * fix(tcp): charge a backend connect timeout to the backend A TCP backend connection still not established when `connect_timeout` expires closed the session, as the documented TCP exception requires (a TCP session is not failed over), but the timeout never reached the accounting a refused connection goes through. The backend timer is armed for `connect_timeout` in `connect_to_backend` and only switches to `back_timeout` in `set_back_connected`, and the backend arm of `TcpSession::timeout` only called `container_backend_timeout.triggered()`. `Server::timeout` runs no `ready` pass for TCP (`ProxySession::needs_ready_pass` is `false`), and `TcpSession::fail_backend_connection`, the only place that bumps `Backend::failures`, arms the retry policy and emits `backend.connections.error`, `backend.down` and `backend.available`, was called only from the HUP branch of `ready_inner`. A blackholed TCP backend (SYN dropped, accept queue full) therefore never entered its back-off window, the load balancer kept selecting it, and every client routed to it waited the full `connect_timeout` before being closed. The backend arm of `TcpSession::timeout` now calls `fail_backend_connection` when the dial is still `Connecting`, then still closes the session. A timer firing on a `Connected` backend is an idle `back_timeout` and charges nothing. Nothing is released twice: `fail_backend_connection` touches only the failure count, the retry policy and the error and down metrics, and the connection release in `TcpSession::close` runs once as before. `CHANGELOG.md`, the `connect_timeout` row and the TCP failover paragraph of `doc/configure.md`, `doc/lifetime_of_a_session.md` and the `max_connection_attempts` comment of `bin/config.toml` describe the new accounting. Tests: - `tcp::sni_routing_tests::a_backend_connect_timeout_is_charged_to_the_backend` fires the backend timer of a still-`Connecting` dial and asserts the session closes with `failures == 1` and one retry-policy try (unfixed: `left: 0 right: 1`). - `tcp::sni_routing_tests::a_backend_idle_timeout_is_not_charged_to_the_backend` is its pair: the same timer on a `Connected` backend closes the session and charges nothing. Signed-off-by: Florentin Dubois <[email protected]> * fix(tcp): do not replay the SNI route on a hang-up during the backend connect Once a ClientHello routes a TCP SNI-preread session, the route latches in `SniPreread::outcome`, and frontend HUP interest stays armed while the backend dial is still `Connecting`. A client FIN or RST then reached `TcpSession::front_hup`, `SniPreread::on_front_closed` and `front_gone`. The accumulator still held the ClientHello, so `Input::FrontClosed` went into the already-decided core, which replayed the latched `Output::Routed` through `handle_output` a second time: release builds counted `tcp.sni_preread.routed` twice and logged the route twice, and debug builds aborted the worker on `debug_assert!(self.outcome.is_none(), ...)`. `SniPreread::front_gone` now returns `SessionResult::Close`, with a `debug!` line, before it looks at the accumulator whenever a route has already latched, as the route-aware front timeout in `TcpSession::timeout` already does (#1290). The guard sits in the shared helper, so the read-error path is covered as well as the HUP path. The session still closes through the existing teardown, exactly once. The doc comment of `SniPreread::on_front_closed` no longer claims it only runs before a routing decision. `CHANGELOG.md` and the tcp_preread `LIFECYCLE.md` describe the new behaviour. Test: - `tcp::sni_routing_tests::frontend_hup_after_route_with_pending_dial_does_not_replay_the_route` routes a session, leaves its dial `Connecting`, delivers a frontend HUP and runs one `ready()` pass: the pass must not panic, must still close the session, and `routed` must move by exactly one. Unfixed, it panics with "a route must be captured at most once per SniPreread lifetime", and with debug assertions off it fails with `left: 2 right: 1`. Signed-off-by: Florentin Dubois <[email protected]> * fix(tcp): give an expect-proxy pipe no clone of the session's frontend timer On an `expect_proxy` TCP listener, `TcpSession::new` gave `ExpectProxyProtocol` a clone of the session's frontend `TimeoutContainer`, and `ExpectProxyProtocol::into_pipe` passed that clone on to the `Pipe`. A clone shares the timer wheel handle but not the entry it names, so a reset only the session performed (`TcpSession::set_back_connected`, or `TcpSession::readable` ahead of the pipe's own reset) left the pipe with a stale handle, and the pipe re-armed a second entry under the same token. When that second entry fired first, `TcpSession::timeout` discarded the session's own live entry with `triggered()`. Nothing could cancel that entry any more: it later fired under a slab key reused by an unrelated TCP session, which was closed with no deadline check. It takes two frontend reads while the backend connect is pending, a connect that completes on a later wheel tick, both peers going quiet, and a `front_timeout` exceeding `back_timeout` by less than the time the connect took; the 60 s and 30 s defaults are never affected. `TcpSession::new` now hands `ExpectProxyProtocol` an empty container (`TimeoutContainer::new_empty`), and `ExpectProxyProtocol::into_pipe` builds the `Pipe` with no frontend timer, so the session keeps the only frontend deadline, as the plain, send-proxy, relay and SNI-preread pipes already do. The session resets that entry wherever the pipe reset its clone, so no session closes earlier than before, and the `Could not reset front timeout (pipe)` error log disappears on this path. HTTP and HTTPS never call `into_pipe` and are unchanged. `CHANGELOG.md`, `doc/lifetime_of_a_session.md` and the proxy_protocol `LIFECYCLE.md` describe the new wiring. Test: - `tcp::sni_routing_tests::expect_proxy_pipe_leaves_no_orphan_frontend_timer_after_a_timeout` drives an expect-proxy session through the stale-clone sequence and asserts that no orphan frontend entry fires after the timeout, that the expect stage holds no armed entry, and that the pipe carries no frontend timer. Unfixed, it fails with `entries fired at +[30, 34]s`; each half of the fix alone fails one of the two structural assertions. Signed-off-by: Florentin Dubois <[email protected]> * fix(tcp): read a pending ClientHello before honouring a coalesced HUP On an SNI-routed TCP listener a client can send its ClientHello and half-close right behind it, and Linux then reports both as one `READABLE | HUP` event. `TcpSession::ready_inner` honoured the HUP before reading. `SniPreread::front_gone` looks at the accumulator, not at the kernel queue, so a session whose hello was still unread was closed as a silent bare-TCP health check: `trace!` only, no `tcp.sni_preread.routed` or `tcp.sni_preread.rejected.*` count. A hello whose last fragment arrived together with the FIN was counted as `rejected.front_closed`, although the rest of it was already queued. The pre-HUP drain in `TcpSession::ready_inner`, which ran only for `ExpectProxyProtocol` (#1823), now also runs for an `SniPreread` that has not routed yet, so the pending bytes reach the core before the HUP is acted on. A complete hello is routed and counted once, then the still-set HUP closes the session through the route-latched arm of `SniPreread::front_gone` without dialing the backend; a malformed one is rejected with the reason it earns; a hello the FIN cut short is metered `rejected.front_closed`; and a connect that sent nothing stays silent. Teardown reuses the existing `front_hup` path and releases nothing new. The comments of `SniPreread::front_gone` and `on_front_closed` and the tcp_preread `LIFECYCLE.md` §9 now describe a route latched in that drain as well as during a pending dial. `CHANGELOG.md`, `doc/lifetime_of_a_session.md` and the tcp_preread `LIFECYCLE.md` describe the new behaviour. Tests: - `tcp::sni_routing_tests::sni_preread_hello_and_fin_in_one_event_is_routed_not_a_silent_health_check` delivers a complete hello and a FIN in one real epoll event. - `tcp::sni_routing_tests::sni_preread_last_fragment_and_fin_in_one_event_is_routed_not_rejected` reads the first half of the hello in an earlier pass, then delivers the second half and the FIN in one event. Both fail on the unfixed tree at their final routed-count assertion (`left: 0 right: 1`). Signed-off-by: Florentin Dubois <[email protected]> * fix(tcp): forward a request half-closed before the backend connect on PROXY clusters On a TCP cluster that sends a PROXY header to its backend (`send_proxy = true`), a relay cluster when the listener has `expect_proxy = true` and a send cluster otherwise, a client may write its request and FIN before the worker services the socket. The first `TcpSession::ready_inner` pass only dials, so the coalesced `READABLE | HUP` was still pending on the next pass, which handed it to the wildcard arm of `TcpSession::front_hup`. That closed the session before `RelayProxyProtocol::back_writable` or `SendProxyProtocol::back_writable` had written anything: the backend saw a connection dialed and then closed with nothing written, without even its PROXY header on a send cluster, and the client's own header and request were dropped on a relay one. An `expect_proxy` listener without `send_proxy` was not affected: it already reads the queued bytes before acting on the HUP. `TcpSession::ready_inner` now drains a relay session's readable bytes before its HUP check, and a new `TcpSession::defers_frontend_hup` keeps the HUP of a send session, and of a relay session once its header is parsed, in the readiness event while masking it out of the dispatch loop's frontend interest. The HUP then reaches the existing teardown, `Pipe::frontend_hup`, through the existing upgrade: the header and the request are forwarded, and the pipe closes the session once nothing is left in flight. A relay client that half-closes inside its PROXY header still closes at once, ERROR still closes at once, and no new release path is added. A send session reads nothing before the upgrade, so a bare connect and FIN, typically an L4 health check, now waits for the backend connect and costs the backend one connection that carries only the PROXY header; the wait is bounded by the connect, `connect_timeout` and the frontend timeout. `CHANGELOG.md`, `doc/lifetime_of_a_session.md` and the proxy_protocol `LIFECYCLE.md` describe the new behaviour. Tests (in `tcp::sni_routing_tests`): - `relay_proxy_protocol_half_close_before_backend_connect_forwards_the_request` - `send_proxy_protocol_half_close_before_backend_connect_forwards_the_request` Both fail on the unfixed tree on the delivery assertion ("the backend must receive it, got []"). Guards for each arm of the new predicates: - `relay_proxy_protocol_front_hup_while_connecting_waits_for_the_backend` - `send_proxy_protocol_front_hup_while_connecting_waits_for_the_backend` - `relay_proxy_protocol_half_close_without_any_byte_closes_at_once` - `relay_proxy_protocol_half_close_inside_the_header_closes_at_once` - `send_proxy_protocol_bare_half_close_delivers_only_the_header_then_closes` - `send_proxy_protocol_reset_while_connecting_closes_at_once` Signed-off-by: Florentin Dubois <[email protected]> * docs(tcp): repair the TO SEE THIS RED recipes of the new tests The recipe of tcp::sni_routing_tests::a_backend_connect_timeout_is_charged_to_the_backend said "run it unmodified" and named no statement to mutate. It now names the statement and the failure it produces: delete the `self.fail_backend_connection();` call from the `is_connecting()` block in the backend arm of `TcpSession::timeout`, and the `failures` assertion fails with "a connect timed out on connect_timeout must be counted against its backend". The mutation was applied and the test seen failing on its own assertion, then the code was restored. Comments only. Signed-off-by: Florentin Dubois <[email protected]> * fix(tcp): dial a relay session's backend only after its PROXY header is parsed A `RelayHeader` TCP session (a cluster with `send_proxy = true` behind a listener with `expect_proxy = true`) dialed its backend on its first readiness event, before `RelayProxyProtocol::readable` had parsed the inbound PROXY-v2 header. `TcpSession::attempt_backend_connect_if_needed` excluded only `ExpectProxyProtocol` and an unrouted `SniPreread`. With nothing parsed, `TcpSession::effective_session_address` fell back to the accepted peer, which is the upstream load balancer, so the per-(cluster, source-IP) and per-subnet slots (`max_connections_per_ip`, `max_connections_per_subnet`) were charged to the load balancer for every client behind it, and the affinity key of `HRW`, `MAGLEV` and `shard_percent` was derived from it too. `attempt_backend_connect_if_needed` now returns early for a `RelayProxyProtocol` whose `header_size` is still `None`, so a relay session dials through the attempt that follows the `readable()` call that parses its header, and is charged to the header's source address. The pre-HUP drain in `TcpSession::ready_inner` also gets one dial attempt, restricted to a relay session, so a header coalesced with the client's FIN does not leave the session undialed until the frontend timeout. The dial and the release are the existing `connect_to_backend` and close paths. A `LOCAL` / `AF_UNSPEC` header still falls back to the peer, as documented. A relay session no longer overlaps its backend connect with the wait for the header, and a relay connection that never completes a header (a bare health check, a slow or garbage client) opens no backend connection at all. The comments of `ready_inner` and of the half-close test helper now describe the parse-then-dial order, and the relay front-HUP test sends only its payload, since its fixture now writes and parses the header before dialing. `CHANGELOG.md`, `doc/lifetime_of_a_session.md`, `doc/rate-limit-design.md` and the proxy_protocol `LIFECYCLE.md` describe the new behaviour. Test: - `tcp::sni_routing_tests::a_relay_proxy_protocol_session_is_charged_to_the_header_source_not_the_lb_peer` connects from 127.0.0.1 (the load balancer) and relays a header whose source is 192.0.2.7, and asserts that no slot is held before the header, that the slot is charged to 192.0.2.7 after it, and that 127.0.0.1 holds none. On the unfixed tree it fails with "the per-IP slot must not be charged to the load balancer's peer address before its PROXY header is read". Signed-off-by: Florentin Dubois <[email protected]> --------- Signed-off-by: Florentin Dubois <[email protected]>
Summary
Adds SNI + ALPN-based routing for TCP passthrough (closes #1279): preread the TLS
ClientHello on an SNI-enabled TCP listener, route by SNI (exact + wildcard) and
offered ALPN (client-preference order) to a backend cluster, and forward the
original encrypted stream byte-for-byte — end-to-end TLS and client-cert mTLS
preserved. Canonical use case: many mTLS backends (e.g. Kubernetes API servers)
multiplexed behind one IP:port.
Architecture mirrors the UDP sans-io work: a pure ClientHello preread core
(
lib/src/protocol/tcp_preread/, no I/O, injected time/config, invariant sweeps,no panic on adversarial input) driven by an impure mio shell; a deterministic
simulation in
sozu-sim, a cargo-fuzz target, and focused e2e.Protocol / security impact (please review closely)
Pipeclose-before-flush truncation. On frontendEOF with bytes still queued for the backend,
Pipe::readablereturnedCloseunconditionally and dropped them, silently truncating any upload racing a
frontend close. This affects H1 / H2 / WebSocket / TCP, not just the new SNI
path (the SNI coalesced case was just the reliable reproducer — same class as the
WebSocket handoff fix in fix(pipe): preserve websocket bytes after upgrade #1288). Now half-closes to
WriteOpen, arms the backendwritable, and defers teardown to
check_connectionsso the queue drains first.See
lib/src/protocol/pipe.rs. Full e2e suite (all protocols) is green.runs, deterministically simulated). No
unwrap/panic/debug_assertonnetwork-controlled input.
reject non-TLS / no-SNI / malformed first bytes. Validation is enforced both at
config load and at the worker request boundary (dynamic
AddTcpFrontend/state replay), not just a debug assertion.
buffer before splice engages.
Config surface
sni, repeatablealpn. Frontend identity is(address, sni, alpn-set).sni_preread_timeout(default 5s),sni_preread_max_bytes(default 16384, clamped to
buffer_size, floored at the 5-byte TLS record headerso a
0can never spin).--sni/--alpnonfrontend tcp add,--sni-preread-timeout/--sni-preread-max-bytesonlistener tcp add.Tests
tcp_prereadcore + parser), fuzz (fuzz_tcp_clienthello+ seed corpus),deterministic simulation (
tcp_preread_sim, 15-class nonzero coverage gate), ande2e: SNI/ALPN routing, Kubernetes-API-server-style mTLS (client cert verified
reaching the backend through Sōzu), byte-for-byte replay, the full reject matrix,
PROXY protocol expect/send/relay composition, splice, and gauge/counter
conservation.
across all protocols. CI is wired to run the new fuzz + simulation targets.
Docs
doc/configure.md(config keys + metrics),doc/testing.md,CHANGELOG.md, and anew
lib/src/protocol/tcp_preread/LIFECYCLE.md.Known limitations (documented)
UpdateTcpListenerConfigcannot patch the two preread knobs (Add-only).operator to write the punycode A-label (no IDNA U-label normalization yet).