Skip to content

fix(proxy-protocol): preserve payload after short v2 headers - #1844

Merged
FlorentinDUBOIS merged 3 commits into
mainfrom
fix/proxy-v2-expect-payload
Oct 4, 2026
Merged

FlorentinDUBOIS merged 3 commits into
mainfrom
fix/proxy-v2-expect-payload

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

ExpectProxyProtocol read inbound PROXY v2 data in fixed 28-, 52- and 232-byte stages. When a valid short header and application payload arrived in one client write, the socket read could pull payload into the header staging buffer. The parser returned that payload as its remainder, but the TCP, HTTP and HTTPS upgrades discarded the staging buffer.

A 16-byte LOCAL header therefore removed the first 12 payload bytes; IPv4 and IPv6 headers with TLVs could lose more.

A valid PROXY v2 header that filled the complete 232-byte expect buffer triggered a second defect: the expect stage removed READABLE interest. HTTPS copied that interest into the TLS handshake, so neither a queued nor a later ClientHello could be read and the connection stalled.

Contract and fix

Read the fixed 16-byte PROXY v2 prelude first, derive the exact target as 16 + len, reject a declared total above Sōzu's existing 232-byte capacity before another read, then read only to that target. Application bytes coalesced after the header remain on the socket for the downstream protocol.

The accepted 232-byte boundary, malformed-header rejection and public HeaderLen API remain intact. A complete maximum-size header no longer removes READABLE interest before the protocol transition, so HTTPS can consume the ClientHello. The documentation distinguishes invalid signatures, which fail parsing, from a valid prelude whose declared total exceeds the 232-byte capacity. Runtime ingress accepts PROXY v2; v1 remains only a legacy header model.

Scope

Nine files form one behavior, test and documentation changeset:

  • lib/src/protocol/proxy_protocol/expect.rs: exact-length reads, capacity rejection and preserved READABLE interest at the accepted 232-byte boundary;
  • e2e/src/tests/tcp_tests.rs: real worker/backend regression for header totals 16, 28, 36, 60 and 232;
  • e2e/src/tests/proxy_protocol_payload_tests.rs and e2e/src/tests/mod.rs: repeated TCP, HTTP and HTTPS regressions for coalesced and fragmented delivery, all accepted v2 header shapes, the exact 232-byte boundary, and refused v1, oversized and malformed inputs;
  • lib/src/protocol/proxy_protocol/LIFECYCLE.md: exact-read, handoff, 232-byte interest, malformed input and merged half-close contracts;
  • doc/configure.md: v2-only configuration and metric descriptions;
  • lib/README.md and lib/src/protocol/proxy_protocol/mod.rs: v2 runtime versus legacy v1 model;
  • CHANGELOG.md: both client-visible failures and their corrected behavior.

Verification

On main after #1836 and before the exact-read correction, the targeted TCP E2E remained red, exit 101 (0 passed; 1 failed; 623 filtered). Backend observations were 17/29 for LOCAL-16, 29/29 for the IPv4-28 positive witness, 13/29 for IPv4+TLV-36, 0/29 for IPv6+TLV-60 and 29/29 for LOCAL-232. The worker stopped cleanly.

On 13e07772497f96830410dc0b7afb0599c96f4b5b, before the 232-byte HTTPS correction, the unchanged HTTPS regression was red (0 passed; 1 failed; 627 filtered): all eight shorter coalesced and fragmented witnesses returned HTTP 200, while both exact-232 variants received no answer. The v1, 233-byte and malformed inputs remained refused without a backend dial, and the worker stopped cleanly.

