Skip to content

Forward a TLS-terminating connection to a peer when its local connect fails - #85

Merged
kriszyp merged 2 commits into
mainfrom
fix/tls-terminating-connect-forward
Nov 6, 2026
Merged

kriszyp merged 2 commits into
mainfrom
fix/tls-terminating-connect-forward

Conversation

@kriszyp

@kriszyp kriszyp commented Nov 5, 2026 •

Copy link
Copy Markdown
Member
Kyle tries a jammed bay door and stops a robot cutting a crate's seal

⊙ Problem

On a TLS-terminating failover route, the first connection after the local upstream stops is dropped, even with a healthy peer. The route connects after its handshake, which has already read the ClientHello, so nothing is left to send to a peer. Forward a passthrough connection to a peer when its local connect fails covered passthrough only, and Fabric's Unix-socket routes all terminate TLS.

💡 Solution

⚖️ Alternatives

  • Probe with a connect and close, then connect again: an extra accept and close on Harper per connection.
  • Probe healthy slots on a timer: connections before the next probe are lost.
  • Send decrypted traffic to the peer: changes the ingress wire format; the peer could not verify client certificates.

🤔 Should a hello too large to replay connect early?

No. A hello over 16 KiB cannot be forwarded, so a dead h1 destination would close a client that a healthy h2 destination can serve.

🤔 Should routes requiring a client certificate connect early?

No. A client with no certificate could hold Harper sockets before authenticating, with connection limits off by default. These routes still lose the first connection after an outage. Flipping this is one condition.

🤔 Is the new exposure acceptable on other routes?

A client that abandons its handshake holds a Harper socket, with no bytes sent, for up to the handshake timeout. A hello flood can overrun the accept queue and push the route to its peers. Finishing the handshake already allowed a longer hold.

🤔 Is the added cost acceptable?

Performance is below. It buys the first post-outage connection.

🔧 Changes

Connecting before the handshake

Before After
The handshake reads the hello, then the local connect fails. The client is closed: upstream_connect 1, forwarded 0. The local connect fails with the hello unread. A peer serves the client: upstream_connect 1, forwarded 1.

proxy_conn.rs:382

+if (peers && peek.complete && !route.requires_client_cert) {
+  upstream = ⏳ connect_or_forward(predicted destination)  // at most hs_timeout / 2
+  if (!upstream) return                                   // a peer served it, or none could
+  hs_timeout = deadline - now
+}
 tls = ⏳ tls_accept(stream, hs_timeout)                    // reads the hello
 destination = destination_for(negotiated_h2)
+if (upstream is for another destination || upstream.closed()) upstream = null
-upstream = ⏳ connect(destination)
+upstream ??= ⏳ connect(destination)
 ⏳ proxy_via_tls(tls, upstream)

A first connection after the upstream stops

The peer terminates TLS with its own copy of the certificate, so the client handshakes with it through the tunnel.

sequenceDiagram
    participant Client
    participant Symphony
    participant Local as Local upstream
    participant Peer
    Client->>Symphony: ClientHello (peeked, unread)
    Symphony->>Local: connect
    alt connect fails
        Symphony->>Peer: PROXY v2 + ClientHello
        Peer-->>Client: handshake through the tunnel
    else connect succeeds
        Symphony-->>Client: handshake
        Symphony->>Local: PROXY header, then client bytes
    end
Loading

Nothing is written upstream until the handshake completes, so a failed handshake is a close with no bytes.
One handshake timeout covers the connect and the handshake. A replacement connect after the handshake uses the ordinary upstream_connect_timeout.

Which connections connect early

Connection Connects If the local connect fails
Failover route, client listener, complete hello before the handshake a peer serves it
Requires a client certificate after the handshake lost; the slot is marked, so later ones go to a peer
Hello over 16 KiB after the handshake lost: too large to replay
Ingress listener after the handshake lost: the forwarder has already committed to this peer
Suspended route, or no failover policy after the handshake lost

