Skip to content

Close ends every accepted connection instead of waiting for it - #19

Merged
myleshorton merged 1 commit into
mainfrom
fisk/close-sessions
Oct 27, 2026
Merged

myleshorton merged 1 commit into
mainfrom
fisk/close-sessions

Conversation

@myleshorton

@myleshorton myleshorton commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Server.Close now ends every connection the server accepted, then waits for their goroutines. Until now it cancelled its context, closed the listener and waited, and each connection's goroutine lived until the client left. So Close blocked for as long as any session stayed open, and the sessions kept proxying.

This matters for Lantern's volunteer peers ("direct mode"). radiance rotates a volunteer's inbound hourly and, with helper invites, as soon as the user turns off "help others too". It closes the old sing-box, gives up waiting after a timeout, and the old samizdat sessions keep running. So a volunteer who stops serving strangers still serves every stranger already connected, and rotated-out credentials keep working on open sessions.

What changed

  • Serve records each accepted connection and adds it to the wait group under one lock, checking a closed flag. A connection accepted after Close started is closed at once instead of handled.
  • Close cancels the context, marks the server closed, closes the listener (first call only), closes every recorded connection, then waits. Calling it twice is safe.
  • Serve returns at once if Close already ran before it recorded the listener. Previously that case accepted forever.
  • Each connection path now ends on Close:
    1. Reading the ClientHello: the connection is closed, so the read fails.
    2. Masquerade dial: it now uses DialContext(s.ctx) through an unexported proxyConnection(ctx, …). The public ProxyConnection keeps its signature.
    3. Masquerade copy: a context watcher closes both the origin and client connections. Closing only the client left the origin-to-client copy blocked while the origin held its side open.
    4. Authenticated TLS handshake: it already used HandshakeContext(s.ctx), and its connection is now closed too.
    5. http2.ServeConn: closing the raw connection ends it. Streams see an ordinary disconnect, the same as a SetShortIDs revoke.
  • SetShortIDs and the sessions map are unchanged.

Testing

  • go test -race -count=1 ./... and go vet ./... pass, which is what CI runs.

  • close_test.go adds four tests, each of which failed before the fix:

    • an authenticated session with an open CONNECT tunnel;
    • a masquerade connection to an origin that holds its side open;
    • a raw connection that sent only part of a TLS header;
    • 64 dials racing Close, followed by a second Close.

    Each asserts that Close returns within 1 s and that the client then sees a real error, not a timeout. The new tests and the SetShortIDs tests also passed 10 runs in a row under -race.

  • Not tested: a masquerade dial cancelled mid-dial, because a hanging dial can't be reproduced reliably on a local machine.

Risk

  • Every consumer's Close now drops live sessions instead of letting them drain. In lantern-box's samizdat inbound, that means a radiance volunteer's hourly credential rotation drops open sessions, paired ones included, and clients reconnect within seconds. That is the behaviour radiance's rotation already assumed.
  • The wait group covers connection goroutines, not http2 handler goroutines. After Close returns, a handler's own outbound dial or copy can take a moment to notice its stream is gone. That is unchanged.
  • Riskiest file: server.go.

How to revert

Revert the merge commit. Nothing else depends on it until lantern-box bumps its samizdat pin.

Pre-PR review (local Codex gate)

  • Rounds: 1 — final: CODEX GATE: verdict=approve critical=0 important=0 minor=0 preexisting=0 reviewed=12
  • Reviewed at: dd65ff6
  • Exit: approve
  • Step back: not needed
  • Fixed: none
  • Dismissed: none
  • Pre-existing (not introduced here, worth filing): none
  • Proposed AGENTS.md additions: none

GitHub review

  • Copilot (dd65ff6): approval recommended, no issues.
  • CodeRabbit (dd65ff6): review completed, no actionable comments.

🤖 Generated with Claude Code

https://claude.ai/code/session_01KqE58aYaai3u8CFZe5nXdE

Server.Close cancelled the context, closed the listener and waited for the
connection goroutines, but nothing ended those connections: an H2 session
ran until the client hung up, so Close blocked indefinitely and the session
kept proxying. lantern-box's inbound Close calls it, so rotating or turning
off a volunteer's inbound left open sessions serving.

Serve now records every accepted connection (and adds it to the wait group)
under a lock that Close takes to mark the server closed, so a connection is
either seen by Close or refused and closed on arrival. Close closes them all
before waiting, which ends authenticated sessions, handshakes in progress and
connections still sending a ClientHello. The masquerade path also watches the
server context: the dial to the origin is abandoned and the origin connection
is closed too, since a held-open origin would otherwise keep the copy loop
alive. Close is idempotent, and a Serve that starts after Close returns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KqE58aYaai3u8CFZe5nXdE
Copilot AI balanced review requested due to automatic review settings October 27, 2026 21:46
@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 87036ef0-7c02-4fd2-9b55-429a7b19729c
Commits

Reviewing files that changed from the base of the PR and between 34a7d25 and dd65ff6.

Files selected for processing: 3
  • close_test.go
  • masquerade.go
  • server.go

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Walkthrough

The server now tracks accepted connections and closes them during shutdown. Masquerade proxying uses a context-aware dial that closes both connections when canceled. New tests cover shutdown of active sessions, masquerade connections, incomplete ClientHello connections, and connections accepted while shutdown races.

Changes: Server connection shutdown

Layer / File(s) Summary
Track and close accepted connections
server.go, close_test.go
The server tracks accepted connections, rejects connections after shutdown begins, closes the listener and tracked connections, and waits for handler goroutines. Tests cover active sessions, incomplete ClientHello connections, repeated closes, and racing accepts.
Cancel masquerade proxy connections
masquerade.go, server.go, close_test.go
ProxyConnection delegates to a context-aware method that uses DialContext and closes both connections when canceled. Server masquerade forwarding calls this method, and a test checks that shutdown closes the masquerade probe connection.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Server
  participant Listener
  participant AcceptedConnection
  participant Handler
  Server->>Listener: Close listener
  Server->>AcceptedConnection: Close tracked connections
  Server->>Handler: Wait for handler goroutines
Loading
Merge Risk: Minimal · up to dd65f

The shutdown change is ready to merge after normal checks; no concrete unresolved failure is established.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surv… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly summarizes the primary change: Server.Close now ends accepted connections instead of waiting for them to close.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 8 functions across 3 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

Copilot AI 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.

🟢 Approval recommended

No active review issues are reported for the server shutdown and connection-termination changes.

No open issues 🎉

What changed in this PR

This PR makes Server.Close terminate accepted connections rather than wait for clients to disconnect, ensuring shutdown and volunteer-peer rotation stop existing sessions.

Changes:

  • Tracks accepted connections and coordinates registration with shutdown, including repeated Close calls and listener-startup races.
  • Cancels masquerade dialing and closes both proxy connections when the server shuts down.
  • Adds shutdown tests for authenticated sessions, masquerade traffic, partial TLS headers, and racing accepts.
File Description
server.go Tracks and closes accepted connections before waiting for their goroutines.
masquerade.go Adds context-aware cancellation while preserving the public ProxyConnection signature.
close_test.go Tests connection termination, shutdown timing, and repeated closure.

Review effort: Balanced

@myleshorton
myleshorton merged commit 50f4385 into main Oct 27, 2026
4 checks passed
@myleshorton
myleshorton deleted the fisk/close-sessions branch October 27, 2026 21:51
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.

2 participants