On current head 02b7eceb73637c90f511b73d4969470b769b4af4:

  • the exact HTTPS regression passed (1 passed; 0 failed; 627 filtered) with both exact-232 variants returning HTTP 200;
  • the complete TCP/HTTP/HTTPS payload module passed (3 passed; 0 failed; 625 filtered), with each test requiring two consecutive clean executions through repeat_until_error_or;
  • the merged fix(proxy-protocol): drain a PROXY-v2 header coalesced with the client half-close #1836 READABLE | HUP oracle passed (1 passed; 0 failed; 1572 filtered);
  • scoped Clippy for sozu-lib and sozu-e2e, all targets, features opentelemetry,splice,simd, with warnings denied, passed;
  • CI nightly rustfmt, documentation citation drift validation against 84f12bb1c139711a87089602cf4b6eaf3deeaad3, and git diff --check passed;
  • both commits retain signatures and sign-offs.

The original exact-read patch SHA-256 is 8e22297330000bdb3696838f177da87b382ad4700f2af3c075b807b288a885e5. The 232-byte HTTPS correction from 13e07772... to 02b7eceb... has patch SHA-256 6340a17e9e42d144ea67e1421d616dbe81ed414807fc93474d56ab931954900e. Independent source review accepted the current correction; its report SHA-256 is 416ee19740c910e2542e7514f1994f94d631f954323d26ad75094d73170ea152.

Boundaries

The runtime regressions cover TCP, HTTP and HTTPS, coalesced and fragmented writes, accepted totals 16, 28, 36, 52, 60 and 232 where each protocol permits them, plus rejected v1, 233-byte and undersized address inputs. The focused #1836 unit oracle preserves parsing before a coalesced half-close; the broader TCP half-close policy tracked by #1840 remains outside this change.

Fixes #1841

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

Review of 34221e4. One small fix requested before merge. The root-cause fix is right. It reads the 16-byte fixed part, then reads exactly up to 16 + len. The new e2e test fails on main: the backend receives 17/29, 13/29 and 0/29 bytes for the 16-, 36- and 60-byte headers. It passes on this head. Relay mode, the SNI pre-read and send mode needed no change.

MEDIUM, already present on main, three lines to delete in this PR's file: an HTTPS expect_proxy listener stalls on a PROXY v2 header of exactly 232 bytes.

  • lib/src/protocol/proxy_protocol/expect.rs:178-180 removes READABLE interest when self.index == self.frontend_buffer.len().
  • HttpsSession::upgrade_expect then copies the whole readiness, interest included, into the handshake (lib/src/https.rs:435, handshake.frontend_readiness = readiness;).
  • The handshake never gets read interest back, so the TLS handshake never completes and the client gets no answer. TCP and HTTP copy only the event bits and are unaffected.
  • The case fails with both coalesced and split writes, on main and on this head. With those three lines deleted, it passes.
  • Exact reads mean index == 232 now only happens once the header is complete, so the branch no longer does anything useful.
  • The PR text and LIFECYCLE.md both say the 232-byte boundary is accepted.

An extended e2e was run on this head:

  • coverage: TCP, HTTP and HTTPS listeners; coalesced and split writes; LOCAL, IPv4 and IPv6 addresses, with and without TLVs; a 232-byte header, a 233-byte header, PROXY v1, and a short address block;
  • result: everything passes apart from the HTTPS-232 case.

The file is available as e2e/src/tests/proxy_protocol_payload_tests.rs in the local worktree sozu.fix-proxy-protocol-short-header-payload if you want to adopt it. The PR's own tests cover only TCP with coalesced writes.

Nits:

  • the new e2e test is not wrapped in repeat_until_error_or and has no "To SEE THIS RED" comment, unlike its neighbours;
  • LIFECYCLE.md rule 1 still says invalid bytes "trip the oversized-header branch"; they now fail the signature parse.

Interaction with #1836: expect.rs and CHANGELOG.md auto-merge. LIFECYCLE.md §2.1 has a doc-only conflict: keep these bullets and append #1836's "HUP is honoured only after…" bullet. In the combined tree:

  • lib tests: 1598 passed;
  • e2e: everything passes except the same HTTPS-232 case;
  • the half-close drain still parses a header followed immediately by a FIN.