Choosing h1 or h2 before ALPN is known

rustls negotiates the first server protocol the client offered. Symphony's list is either empty or starts with h2, so the prediction needs one bit from the hello. Fabric routes set neither http2 nor an h2 upstream today, so on them this has no effect.

proxy_conn.rs:500

predicts_h2(config, offers_h2) → offers_h2 && config.alpn_protocols[0] == 'h2'

The negotiated protocol always decides. A wrong prediction costs one extra connect, never a wrong destination.

Holding a connection across the handshake

Example: a slow client on a long handshake timeout

Harper destroys a socket that sends nothing for 10 s. A device takes 11 s to finish its handshake, on a route with tlsHandshakeTimeoutMs: 20000.

Outcome: closed() sees the close when the handshake ends, and symphony connects again. The client is served.

closed() reads the reactor's read-closed readiness rather than the socket. A peek cannot see a close behind unread data, and costs a syscall. The readiness check can miss a close the reactor has not yet processed; that window is sub-millisecond, and the connection is then lost.

Files

✅ Verification

  • npm test: 294 pass. cargo test: 249 pass. Clippy and fmt clean.
  • With src/ from 1b1fd72, 18 of failover.spec.ts's 65 cases fail, all TLS-terminating (actual: null, expected: 'ping').
  • Against harper 5.4.0-alpha.2: 20 aborted handshakes then a good request, and an 11 s handshake past Harper's 10 s idle limit.
  • Not tested: a negotiated protocol differing from the prediction. Only a client changing its offer across a hello retry gets there.

Performance: every connection gains one ALPN scan, 48 ns of parse_client_hello's 4.37 µs, and 24 bytes of future (3488 to 3512, debug layout, budget 4096). An early-connecting connection adds two clock reads and one closed(): 73 ns, no syscall. Release build, bench-run, turbo off.

Cases covered, and what each safeguard's removal breaks
Removing Fails
the closed() check replaces a connection the upstream closed during a slow handshake, loses the connection, once counted, when the upstream stops during the handshake
the complete-hello condition connects after the handshake for a hello too large to replay
the ALPN prediction connects each client only to the destination its protocol selects, with only its h2 destination refusing…
the shared timeout gives the handshake only what a slow local connect left of the timeout

Also covered: h2 offers in either order, h1 and no ALPN, one accept per client; all peers refuse with one upstream_connect; hanging connects and drain fallback in both modes; a failed and an abandoned handshake close the upstream with no bytes; mTLS routes reach the upstream only after verification; other local slots are tried before peers; ingress and suspended routes unchanged. Rust tests compare the prediction with real rustls negotiation over offer order, server config and TLS 1.2 and 1.3, plus resumption and a real hello retry.

Refs Forward to a peer when the local upstream connect fails on a TLS-terminating failover route.

PR QA: skipped @ 786025b — symphony is outside the trial's scope.

Docs: this repo's README. HarperFast/documentation has no symphony page.

🤖 Generated by Claude Code (Claude Opus 5.5); posted via @kriszyp.

Related PRs: #81 overlaps (this generalizes its connect-or-forward block), #86 overlaps (rebased onto its failover probe and test additions), #76 overlaps (same failover tests; its refusal classification is reused)
Complexity: complicated

Origin — the dispatch brief this PR was written from

Forward to a peer when the local connect fails on a TLS-terminating failover route

Implement #83. On a TLS-terminating route with a failover policy (client listener, not suspended), connect upstream before the TLS handshake. If that connect fails, forward the untouched ClientHello to peers with forward_to_peers in ForwardMode::Down, the way #81 does for passthrough routes in src/proxy_conn.rs. If it succeeds, use that connected upstream in proxy_via_tls after the handshake instead of connecting again. Open a draft PR.

