Skip to content

SessionHandler, DialSession and a certificate pin for reversed roles - #22

Merged
myleshorton merged 6 commits into
mainfrom
feat/session-handler
Nov 5, 2026
Merged

myleshorton merged 6 commits into
mainfrom
feat/session-handler

Conversation

@myleshorton

Copy link
Copy Markdown
Contributor

Lets a caller take samizdat's authenticated connection on either end and run its own protocol on it, and lets a client pin the server's certificate. Lantern's reverse direct mode for personal proxies needs both: the TLS server (the inviter's portal) runs an HTTP/2 client, and the TLS client (the helper's bridge) runs an HTTP/2 server.

Why

Today the TLS client is always the HTTP/2 client. In reverse direct mode the helper dials out to the inviter, because the inviter can accept connections and the helper can't. The inviter's traffic then flows back down that connection and exits from the helper. So the roles reverse. The helper also learns the inviter's certificate from a sealed blob, and must refuse anyone else listening on that address.

What changes

  • Server: ServerConfig.SessionHandler. func(ctx, conn net.Conn, shortID [8]byte), called once per authenticated connection in place of the built-in HTTP/2 CONNECT server. Handler may be nil when it's set.
    • Probes that fail authentication still go to the masquerade.
    • conn is the TLS connection (ALPN h2 negotiated). SessionConnFromContext and ShortIDFromContext work on its ctx.
    • Each session has its own ctx. It ends when the session ends:
      • SetShortIDs revokes the session's short ID (cause ErrSessionRevoked);
      • Server.Close runs (ErrServerClosed);
      • the conn is closed;
      • a Read fails, other than on a read deadline;
      • any Write fails. A write timeout counts too, because crypto/tls refuses every later Write once one has timed out.
    • The server closes the TLS connection when the handler returns. Server.Close waits for handlers, so they must return once ctx is done.
  • Client: (*Client).DialSession(ctx) returns a new authenticated connection that is not pooled and runs no HTTP/2. The caller owns it.
    • It returns an error after Close.
    • It applies ConnectTimeout to the whole dial and handshake when ctx has no deadline.
    • On failure it returns a nil net.Conn, not a typed nil.
  • Client: ClientConfig.ServerCertSPKISHA256. When set, the leaf certificate's SPKI SHA-256 must match it, or the handshake fails with ErrCertPinMismatch. NewClient rejects a pin that is neither empty nor 32 bytes. The certificate is still not checked against a CA.
  • SPKISHA256(certDER) computes that pin.
  • createTransport is split into dialConn plus the HTTP/2 transport. DialContext and its pooling behave as before.
  • An isClosed() helper replaces a duplicated check.

Testing

  • go build ./... and go vet ./... are clean, and go test -race -count=1 -timeout 5m ./... passes.
  • New tests:
    • The SessionHandler gets the authenticated conn and the right short ID.
    • NewServer needs a handler.
    • The session ctx ends on a client disconnect, on revocation, and on a write timeout, but not on a read timeout.
    • ConnectionState is still reachable through the wrapper.
    • The pin accepts the right certificate and refuses a wrong one with ErrCertPinMismatch.
    • DialSession after Close, with a cancelled ctx, and under ConnectTimeout returns a nil conn.
    • TestReversedHTTP2Roles: the TLS server runs http2.Transport.NewClientConn and the TLS client runs http2.Server.ServeConn. A PING and a CONNECT round trip pass, and the handler returns when the client closes, without Server.Close.
  • Each fix was checked by restoring the old code: the matching test fails.

Risk

  • Existing users of Serve / Handler / DialContext see no change. The new paths are opt-in.
  • Riskiest file: server.go, where the session wrapper and its cancel paths live.
  • With the roles reversed, the TLS server sends the HTTP/2 client preface. It's inside TLS, so only record sizes and timing could show it.
  • DialSession errors include the server address, as DialContext's do, so callers must redact them before logging.

How to revert

Revert the merge commit. Nothing depends on these APIs until lantern-box's reverse direct mode lands.

Pre-PR review (local Codex gate)

  • Rounds: 3. Final: CODEX GATE: verdict=approve critical=0 important=0 minor=0 preexisting=0 reviewed=12
  • Reviewed at: 808687a
  • Exit: approve
  • Step back: not needed
  • Fixed:
    • client.go:134: DialSession returned a typed-nil net.Conn on a failed dial (r1, fixed in 61018a9).
    • server.go:404: a write timeout poisoned the TLS conn but left the session ctx live (r2, fixed in 808687a).
    • Before the gate, the task review found that the SessionHandler ctx only ended on Server.Close, so a disconnect or revocation leaked the handler (fixed in 091456c).
  • Dismissed: none
  • Pre-existing: none
  • Proposed AGENTS.md additions: none

🤖 Generated with Claude Code

https://claude.ai/code/session_01KqE58aYaai3u8CFZe5nXdE

Adam Fisk and others added 6 commits November 5, 2026 14:15
The ctx was derived from the server's alone, so only Server.Close ended
it. A handler that waits on ctx.Done() leaked on every disconnect or
short ID revocation. Each session now has its own ctx, cancelled by
revocation (ErrSessionRevoked), by the first failed Read or Write on the
conn the handler gets, or by closing it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KqE58aYaai3u8CFZe5nXdE
crypto/tls fails every Write after one times out, so treating a write
deadline like a read deadline left the session's ctx live on an unusable
conn. Only read timeouts are ignored now.

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 November 5, 2026 21:32
@coderabbitai

coderabbitai Bot commented Nov 5, 2026

Copy link
Copy Markdown

Warning

Review limit reached

This review ran on the open-source allowance, not this organization's plan, because the pull request author doesn't have an assigned seat. Waiting won't change this — ask an organization admin to assign them a seat, or add seats in Billing if every seat is already assigned, then retry.

Next included review available in 24 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

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: 92cf069d-06ee-4bc7-a8ff-18f841efcd2e
Commits

Reviewing files that changed from the base of the PR and between 2ea6ea8 and 808687a.

Files selected for processing: 6

  • client.go
  • reverse_test.go
  • samizdat.go
  • server.go
  • session_test.go
  • shortids_test.go
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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 remain for the authenticated-session and certificate-pinning changes.

No open issues 🎉

What changed in this PR

Adds authenticated sessions that callers can use for their own protocols, enabling reversed HTTP/2 roles for personal proxies. Optional certificate pinning lets clients verify the server’s public key.

Changes:

  • Adds SessionHandler and unpooled DialSession, while retaining the existing HTTP/2 CONNECT path.
  • Adds SHA-256 SPKI certificate pinning and a helper to compute pins.
  • Adds tests for session lifecycle, cancellation, timeouts, certificate pins, and reversed HTTP/2 roles.
File Description
shortids_test.go Adapts session-tracking tests to the cancellation parameter.
session_test.go Tests session APIs, lifecycle behavior, timeouts, and certificate pinning.
server.go Dispatches custom session handlers and manages session cancellation.
samizdat.go Defines and documents the session handler and certificate-pin configuration.
reverse_test.go Verifies reversed HTTP/2 roles with PING and CONNECT exchanges.
client.go Adds raw session dialing, certificate pinning, and shared TLS connection setup.

Review effort: Balanced

@myleshorton
myleshorton merged commit 38715c2 into main Nov 5, 2026
4 checks passed
@myleshorton
myleshorton deleted the feat/session-handler branch November 5, 2026 22:52
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