Verification on this head:

  • lib tests: 1593 passed;
  • e2e: proxy_protocol 17, expect_proxy 4, via_proxy_v2 1 and tcp 41 passed;
  • doc citations against origin/main: OK;
  • git merge-tree against main: clean.

@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/proxy-v2-expect-payload branch from 34221e4 to 13e0777 Compare October 3, 2026 21:58
ExpectProxyProtocol::readable removed READABLE from the frontend interest
once the read cursor reached the 232-byte buffer length. With exact-length
reads that only happens when a maximum-size header is complete, and
HttpsSession::upgrade_expect copies the whole readiness, interest included,
into the TLS handshake, which then never read the ClientHello and stalled.
Drop the branch.

Add e2e coverage for the payload behind every v2 header shape on TCP,
HTTP and HTTPS expect listeners, coalesced and split, including the
232-byte case that failed on HTTPS before this change. Fix the stale
LIFECYCLE.md hardening rule (invalid bytes now fail the signature parse)
and refresh its expect.rs citations.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 9561b24 into main Oct 4, 2026
28 checks passed
FlorentinDUBOIS added a commit that referenced this pull request Oct 4, 2026
Fixes #1828.

Long-lived sessions can emit cluster and backend metrics after `RemoveCluster`. When the same cluster, backend id, and address are recreated, those delayed events must not update the replacement lifetime.

This change gives each effective cluster lifetime an internal metrics incarnation captured by the request, route, pipe, or backend owner that may emit later. Labelled `cluster` and `backend` metrics reach the drains only while that captured incarnation is still active. Process and frontend aggregates continue to accept the same physical events after their labels are removed, so late decrements still balance the aggregate gauges they previously incremented. The public `SessionMetrics` literal shape and `register_end_of_session` behavior remain compatible.

The lifetime rules are:

- the first legal route can allocate an implicit identity before `AddCluster`;
- `AddCluster` without an intervening removal preserves that identity;
- `RemoveCluster` deletes the active identity and tombstones both drains;
- the first legal route after removal allocates a different identity and re-arms both drains, so a replacement created without `AddCluster` is visible immediately while the removed identity remains fenced;
- `metrics clear`, detail changes, and collection disable/enable do not reset an active identity;
- identity exhaustion is a distinct invalid capture: labelled metrics fail closed and removed-drain tombstones remain armed.

HTTP captures the identity per routed request or stream, so an H1 keep-alive connection can reroute correctly. TCP static and SNI routing capture once for the selected route and do not adopt a later incarnation during retry. Proxy-level connection metrics remain separate and still record physical closes.

Documentation and regression coverage are included in the same changeset. The decisive strict H1 runtime test holds an old session, removes and recreates the same cluster/backend/address, observes the proxy gauge transition from 2 to 1, verifies the replacement remains at 1, then consumes a new response metric before checking that the old close did not contaminate the new row. Additional tests cover legal routing without `AddCluster`, implicit identity continuity across an add, remove/clear fencing, replacement re-arm without an add, process/frontend aggregation, exhaustion, public API compatibility, and TCP static/SNI capture.

Validation:

