carlos / platform Public

tunnelclient: the box half of tunnel WebSockets (#471 Task 1)

Mark now serves through an upgrade shim: a stream carrying
Carlos-Tunnel-Upgrade reaches the box edge as an HTTP/1.1-shaped
upgrade (Connection/Upgrade rebuilt, body NoBody, ContentLength 0)
with a writer whose Hijack answers the hub with an HTTP/2 200 marked
Carlos-Tunnel-Upgraded: 1 and returns a net.Conn over the stream
(reads the request body, writes flush per Write). An invalid token
gets 400 and never reaches the edge. Every response written without a
hijack loses an app-set Carlos-Tunnel-Upgraded. Requests without the
marker pass through unchanged.

Dial advertises Carlos-Tunnel-Caps: upgrade/1. The box's h2 server
limits are data: Limits / DefaultLimits (250 streams, 1 MiB stream
window, 160 MiB connection window), ServeWith, Config.Limits resolved
by Loop and passed through serveUntilDead. Serve keeps its signature
and uses DefaultLimits.

Spec §7 records what the census card shows for the package.

Upgrades stay refused at the hub until Task 5.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 13985af5717364cfa03a2be6af65097689d510fe parent 464897b
4 files changed, +910 −14
  • docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md +12 −0
  • internal/tunnelclient/tunnelclient.go +24 −14
  • internal/tunnelclient/upgrade.go +343 −0
  • internal/tunnelclient/upgrade_box_test.go +531 −0

Intent

Human

<task-notification> <task-id>ae788846b0095491a</task-id> <tool-use-id>toolu_01YYDCyQZqRMgnSHRsJDVXfL</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/ae788846b0095491a.output</output-file> <status>completed</status> <summary>Agent "Draft #471 WebSocket tunnel spec" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Plan rev 2 resolves all six round-1 findings, and the branch is pushed. The tip is **464897b7**, and `ls-remote` shows the same commit on amadan. - **8d3bd5f1**: plan rev 2, plus the R1 findings file committed alongside it. - **464897b7**: `CODEX-REVIEW-BRIEF-tunnel-websockets-plan-R2.md`, round 2 of 3, naming 8d3bd5f1. It carries your round-1 rulings as fixed and says where rev 2 answers each finding. The plan now has a dispositions table for round 1. I checked each finding against the code before fixing it: - **P1-1 (the real tunnel loop can't trust the TLS fixture):** Confirmed. `Dial` builds its own TLS config with no `RootCAs` (`tunnelclient.go:206-209`), so it verifies against the system roots, and Go on Linux reads `SSL_CERT_FILE` when it first loads those (`root_unix.go:36`). - The new helper is `runTrustedChild` in `internal/edge/trusted_child_test.go`. The parent writes a fresh fixture CA and leaf, then re-runs its own test binary for that one test with `SSL_CERT_FILE` set to the CA and `SSL_CERT_DIR` set to an empty directory. - `tunnelclient.Dial` is unchanged and certificate verification stays on; there is no production trust seam. - The child's first assertion is that `home/box-1` reaches "connected" within 5 s. A control test, `TestTrustedChildIsNeeded`, uses an unrelated CA and must never connect, with an `x509` unknown-authority error. - The helper only works on Linux, because macOS and Windows ignore `SSL_CERT_FILE`, so the test file carries `//go:build linux`. CI runs Linux. - Task 7's real-loop tests use the same helper. - **P1-2 ("Enqueue a job" reloads the page):** Confirmed. `button_to` posts a normal form and the controller redirects. - The inline script now intercepts that form and sends the same POST with `fetch`, using the form's own data (so its CSRF token goes with it) and no navigation. - The page used to update only "Jobs done", which would have left the total stale. `PingJob` now broadcasts `done` and `total`, so both counts change from the broadcast alone. - No new visible words: two spans wrap the existing numbers. - Task 10 checks in a browser that the page doesn't navigate and the `/cable` socket stays the same connection. - **P2-3 (incomplete caller and limits inventory):** `serveUntilDead` now takes the limits and calls `ServeWith`, and a new test (`TestLoopAppliesConfigLimits`) reads the advertised settings through the real `Loop`. - The `Loop` caller in `fleet_public_routes_e2e_test.go:500` is listed. - All 20 files that call `NewTunnelHub` or `EnableTunnels` are listed and need no edits; Task 3 re-runs their packages' tests. - `EnableTunnels` is in Task 5's changed functions and census step. A hub built without it refuses upgrades with `errNoAdmission` instead of panicking, and has its own test. - **P2-4 (the `-tunnel` arm lacked the full witness):** Task 6 adds case 2b: case 2 in full (gate, login, protocol, messages both ways, cookie stripped, `X-Forwarded-Proto: https`) through a static `-tunnel` route on the real box edge and shim. - **P2-5 (the local container check never started the server):** Confirmed: the image has no `CMD`, puma binds `CARLOS_SOCKET` or `PORT`, and the database path comes from `CARLOS_DB`. - Step 1 runs `carlos ship --check` with the guide's placeholders. - Step 2 starts a loopback-only container running the `release` then `web` commands from `processes.json`, with `PORT=3000` and `CARLOS_DB` set. - It then sends a handshake with origin `https://127.0.0.1:3000`. The origin is https because production sets `assume_ssl`, which makes Rails report every request as https. - **P2-6 (wrong delete command, and a purge that doesn't exist):** Task 10 now runs `carlos apps delete --account bab cable`, with the app name positional (`apps.go:240-248`). - There is no purge step. `cable` stays in the Trash for 30 days and is then purged automatically. - While it waits it runs nothing: its routes drop at delete and the box retires its instance. It keeps only its release image in the fleet's store and holds the name `cable`. D-1 is still open for Task 10's live revocation. Rev 2 keeps option (a), the throwaway `cable` app, and Step 4 follows that option.</result> <usage><subagent_tokens>482799</subagent_tokens><tool_uses>13</tool_uses><duration_ms>221454</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bbd21c7x5</task-id> <tool-use-id>toolu_01CaoN5TT4wv1cqfg5xzWRmZ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bbd21c7x5.output</output-file> <status>completed</status> <summary>Background command "Run Astra plan review round 2 on #471" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a6df1701ef5c7b658</task-id> <tool-use-id>toolu_01NsmS1RmmEtbe4iqvDVk9tn</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a6df1701ef5c7b658.output</output-file> <status>completed</status> <summary>Agent "Write the Plan 6 amendment" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I've written the amendment into the plan, revised the copy deck, written the Astra brief, and pushed to origin `rootfs-apps-6-interactive`. Tip is `5d802f2e18c0107c04c0e7a149a2baeab47a2465`, confirmed with `git ls-remote`. No code changed. Two tests in the root package's copy gate, `TestRootfsCopyDeckParses` and `TestRootfsCopyRecordIsComplete`, now fail on the branch. Adding the RFS-6-C65 row to the deck means it no longer matches the gate's pinned id list, `rootfsCopyIDs` in `approved_rootfs_copy_test.go`. I left that test file alone because you said not to touch code. The fix is one line, adding "RFS-6-C65" to that list, in the commit that applies Paul's review. I ran the gate and these were the only two failures. **Changed tasks** - **Task 7a (new):** `carlos run` on rootfs rows, without `--version`. It reuses Plan 3's rootfs command start (already used by the release command), passes rootfs records through the "does not sleep" check, and builds RFS-3-C27. - **P1 #1 (command outlives the lease):** at the moment the lease is lost, root now kills the run's unit outright, alongside the generations and workers. The run is also stopped gracefully when the lease starts running short, even if the instance is already stopping. A start still in progress is killed again when it returns, and a run only starts if the lease has enough time left. - **P1 #4 (run directory deleted too early):** a new callback, `CmdSpec.AfterSettled`, removes the run directory only once the unit is proven gone. That covers a start that may have begun. - RFS-3-C27 moves into Plan 3's landed copy group, so `TestPlan3CopyGroups` stays green. - **Task 9:** the session's unit is killed at lease loss the same way. Sessions are not refused while a release command runs. The four idle and stop checks and the stop's cancel cover both runs and sessions. - **Task 10:** the session door ends its request's lifetimes unit at the WebSocket upgrade. Admission and the end each take their own short write unit through a new helper, `lifetimesStep`. A refused admission ends the session with RFS-6-C37; a refused end is parked and finished by the sweep. It also gets the request budget, the perf-log skip, `provision.Incarnation` and the rootfs pass. A test checks a cutover drains and activates while a session stays open. - **Task 11:** the box door is exempt from lifetimes (it reads no record). The sweep finishes parked ends with their real reason. The fleet check now also requires the fleet to belong to the session's account. Tests cover the drain with a live session and the parked-end finish. - **Task 16:** the run relay takes a unit per record write and none for the connection. Same fleet owner check, region-HA rule and judged reads. It strikes RFS-3-C28 (deck, struck list and Plan 3's copy group) and gets a rootfs fleet-run test. - **Tasks 1, 3–8, 12–15:** - Task 1 Step 2 is no longer a stop, and copy is pending. - Task 3 makes the record marker go through the lifetime judge. - Task 4 gets the new `appsSetRun` signature, the occurrence count, and the zero-downtime copy record. - Task 5 gets the tty name rules, the `--rootfs tty` exit line and the binary probe's `/dev/pts` wiring. - Task 6 gets the fifth client verb and per-role locks. - Task 7 adds `tty` to `instance-exit`. - Task 8 gets the optional `TTYControl` interface, a role-aware unit, and `b.tier(rt)`. - Task 12 gets `HoldsAwake` and judged reads. - Task 13 refuses `-it` with `--idempotency-key`. - Task 14 places its paragraphs after C27. - Task 15 rolls dev first and adds a rootfs run witness. - Stale file:line references now point at "see preflight §1 row N". **Copy rows (both `pending` in the deck and the plan's string table)** - **RFS-6-C47:** `apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow, --size or --interactive` - It appears in `apps_swap.go` as `appsSetNothing`, when `carlos apps set &lt;app&gt;` gets no setting flag. It's a CLI error and exits 1. - It replaces today's approved text (IP1-57): `apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow or --size`. The first draft of C47 read `… --interactive or one of the update settings`. - The same text is also held by the zero-downtime record `zdd.apps-set.nothing`, which Task 4 updates in the same commit. - For Paul: both today's line and this draft leave out the update-policy flags (`--instance-control`, `--default-updates`, `--default-channel`, `--default-major`), which also count as something to set. - **RFS-6-C65 (new):** `-it takes no --idempotency-key. a session is never repeated by a retry` - It appears from `parseRunArgs` in `run.go` when `carlos run -it` (or `--interactive`) is given with `--idempotency-key`. It prints to stderr, then the usage text, and exits 2. - Its neighbours are C03–C05 (`-it takes no --file…`) and today's `--idempotency-key is for starting a run. --follow starts none`. **Not settled** 1. **Root kill at lease loss (Call A1).** The preflight's ruling for this (PF-3) said to stop runs and sessions the way workers are stopped, with no kill. That alone doesn't fix Astra's P1 #1: a command that ignores SIGTERM keeps running for up to 20 s after the loss, and Astra's own fix asked for a root-side change. So the plan adds `kill=1` for rootfs run and session units. It's a new root verb that needs a census approval on #280. It's written up in the amendment and is item 1 in the review brief. Workers keep the old behaviour and the same exposure. 2. **The gate's id list:** the red copy gate described at the top. 3. **The series index** still lists rootfs `carlos run` and `--version` under Plan 3. The amendment notes it, but I didn't edit the index. Files: - `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/docs/superpowers/plans/2026-10-24-rootfs-apps-6-interactive.md` - `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md` - `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-plan6-amendment.md` (round 1 of 3)</result> <usage><subagent_tokens>425271</subagent_tokens><tool_uses>166</tool_uses><duration_ms>1466667</duration_ms></usage> </task-notification>

Attributed to this commit: 40.3 g CO₂e (5,227,000 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-tunnel-websockets-471, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
index 0dd80a2dc..1ff90669f 100644
--- a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
+++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
@@ -961,6 +961,18 @@ a card. Expected classes:
the agent, and the only new input is bytes on the tunnel, which the box
already trusts the hub for and the hub already trusts the box for (1a).
+What the card shows for `internal/tunnelclient` (Task 1, `make
+census-card`): the envelope re-pinned, and one `new` unit,
+`upgrade.go:upgradedConn.Read`, with `reads +file:Read ×2`. That is the
+scanner matching the name `Read`: the method reads the stream's HTTP/2
+request body (the hub's bytes, `c.body.Read`), not a file or root-owned
+state, so "no `reads`" above stands. The `body` units listed above for
+this package (`Dial`, `Serve`, `markedHandler.ServeHTTP`) and the other
+new declarations (`ServeWith`, `ValidUpgradeToken`, `Limits`, the shim's
+writer, the constants) have no census row because they read nothing;
+their changes are covered by the envelope re-pin, which the reviewer
+reads function by function.
+
The reviewer is Astra (Claude author), recorded on #280.
Copy. Two new cause descriptions in `internal/apperr/availability.go`
diff --git a/internal/tunnelclient/tunnelclient.go b/internal/tunnelclient/tunnelclient.go
index e4718c3fe..9c3ec791a 100644
--- a/internal/tunnelclient/tunnelclient.go
+++ b/internal/tunnelclient/tunnelclient.go
@@ -26,8 +26,6 @@ import (
"net/http"
"net/url"
"time"
-
- "golang.org/x/net/http2"
)
// The two states Loop reports through Config.OnState. "" (never reported
@@ -76,6 +74,10 @@ type Config struct {
// Logf defaults to log.Printf. The agent passes one that prefixes
// "agent: " so the journal lines stay exactly what operators grep for.
Logf func(format string, args ...any)
+ // Limits sets the HTTP/2 server's stream count and receive windows on
+ // the tunnel conn; nil means DefaultLimits. Tests pass small ones to
+ // reach the limits without production-sized traffic.
+ Limits *Limits
}
// Loop dials cfg.URL and serves cfg.Handler over the inverted conn, forever,
@@ -94,6 +96,10 @@ func Loop(ctx context.Context, cfg Config) {
cfg.OnState(s)
}
}
+ limits := DefaultLimits
+ if cfg.Limits != nil {
+ limits = *cfg.Limits
+ }
backoff := BackoffFloor
for ctx.Err() == nil {
// Set BEFORE dialing, not only on error: Dial can block for up to
@@ -117,7 +123,7 @@ func Loop(ctx context.Context, cfg Config) {
setState(StateConnected)
logf("tunnel connected as %q", cfg.Name)
connectedAt := time.Now()
- serveUntilDead(ctx, conn, Mark(cfg.Handler)) // blocks until the conn dies
+ serveUntilDead(ctx, conn, Mark(cfg.Handler), limits) // blocks until the conn dies
setState(StateReconnecting)
logf("tunnel lost — re-dialing")
// A connection that stayed up a while earns a fast retry (the
@@ -152,10 +158,10 @@ func wait(ctx context.Context, d time.Duration) bool {
}
}
-// serveUntilDead is Serve plus cancellation: http2.Server.ServeConn blocks
+// serveUntilDead is ServeWith plus cancellation: http2.Server.ServeConn blocks
// until the conn dies and has no other stop signal, so closing the conn is
// how a cancelled ctx gets Loop back.
-func serveUntilDead(ctx context.Context, conn net.Conn, handler http.Handler) {
+func serveUntilDead(ctx context.Context, conn net.Conn, handler http.Handler, l Limits) {
done := make(chan struct{})
go func() {
select {
@@ -165,7 +171,7 @@ func serveUntilDead(ctx context.Context, conn net.Conn, handler http.Handler) {
}
}()
defer close(done)
- Serve(conn, handler)
+ ServeWith(conn, handler, l)
}
// bufferedConn replays bytes the handshake's bufio.Reader over-read (the h2
@@ -232,6 +238,7 @@ func Dial(ctx context.Context, rawURL, name, token string) (net.Conn, error) {
Header: http.Header{
"Authorization": {"Bearer " + token},
"Carlos-Tunnel-Name": {name},
+ CapsHeader: {CapUpgrade},
"Connection": {"Upgrade"},
"Upgrade": {"carlos-tunnel/1"},
},
@@ -279,15 +286,18 @@ func FromTunnel(ctx context.Context) bool {
type markedHandler struct{ h http.Handler }
func (m markedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- m.h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), tunnelKey{}, true)))
+ upgradeShim{m.h}.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), tunnelKey{}, true)))
}
-// Mark wraps h so every request it serves carries the tunnel mark. Loop
-// applies it; a caller using Serve directly applies it itself if it wants
-// the mark.
+// Mark wraps h so every request it serves carries the tunnel mark, through
+// the upgrade shim (upgrade.go): a request the hub marked with
+// UpgradeHeader reaches h as an HTTP/1.1-shaped upgrade with a hijackable
+// writer; any other request reaches h unchanged. Loop applies it; a caller
+// using Serve directly applies it itself if it wants the mark. The shim
+// lives here, on the tunnel's serving path only: on the box's public
+// listener the marker is an ordinary header.
func Mark(h http.Handler) http.Handler { return markedHandler{h} }
-// Serve serves handler over the inverted conn until it dies.
-func Serve(conn net.Conn, handler http.Handler) {
- (&http2.Server{}).ServeConn(conn, &http2.ServeConnOpts{Handler: handler})
-}
+// Serve serves handler over the inverted conn until it dies, with
+// DefaultLimits.
+func Serve(conn net.Conn, handler http.Handler) { ServeWith(conn, handler, DefaultLimits) }
diff --git a/internal/tunnelclient/upgrade.go b/internal/tunnelclient/upgrade.go
new file mode 100644
index 000000000..6f31ea6d7
--- /dev/null
+++ b/internal/tunnelclient/upgrade.go
@@ -0,0 +1,343 @@
+package tunnelclient
+
+// The box half of an upgraded connection through the tunnel (#471, spec
+// §4.3 steps 6 and 8, §4.4, §4.8, §4.9).
+//
+// HTTP/2 has no Connection or Upgrade header, so the hub carries the
+// upgrade token in UpgradeHeader on an ordinary stream whose request body
+// stays open. upgradeShim, inside Mark, turns that stream back into an
+// HTTP/1.1-shaped upgrade request for the box's edge and hands it a writer
+// whose Hijack answers the hub with an HTTP/2 200 marked UpgradedHeader and
+// returns a net.Conn over the stream: reads are the request body, writes
+// are the response body. The edge's reverse proxy then writes the app's 101
+// into that conn and splices, exactly as it does on its own listener.
+
+import (
+ "bufio"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "golang.org/x/net/http/httpguts"
+ "golang.org/x/net/http2"
+)
+
+const (
+ // UpgradeHeader carries the requested Upgrade token from hub to box.
+ // Only the hub's RoundTripUpgrade writes it; the hub scrubs a client's
+ // copy, and the shim honours it only on the tunnel's serving path.
+ UpgradeHeader = "Carlos-Tunnel-Upgrade"
+ // UpgradedHeader, set to "1" on an HTTP/2 200, tells the hub the box
+ // hijacked the stream and the body starts with the app's in-band 101.
+ // The shim deletes an app-set copy from every response it did not
+ // hijack, so an app cannot make the hub read its body as a 101.
+ UpgradedHeader = "Carlos-Tunnel-Upgraded"
+ // CapsHeader is sent on /register; CapUpgrade says this box runs the
+ // shim. Additive: an old hub ignores it (§4.9).
+ CapsHeader = "Carlos-Tunnel-Caps"
+ CapUpgrade = "upgrade/1"
+ // MaxUpgradeTokenLen bounds the Upgrade token, both ends.
+ MaxUpgradeTokenLen = 64
+)
+
+// Limits are the box's HTTP/2 server limits on the tunnel connection
+// (§4.8): how many streams the hub may open, and how much the hub may send
+// ahead of the box's reads per stream and per connection.
+type Limits struct {
+ MaxStreams uint32
+ StreamWindow, ConnWindow int32
+}
+
+// DefaultLimits are the production values. MaxStreams is x/net's own
+// default, pinned so a library change cannot move it; StreamWindow is
+// today's 1 MiB; ConnWindow is raised from 1 MiB so the hub's cap of open
+// upgrades, each holding at most StreamWindow, still leaves PlainHeadroom
+// for plain request bodies. The hub's cap and the invariant tying these
+// together are asserted in internal/edge (§4.8).
+var DefaultLimits = Limits{MaxStreams: 250, StreamWindow: 1 << 20, ConnWindow: 160 << 20}
+
+// PlainHeadroom is the connection window that open upgrades can never take
+// from plain requests: ConnWindow >= cap x StreamWindow + PlainHeadroom.
+const PlainHeadroom = 32 << 20
+
+// ValidUpgradeToken reports whether tok is one RFC 7230 token of at most
+// MaxUpgradeTokenLen bytes. Every tchar is printable ASCII.
+func ValidUpgradeToken(tok string) bool {
+ if tok == "" || len(tok) > MaxUpgradeTokenLen {
+ return false
+ }
+ for i := 0; i < len(tok); i++ {
+ if !httpguts.IsTokenRune(rune(tok[i])) {
+ return false
+ }
+ }
+ return true
+}
+
+// ServeWith serves handler over the inverted conn until it dies, with the
+// server's stream count and receive windows taken from l.
+func ServeWith(conn net.Conn, handler http.Handler, l Limits) {
+ srv := &http2.Server{
+ MaxConcurrentStreams: l.MaxStreams,
+ MaxUploadBufferPerStream: l.StreamWindow,
+ MaxUploadBufferPerConnection: l.ConnWindow,
+ }
+ srv.ServeConn(conn, &http2.ServeConnOpts{Handler: handler})
+}
+
+// upgradeShim is the box half of an upgrade, applied by Mark. A request
+// without UpgradeHeader passes through unchanged; only its response
+// writer is wrapped, to strip an app-set UpgradedHeader.
+type upgradeShim struct{ h http.Handler }
+
+func (s upgradeShim) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ sw := &shimWriter{w: w}
+ toks, marked := r.Header[UpgradeHeader]
+ if !marked {
+ s.h.ServeHTTP(sw, r)
+ return
+ }
+ // The hub validated the token before opening the stream; anything else
+ // did not come from a hub that runs this code. No body: nothing here
+ // is for a person to read.
+ if len(toks) != 1 || !ValidUpgradeToken(toks[0]) {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ up := r.Clone(r.Context())
+ up.Header.Del(UpgradeHeader)
+ up.Header.Set("Connection", "Upgrade")
+ up.Header.Set("Upgrade", toks[0])
+ // The stream's body is the client-to-app half of the socket: the shim
+ // keeps it for the hijacked conn, and the edge sees an upgrade GET
+ // with no body, as it would on its own listener.
+ up.Body = http.NoBody
+ up.ContentLength = 0
+ up.GetBody = nil
+ up.TransferEncoding = nil
+ sw.body = r.Body
+ sw.local, _ = r.Context().Value(http.LocalAddrContextKey).(net.Addr)
+ sw.remote = r.RemoteAddr
+ defer sw.finish()
+ s.h.ServeHTTP(hijackWriter{sw}, up)
+}
+
+// shimWriter wraps the stream's ResponseWriter. Until a Hijack it is the
+// stream's writer with UpgradedHeader deleted whenever the header could go
+// out (WriteHeader, the first Write, Flush); after one, it is inert and
+// the hijacked conn owns the stream.
+type shimWriter struct {
+ w http.ResponseWriter
+ wroteHeader bool // a final status has gone out (or is about to)
+
+ // Upgrade requests only.
+ body io.ReadCloser // the stream's request body; nil on a plain request
+ local net.Addr
+ remote string
+ conn *upgradedConn // set by Hijack
+ hijackedHdr http.Header // what Header returns after Hijack
+ hijackStarted bool
+}
+
+func (s *shimWriter) Header() http.Header {
+ if s.conn != nil {
+ return s.hijackedHdr
+ }
+ return s.w.Header()
+}
+
+func (s *shimWriter) strip() { s.w.Header().Del(UpgradedHeader) }
+
+func (s *shimWriter) WriteHeader(code int) {
+ if s.conn != nil {
+ return
+ }
+ s.strip()
+ if code >= 200 || code == http.StatusSwitchingProtocols {
+ s.wroteHeader = true
+ }
+ s.w.WriteHeader(code)
+}
+
+func (s *shimWriter) Write(p []byte) (int, error) {
+ if s.conn != nil {
+ return 0, http.ErrHijacked
+ }
+ if !s.wroteHeader {
+ s.strip()
+ s.wroteHeader = true
+ }
+ return s.w.Write(p)
+}
+
+// Flush implements http.Flusher directly: the box's edge wrappers assert
+// it on the writer they are given rather than going through Unwrap.
+func (s *shimWriter) Flush() {
+ if s.conn != nil {
+ return
+ }
+ if !s.wroteHeader {
+ s.strip()
+ s.wroteHeader = true
+ }
+ _ = http.NewResponseController(s.w).Flush()
+}
+
+// Unwrap lets http.ResponseController reach the stream's deadlines.
+func (s *shimWriter) Unwrap() http.ResponseWriter { return s.w }
+
+// finish runs when the edge's handler returns on an upgrade stream: it
+// closes the hijacked conn and waits out any Write still in progress, so
+// nothing touches the stream's writer after the handler is done (x/net
+// forbids it).
+func (s *shimWriter) finish() {
+ if s.conn != nil {
+ s.conn.Close()
+ s.conn.fence()
+ }
+}
+
+// hijackWriter is the writer an upgrade request gets: a shimWriter that is
+// also an http.Hijacker. A plain request's writer is not one, as the
+// stream's own writer is not.
+type hijackWriter struct{ *shimWriter }
+
+var errHijackAfterResponse = errors.New("tunnelclient: hijack after the response began")
+
+// Hijack answers the hub: an HTTP/2 200 carrying only UpgradedHeader,
+// flushed, so the hub's round trip returns and reads the rest of the body
+// as the app's bytes. Headers the edge set before hijacking are dropped,
+// as a hijack drops them on an HTTP/1.1 listener.
+func (h hijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ s := h.shimWriter
+ if s.conn != nil || s.hijackStarted {
+ return nil, nil, http.ErrHijacked
+ }
+ if s.wroteHeader {
+ return nil, nil, errHijackAfterResponse
+ }
+ s.hijackStarted = true
+ hdr := s.w.Header()
+ for k := range hdr {
+ delete(hdr, k)
+ }
+ hdr.Set(UpgradedHeader, "1")
+ s.w.WriteHeader(http.StatusOK)
+ s.wroteHeader = true
+ if err := http.NewResponseController(s.w).Flush(); err != nil {
+ return nil, nil, err
+ }
+ c := &upgradedConn{w: s.w, body: s.body, local: s.local, remote: s.remote}
+ s.conn = c
+ s.hijackedHdr = http.Header{}
+ return c, bufio.NewReadWriter(bufio.NewReader(c), bufio.NewWriter(c)), nil
+}
+
+// upgradedConn is the hijacked stream as a net.Conn: Read is the hub's
+// request body (the client's bytes), Write is the response body with a
+// flush per Write (the app's bytes reach the client as they are written).
+//
+// The stream's writer must not be used after the edge's handler returns,
+// but the reverse proxy's two copy goroutines may outlive its wait on the
+// first. So every use of w holds life for reading, and finish takes it for
+// writing after Close: a Write in progress completes (or fails when the
+// stream ends) before the handler returns, and every later one sees closed.
+type upgradedConn struct {
+ w http.ResponseWriter
+ body io.ReadCloser
+ local net.Addr
+ remote string
+
+ life sync.RWMutex
+ wmu sync.Mutex // one Write+Flush at a time
+ closed atomic.Bool
+ closeOnce sync.Once
+}
+
+func (c *upgradedConn) Read(p []byte) (int, error) {
+ if c.closed.Load() {
+ return 0, net.ErrClosed
+ }
+ return c.body.Read(p)
+}
+
+func (c *upgradedConn) Write(p []byte) (int, error) {
+ c.life.RLock()
+ defer c.life.RUnlock()
+ c.wmu.Lock()
+ defer c.wmu.Unlock()
+ if c.closed.Load() {
+ return 0, net.ErrClosed
+ }
+ n, err := c.w.Write(p)
+ if err != nil {
+ return n, err
+ }
+ return n, http.NewResponseController(c.w).Flush()
+}
+
+// Close stops both directions: later reads and writes fail, and a Read
+// blocked on the stream's body returns. It does not wait for a Write in
+// progress; finish does. The stream itself ends when the handler returns.
+func (c *upgradedConn) Close() error {
+ c.closeOnce.Do(func() {
+ c.closed.Store(true)
+ c.body.Close()
+ })
+ return nil
+}
+
+// fence waits for every use of the writer in progress to finish. Called
+// after Close, so none starts afterwards.
+func (c *upgradedConn) fence() {
+ c.life.Lock() // an empty critical section: a barrier, not a guard
+ c.life.Unlock()
+}
+
+func (c *upgradedConn) LocalAddr() net.Addr {
+ if c.local != nil {
+ return c.local
+ }
+ return streamAddr("")
+}
+
+func (c *upgradedConn) RemoteAddr() net.Addr { return streamAddr(c.remote) }
+
+func (c *upgradedConn) SetDeadline(t time.Time) error {
+ if err := c.SetReadDeadline(t); err != nil {
+ return err
+ }
+ return c.SetWriteDeadline(t)
+}
+
+// The deadlines are the stream's own (x/net supports both on a server
+// stream), guarded like Write so they never touch a finished handler's
+// writer.
+func (c *upgradedConn) SetReadDeadline(t time.Time) error {
+ c.life.RLock()
+ defer c.life.RUnlock()
+ if c.closed.Load() {
+ return net.ErrClosed
+ }
+ return http.NewResponseController(c.w).SetReadDeadline(t)
+}
+
+func (c *upgradedConn) SetWriteDeadline(t time.Time) error {
+ c.life.RLock()
+ defer c.life.RUnlock()
+ if c.closed.Load() {
+ return net.ErrClosed
+ }
+ return http.NewResponseController(c.w).SetWriteDeadline(t)
+}
+
+// streamAddr names the peer of a hijacked stream: the tunnel conn's remote
+// address as the HTTP/2 server reported it.
+type streamAddr string
+
+func (streamAddr) Network() string { return "carlos-tunnel" }
+func (a streamAddr) String() string { return string(a) }
diff --git a/internal/tunnelclient/upgrade_box_test.go b/internal/tunnelclient/upgrade_box_test.go
new file mode 100644
index 000000000..0c5e63bbb
--- /dev/null
+++ b/internal/tunnelclient/upgrade_box_test.go
@@ -0,0 +1,531 @@
+package tunnelclient
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "golang.org/x/net/http2"
+)
+
+// h2Pair serves handler with ServeWith on one end of an in-memory pipe and
+// returns an HTTP/2 client conn on the other: the box half of the tunnel
+// with nothing between the test and Mark but x/net.
+func h2Pair(t *testing.T, handler http.Handler) *http2.ClientConn {
+ t.Helper()
+ box, hub := net.Pipe()
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ ServeWith(box, handler, DefaultLimits)
+ }()
+ cc, err := (&http2.Transport{}).NewClientConn(hub)
+ if err != nil {
+ t.Fatalf("h2 client: %v", err)
+ }
+ t.Cleanup(func() {
+ cc.Close()
+ hub.Close()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Error("ServeWith did not return after the client hung up")
+ }
+ })
+ return cc
+}
+
+const switching = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"
+
+func TestShimRebuildsTheUpgrade(t *testing.T) {
+ type seen struct {
+ conn, upgrade, marker, key string
+ hasMarker bool
+ contentLength int64
+ noBody bool
+ fromTunnel bool
+ }
+ got := make(chan seen, 1)
+ handlerDone := make(chan struct{})
+ h := Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer close(handlerDone)
+ // Not read: before the shim, the body is the live stream and a
+ // read would block; the shim must have swapped it for NoBody.
+ _, has := r.Header[UpgradeHeader]
+ got <- seen{
+ conn: r.Header.Get("Connection"), upgrade: r.Header.Get("Upgrade"),
+ hasMarker: has, key: r.Header.Get("Sec-WebSocket-Key"),
+ contentLength: r.ContentLength, noBody: r.Body == http.NoBody,
+ fromTunnel: FromTunnel(r.Context()),
+ }
+ hj, ok := w.(http.Hijacker)
+ if !ok {
+ t.Errorf("the shim's writer is not a Hijacker on an upgrade")
+ return
+ }
+ conn, brw, err := hj.Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ defer conn.Close()
+ brw.WriteString(switching)
+ if err := brw.Flush(); err != nil {
+ t.Errorf("flush 101: %v", err)
+ return
+ }
+ io.Copy(conn, conn) // echo until the hub ends its side
+ }))
+ cc := h2Pair(t, h)
+
+ pr, pw := io.Pipe()
+ defer pw.Close()
+ req, _ := http.NewRequest("GET", "https://shop.example.com/cable", pr)
+ req.Header.Set(UpgradeHeader, "websocket")
+ req.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("round trip: %v", err)
+ }
+ defer resp.Body.Close()
+ s := <-got
+ if s.conn != "Upgrade" || s.upgrade != "websocket" || s.hasMarker ||
+ s.contentLength != 0 || !s.noBody || s.key != "dGhlIHNhbXBsZSBub25jZQ==" || !s.fromTunnel {
+ t.Fatalf("handler saw %+v", s)
+ }
+ if resp.StatusCode != http.StatusOK || resp.Header.Get(UpgradedHeader) != "1" {
+ t.Fatalf("hub saw %d with %s=%q, want 200 with 1", resp.StatusCode, UpgradedHeader, resp.Header.Get(UpgradedHeader))
+ }
+ in := make([]byte, len(switching))
+ if _, err := io.ReadFull(resp.Body, in); err != nil || string(in) != switching {
+ t.Fatalf("in-band 101 = %q, %v", in, err)
+ }
+ if _, err := pw.Write([]byte("ping")); err != nil {
+ t.Fatalf("write ping: %v", err)
+ }
+ echo := make([]byte, 4)
+ if _, err := io.ReadFull(resp.Body, echo); err != nil || string(echo) != "ping" {
+ t.Fatalf("echo = %q, %v", echo, err)
+ }
+ pw.Close() // the hub's half-close: the box reads EOF and its handler returns
+ select {
+ case <-handlerDone:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the box's handler did not return after the hub closed its side")
+ }
+ if rest, err := io.ReadAll(resp.Body); err != nil || len(rest) != 0 {
+ t.Fatalf("after the handler returned: %q, %v; want a clean end of stream", rest, err)
+ }
+}
+
+// plainFixture is the handler for the plain-request tests: it reports what
+// it saw and answers a 302 with a body, setting the upgraded marker when
+// asked to.
+func plainFixture(t *testing.T, setMarker bool, saw chan<- *http.Request, body chan<- []byte) http.Handler {
+ return Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if _, ok := w.(http.Hijacker); ok {
+ t.Errorf("a plain request's writer offers Hijack")
+ }
+ b, _ := io.ReadAll(r.Body)
+ saw <- r
+ body <- b
+ w.Header().Set("Location", "/elsewhere")
+ w.Header().Set("X-App", "kept")
+ if setMarker {
+ w.Header().Set(UpgradedHeader, "1")
+ }
+ w.WriteHeader(http.StatusFound)
+ io.WriteString(w, "moved")
+ }))
+}
+
+func TestShimPassesPlainRequestsThrough(t *testing.T) {
+ saw, body := make(chan *http.Request, 1), make(chan []byte, 1)
+ cc := h2Pair(t, plainFixture(t, false, saw, body))
+ payload := bytes.Repeat([]byte("0123456789abcdef"), 256) // 4 KiB
+ req, _ := http.NewRequest("POST", "https://shop.example.com/orders/7?x=1", bytes.NewReader(payload))
+ req.Header.Set("X-Thing", "a")
+ req.Header.Add("X-Thing", "b")
+ req.Header.Set("Content-Type", "application/octet-stream")
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("round trip: %v", err)
+ }
+ defer resp.Body.Close()
+ r, b := <-saw, <-body
+ if r.Method != "POST" || r.URL.RequestURI() != "/orders/7?x=1" || r.Host != "shop.example.com" ||
+ strings.Join(r.Header.Values("X-Thing"), ",") != "a,b" ||
+ r.Header.Get("Content-Type") != "application/octet-stream" ||
+ r.Header.Get("Connection") != "" || r.Header.Get("Upgrade") != "" ||
+ r.ContentLength != int64(len(payload)) || !bytes.Equal(b, payload) {
+ t.Fatalf("handler saw %s %s host %q headers %v, %d-byte body (want the request as sent)",
+ r.Method, r.URL.RequestURI(), r.Host, r.Header, len(b))
+ }
+ got, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusFound || resp.Header.Get("Location") != "/elsewhere" ||
+ resp.Header.Get("X-App") != "kept" || string(got) != "moved" {
+ t.Fatalf("hub saw %d %v %q", resp.StatusCode, resp.Header, got)
+ }
+}
+
+func TestShimStripsAnAppSetUpgradedMarker(t *testing.T) {
+ saw, body := make(chan *http.Request, 1), make(chan []byte, 1)
+ cc := h2Pair(t, plainFixture(t, true, saw, body))
+ req, _ := http.NewRequest("GET", "https://shop.example.com/", nil)
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("round trip: %v", err)
+ }
+ defer resp.Body.Close()
+ <-saw
+ <-body
+ got, _ := io.ReadAll(resp.Body)
+ if _, ok := resp.Header[UpgradedHeader]; ok {
+ t.Fatalf("an app-set %s reached the hub: %v", UpgradedHeader, resp.Header)
+ }
+ // The rest of the response is untouched (the fixture can answer).
+ if resp.StatusCode != http.StatusFound || resp.Header.Get("X-App") != "kept" || string(got) != "moved" {
+ t.Fatalf("hub saw %d %v %q", resp.StatusCode, resp.Header, got)
+ }
+}
+
+// The marker is stripped however the response's header goes out: an
+// implicit 200 on the first Write and a Flush before any Write.
+func TestShimStripsTheMarkerOnImplicitHeaders(t *testing.T) {
+ for _, name := range []string{"write", "flush"} {
+ t.Run(name, func(t *testing.T) {
+ cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set(UpgradedHeader, "1")
+ w.Header().Set("X-App", "kept")
+ if name == "flush" {
+ w.(http.Flusher).Flush()
+ }
+ io.WriteString(w, "hello")
+ })))
+ req, _ := http.NewRequest("GET", "https://shop.example.com/", nil)
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("round trip: %v", err)
+ }
+ defer resp.Body.Close()
+ got, _ := io.ReadAll(resp.Body)
+ if _, ok := resp.Header[UpgradedHeader]; ok || resp.Header.Get("X-App") != "kept" || string(got) != "hello" {
+ t.Fatalf("hub saw %d %v %q", resp.StatusCode, resp.Header, got)
+ }
+ })
+ }
+}
+
+// An upgrade the box answers without hijacking (the gate's 302, a 404, a
+// 502) is an ordinary response, and it too loses an app-set marker.
+func TestShimStripsTheMarkerOnAnUnhijackedUpgrade(t *testing.T) {
+ cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set(UpgradedHeader, "1")
+ w.WriteHeader(http.StatusNotFound)
+ io.WriteString(w, "no such page")
+ })))
+ pr, pw := io.Pipe()
+ defer pw.Close()
+ req, _ := http.NewRequest("GET", "https://shop.example.com/cable", pr)
+ req.Header.Set(UpgradeHeader, "websocket")
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("round trip: %v", err)
+ }
+ defer resp.Body.Close()
+ got, _ := io.ReadAll(resp.Body)
+ if _, ok := resp.Header[UpgradedHeader]; ok || resp.StatusCode != http.StatusNotFound || string(got) != "no such page" {
+ t.Fatalf("hub saw %d %v %q", resp.StatusCode, resp.Header, got)
+ }
+}
+
+func TestShimRefusesABadToken(t *testing.T) {
+ for _, tc := range []struct {
+ name, token string
+ reaches bool
+ }{
+ {"space", "web socket", false},
+ {"65 bytes", strings.Repeat("a", MaxUpgradeTokenLen+1), false},
+ {"empty", "", false},
+ {"64 bytes (control)", strings.Repeat("a", MaxUpgradeTokenLen), true},
+ {"websocket (control)", "websocket", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var ran bool
+ var mu sync.Mutex
+ cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ ran = true
+ mu.Unlock()
+ w.WriteHeader(http.StatusNoContent)
+ })))
+ req, _ := http.NewRequest("GET", "https://shop.example.com/cable", nil)
+ req.Header[UpgradeHeader] = []string{tc.token}
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("round trip: %v", err)
+ }
+ resp.Body.Close()
+ mu.Lock()
+ defer mu.Unlock()
+ if tc.reaches {
+ if !ran || resp.StatusCode != http.StatusNoContent {
+ t.Fatalf("token %q: status %d, handler ran %v; want it to reach the handler", tc.token, resp.StatusCode, ran)
+ }
+ return
+ }
+ if ran || resp.StatusCode != http.StatusBadRequest {
+ t.Fatalf("token %q: status %d, handler ran %v; want 400 and no handler", tc.token, resp.StatusCode, ran)
+ }
+ })
+ }
+}
+
+func TestValidUpgradeToken(t *testing.T) {
+ for tok, want := range map[string]bool{
+ "websocket": true, "h2c": true, "a!#$%&'*+-.^_`|~9": true,
+ strings.Repeat("x", 64): true, strings.Repeat("x", 65): false,
+ "": false, "web socket": false, "web/socket": false, "a\x00": false, "caf\xc3\xa9": false, "a\tb": false,
+ } {
+ if got := ValidUpgradeToken(tok); got != want {
+ t.Errorf("ValidUpgradeToken(%q) = %v, want %v", tok, got, want)
+ }
+ }
+}
+
+func TestRegistrationCarriesTheCapability(t *testing.T) {
+ caps := make(chan []string, 1)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ caps <- r.Header.Values(CapsHeader)
+ conn, bufrw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ defer conn.Close()
+ fmt.Fprintf(bufrw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: carlos-tunnel/1\r\nConnection: Upgrade\r\n\r\n")
+ bufrw.Flush()
+ }))
+ defer srv.Close()
+ conn, err := Dial(context.Background(), srv.URL, "box-1", "sekrit")
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ conn.Close()
+ if got := <-caps; len(got) != 1 || got[0] != "upgrade/1" {
+ t.Fatalf("%s on /register = %q, want [upgrade/1]", CapsHeader, got)
+ }
+}
+
+// advertised is what a box's h2 server tells the hub first: its SETTINGS
+// and the connection-level window raise that follows.
+type advertised struct {
+ maxStreams, streamWindow uint32
+ connIncrement uint32
+}
+
+// readAdvertised plays the client side of a fresh h2 connection on rw: it
+// writes the client preface, reads the server's first two frames, and only
+// then sends an empty SETTINGS. The order is deliberate. x/net queues its
+// SETTINGS and the connection WINDOW_UPDATE before it reads the preface
+// (http2/server.go:780-802), but the WINDOW_UPDATE is written only once the
+// serve loop runs, and a pending SETTINGS ACK jumps the write queue
+// (scheduleFrameWrite checks needToSendSettingsAck before popping the
+// scheduler). A client that sent its SETTINGS with the preface could see
+// the ACK between the two; one that sends it after reading them cannot.
+// (x/net allows 2 s for the first SETTINGS; we send it at once.) It returns
+// an error rather than failing the test so the fake hub's handler
+// goroutine can call it.
+func readAdvertised(rw io.ReadWriter) (advertised, error) {
+ read := make(chan struct{})
+ defer close(read)
+ // From a goroutine: on a net.Pipe each write blocks until the server
+ // reads it. It ends when the test closes its end.
+ go func() {
+ io.WriteString(rw, http2.ClientPreface)
+ <-read
+ http2.NewFramer(rw, nil).WriteSettings()
+ }()
+ fr := http2.NewFramer(nil, rw)
+ var a advertised
+ f, err := fr.ReadFrame()
+ if err != nil {
+ return a, fmt.Errorf("first frame: %v", err)
+ }
+ sf, ok := f.(*http2.SettingsFrame)
+ if !ok || sf.IsAck() {
+ return a, fmt.Errorf("first frame = %v, want the server's SETTINGS", f)
+ }
+ var ok1, ok2 bool
+ a.maxStreams, ok1 = sf.Value(http2.SettingMaxConcurrentStreams)
+ a.streamWindow, ok2 = sf.Value(http2.SettingInitialWindowSize)
+ if !ok1 || !ok2 {
+ return a, fmt.Errorf("SETTINGS lacks MAX_CONCURRENT_STREAMS (%v) or INITIAL_WINDOW_SIZE (%v)", ok1, ok2)
+ }
+ if f, err = fr.ReadFrame(); err != nil {
+ return a, fmt.Errorf("second frame: %v", err)
+ }
+ wu, ok := f.(*http2.WindowUpdateFrame)
+ if !ok || wu.StreamID != 0 {
+ return a, fmt.Errorf("second frame = %v, want a connection-level WINDOW_UPDATE", f)
+ }
+ a.connIncrement = wu.Increment
+ return a, nil
+}
+
+func wantAdvertised(l Limits) advertised {
+ return advertised{l.MaxStreams, uint32(l.StreamWindow), uint32(l.ConnWindow - 65535)}
+}
+
+var smallLimits = Limits{MaxStreams: 8, StreamWindow: 64 << 10, ConnWindow: 768 << 10}
+
+func TestServerAdvertisesTheLimits(t *testing.T) {
+ if want := (Limits{MaxStreams: 250, StreamWindow: 1 << 20, ConnWindow: 160 << 20}); DefaultLimits != want {
+ t.Fatalf("DefaultLimits = %+v, want %+v", DefaultLimits, want)
+ }
+ for _, tc := range []struct {
+ name string
+ serve func(net.Conn)
+ want advertised
+ }{
+ {"Serve", func(c net.Conn) { Serve(c, http.NotFoundHandler()) }, advertised{250, 1 << 20, 160<<20 - 65535}},
+ {"ServeWith defaults", func(c net.Conn) { ServeWith(c, http.NotFoundHandler(), DefaultLimits) }, wantAdvertised(DefaultLimits)},
+ {"ServeWith small", func(c net.Conn) { ServeWith(c, http.NotFoundHandler(), smallLimits) }, advertised{8, 64 << 10, 768<<10 - 65535}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ box, hub := net.Pipe()
+ done := make(chan struct{})
+ go func() { defer close(done); tc.serve(box) }()
+ got, err := readAdvertised(hub)
+ hub.Close()
+ <-done
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != tc.want {
+ t.Fatalf("advertised %+v, want %+v", got, tc.want)
+ }
+ })
+ }
+}
+
+// TestLoopAppliesConfigLimits drives the real Loop against a fake hub that
+// reads the box's first frames: Config.Limits reaches the server, and a
+// Config without it gets DefaultLimits.
+func TestLoopAppliesConfigLimits(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ limits *Limits
+ want advertised
+ }{
+ {"configured", &smallLimits, advertised{8, 64 << 10, 768<<10 - 65535}},
+ {"default (control)", nil, advertised{250, 1 << 20, 160<<20 - 65535}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ type result struct {
+ a advertised
+ err error
+ }
+ got := make(chan result, 1)
+ release := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, bufrw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ defer conn.Close()
+ fmt.Fprintf(bufrw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: carlos-tunnel/1\r\nConnection: Upgrade\r\n\r\n")
+ bufrw.Flush()
+ a, err := readAdvertised(struct {
+ io.Reader
+ io.Writer
+ }{bufrw, conn})
+ // Only the first registration reports, and the fake hub
+ // holds its end open: a hub that hung up would send Loop
+ // round again and the test would be measuring a redial.
+ select {
+ case got <- result{a, err}:
+ default:
+ }
+ <-release
+ }))
+ defer srv.Close()
+ defer close(release) // LIFO: release the handler, then close the server
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ Loop(ctx, Config{URL: srv.URL, Name: "box-1", Token: "sekrit", Handler: http.NotFoundHandler(),
+ Limits: tc.limits, Logf: func(string, ...any) {}})
+ }()
+ var res result
+ select {
+ case res = <-got:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the fake hub never read the box's settings")
+ }
+ cancel()
+ <-done
+ if res.err != nil {
+ t.Fatal(res.err)
+ }
+ if res.a != tc.want {
+ t.Fatalf("advertised %+v, want %+v", res.a, tc.want)
+ }
+ })
+ }
+}
+
+// The reverse proxy waits for only one direction of its splice before its
+// handler returns; the other copy goroutine can still be writing. Once the
+// handler has returned, a Write on the hijacked conn must fail with
+// net.ErrClosed, never reach the finished stream's writer (x/net panics).
+func TestHijackedConnRefusesWritesAfterTheHandler(t *testing.T) {
+ returned := make(chan struct{})
+ writerErr := make(chan error, 1)
+ cc := h2Pair(t, Mark(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer close(returned)
+ conn, _, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ go func() {
+ <-returned
+ for {
+ if _, err := conn.Write([]byte("x")); err != nil {
+ writerErr <- err
+ return
+ }
+ }
+ }()
+ })))
+ pr, pw := io.Pipe()
+ defer pw.Close()
+ req, _ := http.NewRequest("GET", "https://shop.example.com/cable", pr)
+ req.Header.Set(UpgradeHeader, "websocket")
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("round trip: %v", err)
+ }
+ defer resp.Body.Close()
+ go io.Copy(io.Discard, resp.Body) // keep the stream's window open
+ select {
+ case err := <-writerErr:
+ if !errors.Is(err, net.ErrClosed) {
+ t.Fatalf("a write after the handler returned failed with %v, want net.ErrClosed", err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("writes after the handler returned kept succeeding")
+ }
+}