Acceptance

  • failover.spec.ts: a TLS-terminating route with a peer, local UDS refusing and not yet marked down: the first connection is served by the peer. Show it fails on 1.7.1 (current main before the change).
  • Same with a stale socket file (no listener) and a missing socket file.
  • A client offering h2 on a route with an h2 destination reaches the h2 destination; an h1-only client reaches h1.
  • All peers refuse: client closed, upstream_connect counted once.
  • Ingress listener and suspended routes unchanged; passthrough behavior from Forward a passthrough connection to a peer when its local connect fails #81 unchanged.
  • npm test, cargo test, cargo clippy --all-targets, cargo fmt --check pass; per-connection future budget test passes.
  • Do not change host-manager or the failoverIngress wire format.

Dispatch: task symphony-83-tls-terminating-connect-forward · queued by kris-session · ran by claude/opus/xhigh · worker kzyp-xps-1

Deferred findings

  • 7f7b569091b7f0dd nit reliability — src/proxy_conn.rs — replacement connect after handshake uses full upstream_connect_timeout (30 s without protection) — NOT FILED

Review-Coverage: authored=gemini; ran=muse,codex,cursor-composer,claude,cursor-grok; late=cursor-grok:adjudicated; adjudicated=domain; blocked=claude(fallback)(out-of-budget); rounds=8; full=3 @ 786025b

Review-Attention: study ~9m (decisions: connect-before-handshake, balancer-guard-across-handshake, handshake-budget-shared, upstream-connect-metric-semantics, readiness-close-check, do-less-alternative, requirement-shift, perf-cost; raised: open major) @ 786025b

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request enables TLS-terminating failover routes to connect to their upstreams before the TLS handshake, allowing the connection to be forwarded to a peer if the local connect fails. It introduces ALPN prediction to select the correct upstream destination early, handles replacing connections that close during the handshake, and adds comprehensive test coverage. A critical compilation issue was identified in src/upstream.rs where std::task::Context::from_waker is passed a Waker by value instead of by reference.

Comment thread src/upstream.rs Resolved
@kriszyp
kriszyp marked this pull request as ready for review November 6, 2026 20:42
kriszyp and others added 2 commits November 6, 2026 13:52
… fails

A TLS-terminating failover route connected to its upstream after the handshake,
which had already consumed the hello, so the connection that discovered a dead
upstream was lost. It now connects while a complete hello is still unread, on a
client listener and not suspended: a failure goes to the peers as raw TLS, and a
success is kept for after the handshake.

The destination is predicted from the hello's ALPN offer and the route's
protocol list. The negotiated protocol still decides; the early connection is
replaced if it disagrees, or if the reactor has seen the upstream close it. A
route that requires a client certificate stays handshake-first, so a client with
no certificate cannot reach the upstream.

Refs #83

Dispatch-Task: symphony-83-tls-terminating-connect-forward
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Dispatch-Task: pr-maint-b9fcd85adedac6da46e26060a31608c4
Co-Authored-By: Gemini <noreply@google.com>
A client that closes right after its reply can leave a stream error on the
route, depending on timing, so asserting no errors at all fails intermittently.

Refs #83

Dispatch-Task: symphony-83-tls-terminating-connect-forward
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Dispatch-Task: pr-maint-b9fcd85adedac6da46e26060a31608c4
Co-Authored-By: Gemini <noreply@google.com>
@kriszyp
kriszyp force-pushed the fix/tls-terminating-connect-forward branch from 1a882ba to 786025b Compare November 6, 2026 21:08
@kriszyp
kriszyp merged commit 02578ab into main Nov 6, 2026
22 of 24 checks passed
@dawsontoth
dawsontoth deleted the fix/tls-terminating-connect-forward branch November 20, 2026 17:47
kriszyp added a commit that referenced this pull request Nov 28, 2026
Sync package + platform + crate versions to 1.8.0. Adds opt-in mtls.failureHoldMs/failureHoldJitter (#98), case-insensitive SNI/Host matching (#94), and failover forwarding/probe fixes (#85, #86).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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