- `cargo test -p sozu-lib metrics::tests --locked -j 4 -- --nocapture`: 34 passed
- `cargo test -p sozu-e2e real_http_session_without_add_cluster_records_labelled_metrics --locked -j 4 -- --nocapture`: 1 passed
- `cargo test -p sozu-e2e test_old_http_session_metrics_do_not_decrement_same_identity_replacement --locked -j 4 -- --nocapture`: 1 passed with proxy 2→1, replacement 1→1, new 2xx metric 1, and clean worker shutdown
- On the exact intended composition `main@9561b24 + #1845 product delta + #1843 tests@2f78aaf928b2241241713cbba28ff4abdc1f0926`, the independent checker replayed the retained #1843 H1 oracle 1/1 and the new H2/WebSocket oracles 2/2. The #1843 H1 case preserves the cluster id but deliberately uses distinct old/new backend ids and addresses; the strict same-cluster/backend/address H1 case above remains the #1845 oracle.
- The H2 oracle uses one real TLS connection negotiated with ALPN, holds stream 1 across remove/recreate, lets stream 3 complete on the replacement over that same connection, then observes the old stream terminate without decrementing the replacement incarnation.
- The WebSocket oracle observes a real HTTP `101` promotion into `Pipe`, exchanges structurally valid framed data in both directions for both lifetimes, and preserves access counts `1→1→2` and WebSocket gauges `2→1→0`. Its fixture omits `Sec-WebSocket-Accept`, so it proves pipe lifecycle/accounting rather than a complete RFC 6455 handshake.
- On the owner overlay `#184591e8a42 + complete #1843 test content`, the functional run passed 628 tests with exactly four existing `cargo fuzz` wrappers filtered. That overlay predates merged #1844; only the focused H1, H2, and WebSocket replays above were checked on the exact `main@9561 + #1845 product + #1843 tests` composition.
- `cargo clippy -p sozu-lib -p sozu-e2e --all-targets --locked -j 4 -- -D warnings`: passed on product-identical source
- `cargo fmt --all -- --check`, documentation citations, and `git diff --check`: passed
- the replacement-rearm regression was observed red before the fix; an invalid-exhaustion re-arm mutation was observed red before restoration

The accepted H2 and WebSocket runtime tests are published by #1843, not by this PR, so they are absent from #1845's 27/27 CI run at `91e8a421`. TCP static and SNI capture remain covered by focused unit tests without a dedicated teardown runtime scenario. The network drain re-arm remains source-coupled with the local drain and compile/lint covered; the decisive post-removal replacement and exhaustion probes exercise the local drain rather than a UDP runtime.

### Follow-ups (90fbeb2, 3b73653, 91e8a42)

- A cluster referenced by a route before any `AddCluster` gets its metrics identity on that first route; a later `AddCluster` reuses it and only `RemoveCluster` ends it. Capture states are `Missing` / `Active` / `Invalid` (exhaustion), and only an `Active` capture matching the current identity is accepted at Cluster/Backend detail; Process/Frontend aggregates accept every state.
- A route that recreates a removed id without `AddCluster` allocates a fresh identity and re-arms the drains; exhaustion leaves them fenced.
- TCP captures once at routing; `record_backend_metrics!` checks once per invocation.
- Known limit: an id never declared with `AddCluster` cannot be removed (the main process rejects `RemoveCluster` for it), so its identity entry lives as long as the worker.



Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Oct 4, 2026
The main-process hot upgrade rebuilt an empty command Hub while worker work could still be in flight. The original command client then received EOF, and a later worker response reached the replacement as an unknown task even though its data-plane request could still finish.

This change transfers the complete control-plane ownership graph to the replacement main: connected clients, client and worker channel buffers, active and queued tasks, worker-response routes, subscribers, worker pending queues, stopped workers still referenced by a task or route, task deadlines, audit clocks, and future-ID counters. The replacement restores task state directly without replaying operator requests or re-scattering work.

The handoff uses an explicit V2 `PREPARED` / `COMMIT` / `ACTIVATED` protocol:

- the replacement validates and registers inherited descriptors while paused, without command or worker data I/O;
- pre-commit rejection closes and reaps the candidate, restores `CLOEXEC`, and lets the unchanged old Hub continue;
- the first attempt to send `COMMIT` irreversibly fences the old Hub, so an ambiguous post-commit failure cannot execute work twice;
- after a complete commit, the replacement activates the Hub, schedules restored sessions once, publishes PID and systemd readiness, preserves the initiating client's terminal response under backpressure, and acknowledges activation before the old main exits.

Compatibility fails closed before adoption. A running main from before this protocol cannot export the missing Hub state, so the first deployment requires a controlled service restart after pending commands are drained and state is saved. Subsequent V2-to-V2 hot upgrades transfer pending commands. A V2 sender rejects a legacy candidate before freezing live ownership; a legacy sender remains subject to its existing generation, audit, and child-reaping limitations when a V2 candidate refuses its old envelope.

`SIGTERM` observed before commit aborts and reaps the candidate, then the old event loop consumes the preserved stop intention. Operators should signal the service control group. A signal aimed only at the old PID after the final pre-commit observation remains outside this contract, and a failure after commit is fail-stop rather than crash recovery.

The branch is based on `9561b24e61c23511326ffeb547b0b7fe51ee7055`, including the deadline and cancelled-route fixes from #1838 and the PROXY protocol corrections merged in #1844.

Channel snapshot validation accepts all five defined `Ready` bits in both serialized readiness and interest, preserves them exactly, and rejects the first unknown bit `0x20`. This covers the Linux readiness word `WRITABLE | HUP | WRITE_CLOSED` (`0x001a`) without special-casing that observed value.

Descriptor-cleanup tests observe the original command-channel and SCM socket peers instead of probing released numeric descriptors or requiring immediate EOF. EOF is the only success outcome within a fixed one-second bound: data, other errors, and expiration fail. This tolerates transient descriptor copies across a concurrent fork-to-exec window while retaining a durable duplicate of either endpoint still fails the test. The exact transient holder in the original CI jobs was not instrumented, so that scheduler-level cause remains unverified.

Validation completed locally with Rust 1.93.1 and at most four build jobs:

- `cargo test -p sozu-command-lib --locked`: 244 unit tests, 9 integration tests, and 2 doctests passed; 3 existing doctests were ignored.
- `cargo test -p sozu --locked --test upgrade_fd_inheritance_e2e -- --ignored`: failed 0/1 on the earlier snapshot mask with `invalid channel snapshot readiness bits: 0x001a`, then passed 1/1 after accepting `WRITE_CLOSED`.
- the snapshot regression exercises all 32 subsets of the five defined bits in both readiness and interest; it rejects `0x20` in each field. Removing `WRITE_CLOSED` makes the test fail on `0x10`.
- `cargo test -p sozu --locked --no-default-features --features crypto-openssl,opentelemetry,splice,simd --verbose`: 152/152 library tests passed and every integration and doctest target completed successfully.
- `cargo test -p sozu --locked --no-default-features --features fips,opentelemetry,splice,simd --verbose`: 152/152 library tests passed and every integration and doctest target completed successfully.
- retaining durable duplicates of both the command channel and SCM endpoint makes each corrected cleanup oracle fail with both EOF deadlines; restoring the candidate makes each targeted test pass 1/1.
- the accepted-handoff, rejected-candidate, SIGTERM-during-PREPARE, and descriptor-inheritance process tests pass 1/1 on the rebased head.
- the compatibility matrix passes 1/1 in both directions between the rebased candidate and the frozen pre-protocol `d7b5f14d` binary. This verifies those two transition paths rather than certifying every historical version pair; the legacy generation, audit, and child-reaping limitations described above remain observable.
- `cargo clippy --all-targets --locked --no-default-features --features crypto-openssl,opentelemetry,splice,simd -- -D warnings` and the equivalent FIPS matrix passed.
- `cargo +nightly fmt --all --check` passed.
- `.github/scripts/check_doc_citations.py --base 9561b24` passed all 37 citations, 1,078 test names, and 15 pinned excerpts.
- `env -u RUST_LOG ... cargo +1.93.1 test -p sozu --locked --features opentelemetry,splice,simd --test sigterm_soft_stop_e2e -- --ignored`: 1/1 passed. The local 27/27 missing-access-log result was caused by ambient `RUST_LOG=warn`, which GitHub CI does not set; the test requires its configured `info` access records.

GitHub CI checks are pending on the rebased commit `a8bdd54b8833060576674a8c2aff0374f6e8083b`.

Fixes #1832



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.

Expect-proxy drops payload bytes that follow a PROXY v2 header shorter than its read stage

1 participant