carlos / platform Public

edge: switch on the hub's marker, upgrades cross the fleet tunnel (#471 Task 5)

The hub's upgrade branch puts its admission on a tunnel arm's request, and
transportFor sends an upgrade down a channel only with that admission, the
box's upgrade capability and a valid token, under a reservation released
by the transport's own error paths, the returned body's Close or the
request's end. EnableTunnels gives the hub its edge; a hub without one
refuses every upgrade (errNoAdmission).

tunnelProxy and fleetProxy answer the refusals: the channel at its cap is
503 with Retry-After 5, cause tunnel_busy and TWS-C03; a box without the
capability is 502, cause tunnel_upgrade_unsupported, logged through
logThrottled; a stale tenancy or no admission is 502, cause tunnel.
apperr gains the two causes with TWS-C01 and TWS-C02.

The policy tests now expect the 101 and a socket closed by
CloseAccountUpgrades; Task 3's dormancy test is gone. Spec §4.9 takes
P-1's wording and §7 Task 5's census reconciliation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 10151ad5a15b7d2c008b61c179ae4812849c0002 parent 3baa50b
9 files changed, +764 −42
  • approved_tunnel_websockets_copy_test.go +1 −1
  • docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md +27 −1
  • internal/apperr/availability.go +10 −0
  • internal/apperr/availability_test.go +17 −0
  • internal/edge/edge.go +56 −2
  • internal/edge/fleetforward_policy_test.go +45 −17
  • internal/edge/tunnel.go +98 −1
  • internal/edge/tunnel_upgrade_test.go +508 −0
  • internal/edge/upgrades_test.go +2 −20

Intent

Human

<task-notification> <task-id>bymcwut6k</task-id> <tool-use-id>toolu_01XXfJHUYsYWc37szDAL2bRQ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bymcwut6k.output</output-file> <status>failed</status> <summary>Background command "Run Astra scoped re-review of #471 Task 4 fix" failed with exit code 127</summary> </task-notification>

Human

<task-notification> <task-id>b201rav9i</task-id> <tool-use-id>toolu_014fQHeKK12GNhtp3FfNWzqx</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/b201rav9i.output</output-file> <status>completed</status> <summary>Background command "Run Astra scoped re-review of #471 Task 4 fix" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a26e7645db516d417</task-id> <tool-use-id>toolu_01BvvBACaZ4HDN1WSz7iPJYy</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a26e7645db516d417.output</output-file> <status>completed</status> <summary>Agent "Plan 6 Task 6: control /tty routes" 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>**Status:** DONE_WITH_CONCERNS **Commit:** `08554c12` "instance-control: POST /tty and GET /tty/{host} (rootfs plan 6)", on top of base `d5986010`. Not pushed. Worktree clean. **Tests:** All 18 new TTY tests failed before the change and pass after it. The instancectl package's tests pass, and all four removal guards pass with their pinned lists unchanged. The root-read census tests and `TestPlan9B8` pass after the re-proposal. Build, vet and gofmt are clean. The root binary cross-builds for darwin/arm64, windows/amd64 and linux/arm64. Of 28 mutations, 27 are killed by the tests and 1 survives because it changes nothing observable (concern 2). **Concerns:** 1. **Census approval is still owed.** I re-proposed the `rootfs-apps-6` overlay (new seal `b611b6ff…`) and carried over the earlier tasks' claims unchanged. The two tty template claims now say what starts them and where their files go, since their old text said "nothing starts it yet". Astra still needs to approve on #280; I did not request it. 2. **One mutation survives.** Reverting `stopRootfs`'s cleanup to cmd-only does not change behaviour. A tty stop falls through to the general branch, which does the same proof and the same removals. It only skips the role lock, and the per-unit lock already keeps a start in flight out. The change the brief asked for is in place. 3. **Census sees a move as removed plus new.** `handleCmdStatus`'s body now lives in `oneShotStatus`, behind the brief's `handleOneShotStatus(role)`. The census therefore lists `handleCmdStatus` as removed and `oneShotStatus` as new. The claim says it moved whole with no check lost. 4. **A test-vet failure on darwin and windows was already there.** `GOOS=darwin|windows go vet ./internal/instancectl/` fails at `hardening_test.go:137`, which uses a helper defined only in a linux-only test file. My new tests avoid linux-only helpers, and the root binary still cross-builds on all three targets. 5. **New error text built from the role.** Messages such as `tty: &lt;unit&gt; is active` and `not a tty's` are agent-facing, built by putting the role in place of "cmd". The cmd wording is unchanged byte for byte. I left `parseQuery`'s "role %q is not run, seed, sidecar, cmd or worker" alone, as Task 5 flagged. The full report (RED/GREEN, the mutation table, every caller migrated, the census card, and departures from the brief) is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/.superpowers/sdd/2026-10-24-rootfs-apps-6-interactive/task-6-report.md`.</result> <usage><subagent_tokens>302399</subagent_tokens><tool_uses>94</tool_uses><duration_ms>1534637</duration_ms></usage> </task-notification>

Attributed to this commit: 5.43 g CO₂e (524,880 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/approved_tunnel_websockets_copy_test.go b/approved_tunnel_websockets_copy_test.go
index ca4e39166..ab209c40a 100644
--- a/approved_tunnel_websockets_copy_test.go
+++ b/approved_tunnel_websockets_copy_test.go
@@ -39,7 +39,7 @@ var tunnelWebSocketsCopyStatuses = []string{"pending", "approved", "struck"}
// tunnelWebSocketsCopyBuilt is every id whose text the code or docs carry.
// The task that writes a row's text adds its id here in the same commit, once
// the row is approved. Task 5 builds all three (TWS-C01 to TWS-C03).
-var tunnelWebSocketsCopyBuilt = []string{}
+var tunnelWebSocketsCopyBuilt = []string{"TWS-C01", "TWS-C02", "TWS-C03"}
func mustParseTunnelWebSocketsRecord(t *testing.T) []copyRow {
t.Helper()
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 c541b01f2..fd3f43ebf 100644
--- a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
+++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
@@ -873,7 +873,7 @@ other combination behaves exactly as today:
|---|---|---|
| old | old | 502 |
| old | new | 502 (the old hub ignores the header and x/net refuses as today) |
-| new | old | 502, cause `tunnel_upgrade_unsupported` (§7), logged once per channel per hour |
+| new | old | 502, cause `tunnel_upgrade_unsupported` (§7), logged per channel through the edge's `logThrottled` (the first occurrence, then every 300th; plan ruling P-1) |
| new | new | 101 |
The channel picked for an upgrade is the one `fleetChannelFor` picks for
@@ -1046,6 +1046,32 @@ for it:
The seal is unchanged. No overlay is proposed here (Task 9).
+Task 5's card (`make census-card`) shows the same three rows as Task 4
+(`body` `Edge.ServeHTTP`, read sites unchanged at 29; `reads`
+`Edge.Reload`; the two `new` tunnelclient `Read` units) and re-pins one
+more envelope, `internal/apperr`, as this section expected. What Task 5
+changed, and why the card has no row for it:
+
+- `Edge.ServeHTTP`: the upgrade branch puts the admission
+ (`withUpgradeAdmission`, from the host, the path and `up.tenancy`, all
+ already in hand) on a tunnel arm's request. The `body` row above; no
+ read added.
+- `Edge.EnableTunnels`: also sets `hub.edge = e` (P2-3). It reads
+ nothing; the `internal/edge` envelope re-pin covers it.
+- `TunnelHub.transportFor` and the new `roundTripUpgrade`,
+ `channelRefusal`, `reservedConn`, `reservedBody` and `tunnelBusyBody`:
+ an upgrade goes down a channel only with an admission, the box's
+ capability and a valid token, under a reservation. They read the
+ request, the in-memory channel and the registry of open upgrades; no
+ file and no root-owned state, so no row.
+- `tunnelProxy`, `fleetProxy` and the new `tunnelUpgradeError`: the
+ error handlers answer the new sentinels (503 with TWS-C03, or 502) and
+ note the cause. No read.
+- `internal/apperr`: two cause constants and their descriptions
+ (TWS-C01, TWS-C02). No read; the envelope re-pin covers them.
+
+The seal is unchanged.
+
The reviewer is Astra (Claude author), recorded on #280.
Copy. Two new cause descriptions in `internal/apperr/availability.go`
diff --git a/internal/apperr/availability.go b/internal/apperr/availability.go
index e6399b2e1..0d15e6f53 100644
--- a/internal/apperr/availability.go
+++ b/internal/apperr/availability.go
@@ -35,6 +35,13 @@ const (
CauseUpstream = "upstream" // the app itself answered 502/503/504
)
+// The causes tunnel WebSockets adds (#471 spec §7): an upgrade the hub
+// would not send down a fleet box's channel.
+const (
+ CauseTunnelBusy = "tunnel_busy" // the box's channel carries its maximum of open upgrades (§4.8)
+ CauseTunnelUpgradeUnsupported = "tunnel_upgrade_unsupported" // the box registered without the upgrade capability (§4.9)
+)
+
var causeText = map[string]string{
CauseRefused: "the instance refused the connection",
CauseReset: "the instance closed the connection mid-request",
@@ -47,6 +54,9 @@ var causeText = map[string]string{
CauseProxy: "the proxy could not complete the request",
CauseUpstream: "the app answered it itself",
"": "cause not recorded",
+
+ CauseTunnelBusy: "the fleet box has too many open connections",
+ CauseTunnelUpgradeUnsupported: "the fleet box runs a release that cannot carry WebSockets",
}
// UnavailableStatus reports whether an edge-observed status belongs under
diff --git a/internal/apperr/availability_test.go b/internal/apperr/availability_test.go
index b5ba5a46a..5aef1bbba 100644
--- a/internal/apperr/availability_test.go
+++ b/internal/apperr/availability_test.go
@@ -50,3 +50,20 @@ func TestAsAvailabilityRegroupsHistory(t *testing.T) {
t.Fatalf("an unknown cause renders as itself, got %q", got)
}
}
+
+// TestAvailabilityNamesTheTunnelCauses: the two causes tunnel WebSockets
+// adds (#471 spec §7) render with their approved descriptions, TWS-C01 and
+// TWS-C02, not as their raw values.
+func TestAvailabilityNamesTheTunnelCauses(t *testing.T) {
+ for _, c := range []struct {
+ status int
+ cause, want string
+ }{
+ {503, "tunnel_busy", "503 · the fleet box has too many open connections"},
+ {502, "tunnel_upgrade_unsupported", "502 · the fleet box runs a release that cannot carry WebSockets"},
+ } {
+ if got := AvailabilityName(c.status, c.cause); got != c.want {
+ t.Errorf("AvailabilityName(%d, %q) = %q, want %q", c.status, c.cause, got, c.want)
+ }
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 6096499da..db7a67936 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -583,8 +583,14 @@ func (e *Edge) EnableCache(cache *Cache) {
// itself (registration) and routes with Tunnel set proxy over their named
// channel. Call before Reload, same contract as EnableStatic — without a
// Reload afterwards, tunnel routes stay skipped from the last table build.
+// It also gives the hub this edge (hub.edge), whose registry of open
+// upgrades the hub's transport reserves in (#471 spec §4.6.2): a hub never
+// passed to EnableTunnels refuses every upgrade.
func (e *Edge) EnableTunnels(hub *TunnelHub) {
e.tunnels = hub
+ if hub != nil {
+ hub.edge = e
+ }
e.armStoreDoor()
}
@@ -2223,6 +2229,13 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer release()
w = &slotWriter{ResponseWriter: w, release: release}
}
+ // The admission (#471 spec §4.4): a tunnel arm's upgrade carries
+ // what this branch admitted it under, and the hub's transport sends
+ // an upgrade down a channel only with it, re-checked against the map
+ // when it reserves. Every other arm gets nothing.
+ if up.tenancy.Arm != ArmNone {
+ r = r.WithContext(withUpgradeAdmission(r.Context(), upgradeAdmission{Host: host, Path: r.URL.Path, Tenancy: up.tenancy}))
+ }
if up.hibernating {
if e.act.ServeHTTP(w, r, up.route, up.proxy) {
return
@@ -3295,11 +3308,49 @@ func tunnelProxy(name string, hub *TunnelHub) *httputil.ReverseProxy {
scrubInboundPurgeHeader(pr)
scrubTunnelMarkers(pr)
},
- Transport: hub.transportFor(name),
- ErrorHandler: defaultProxyError(tunnelCause),
+ Transport: hub.transportFor(name),
+ ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
+ if tunnelUpgradeError(w, r, err, hub) {
+ return
+ }
+ defaultProxyError(tunnelCause)(w, r, err)
+ },
}
}
+// tunnelUpgradeError answers the tunnel transport's upgrade refusals for
+// tunnelProxy and fleetProxy (#471 spec §4.8, §4.9), and reports whether
+// err was one:
+//
+// - the channel at its cap: 503, Retry-After 5, cause tunnel_busy, the
+// TWS-C03 body;
+// - a box without the upgrade capability: 502, cause
+// tunnel_upgrade_unsupported, logged through logThrottled per channel;
+// - a stale tenancy or no admission: 502, cause tunnel.
+func tunnelUpgradeError(w http.ResponseWriter, r *http.Request, err error, hub *TunnelHub) bool {
+ switch {
+ case errors.Is(err, errTunnelBusy):
+ noteCause(r, apperr.CauseTunnelBusy)
+ w.Header().Set("Retry-After", "5")
+ http.Error(w, tunnelBusyBody, http.StatusServiceUnavailable)
+ case errors.Is(err, errTunnelNoUpgrade):
+ noteCause(r, apperr.CauseTunnelUpgradeUnsupported)
+ var cr *channelRefusal
+ if e := hub.edge; e != nil && errors.As(err, &cr) {
+ e.logThrottled("tunnel-upgrade-unsupported "+cr.channel, fmt.Sprintf(
+ "channel %s registered without %s: an upgrade to it answers 502", cr.channel, tunnelclient.CapUpgrade))
+ }
+ w.WriteHeader(http.StatusBadGateway)
+ case errors.Is(err, errTenancyStale), errors.Is(err, errNoAdmission):
+ noteCause(r, apperr.CauseTunnel)
+ log.Printf("edge: tunnel upgrade refused: %v", err)
+ w.WriteHeader(http.StatusBadGateway)
+ default:
+ return false
+ }
+ return true
+}
+
// scrubTunnelMarkers deletes both of the tunnel's upgrade markers from a
// request bound for a tunnel (#471 spec §4.4): a stream carries
// Carlos-Tunnel-Upgrade only when the hub's upgrade branch admitted it, and
@@ -3376,6 +3427,9 @@ func fleetProxy(fleet, boxLabel string, hub *TunnelHub) *httputil.ReverseProxy {
http.Error(w, "fleet unreachable: no connected box", http.StatusServiceUnavailable)
return
}
+ if tunnelUpgradeError(w, r, err, hub) {
+ return
+ }
// Any other transport failure (e.g. the picked channel died between
// fleetChannelFor's check and the RoundTrip call) — same shape as
// httputil.ReverseProxy's own default handler: log and 502.
diff --git a/internal/edge/fleetforward_policy_test.go b/internal/edge/fleetforward_policy_test.go
index 72bc8e0ea..e42aa9740 100644
--- a/internal/edge/fleetforward_policy_test.go
+++ b/internal/edge/fleetforward_policy_test.go
@@ -191,18 +191,15 @@ func TestForwardRateLimitAtTheHubOnly(t *testing.T) {
}
}
-// Upgrades do not cross the fleet tunnel today: the hub's tunnel transport is
-// an HTTP/2 client, which refuses a request with an Upgrade header ("http2:
-// invalid Upgrade request header"), so an admitted handshake for any
-// fleet-placed row is answered 502 by the hub and never reaches the box. What
-// the hub's admission decides is still visible: an admitted handshake gets
-// the transport's answer, a refused one the edge's 429.
+// An upgrade to a forward row crosses the fleet tunnel (#471): an admitted
+// handshake gets the app's 101 through the hub and the box, and one past the
+// hub's burst gets the edge's 429 and never reaches the box.
func TestForwardUpgradeIsLimitedAtTheHub(t *testing.T) {
hubURL, _, _, app := policyScene(t)
for i := 1; i <= 2; i++ {
_, _, resp, body := polUpgrade(t, hubURL)
- if resp.StatusCode != http.StatusSwitchingProtocols && resp.StatusCode != http.StatusBadGateway {
- t.Fatalf("handshake %d: %d %q, want it admitted at the hub (its burst is 2) and handed to the tunnel", i, resp.StatusCode, body)
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("handshake %d: %d %q, want the app's 101: admitted at the hub (its burst is 2) and carried by the tunnel", i, resp.StatusCode, body)
}
}
_, _, resp, body := polUpgrade(t, hubURL)
@@ -210,17 +207,18 @@ func TestForwardUpgradeIsLimitedAtTheHub(t *testing.T) {
if got := resp.Header.Get("Retry-After"); got != "1" {
t.Fatalf("handshake 3: Retry-After %q, want the rate limit's 1", got)
}
- if _, ups := app.counts(); ups > 2 {
- t.Fatalf("the app saw %d upgrades, want at most 2", ups)
+ if _, ups := app.counts(); ups != 2 {
+ t.Fatalf("the app saw %d upgrades, want 2", ups)
}
}
// The plan throttle and upgrade tracking key on the forward row's account at
-// the hub. Since no upgrade stays open across the tunnel (above), "an open
-// upgrade is closed" is shown at the moment the hub asks the throttle about
-// it: trackUpgrade registers the request first (Astra plans-4c finding 2), so
-// a CloseAccountUpgrades from inside the throttle hook finds it and cancels
-// it. That is the window the host's pass relies on.
+// the hub. "An open upgrade is closed" is shown twice: at the moment the hub
+// asks the throttle about a handshake (trackUpgrade registers the request
+// first, Astra plans-4c finding 2, so a CloseAccountUpgrades from inside the
+// throttle hook finds it and cancels it: the window the host's pass relies
+// on), and on a socket held open across the tunnel, whose close reaches the
+// app behind the box (#471 spec §4.6).
func TestForwardPlanThrottleAndUpgradeClose(t *testing.T) {
hubURL, hub, _, app := policyScene(t)
var mu sync.Mutex
@@ -275,6 +273,37 @@ func TestForwardPlanThrottleAndUpgradeClose(t *testing.T) {
if n := hub.CloseAccountUpgrades(fwdOwner); n != 0 {
t.Fatalf("CloseAccountUpgrades after the handshake ended closed %d, want 0", n)
}
+
+ // A socket held open across the tunnel: it echoes, then one
+ // CloseAccountUpgrades at the hub closes it, and the app's end of it
+ // closes within 2 s.
+ c, br, resp, body := polUpgrade(t, hubURL)
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("the held socket's handshake: %d %q, want 101", resp.StatusCode, body)
+ }
+ io.WriteString(c, "ping\n")
+ if line, err := br.ReadString('\n'); err != nil || line != "echo:ping\n" {
+ t.Fatalf("the held socket: read %q, %v; want the app's echo", line, err)
+ }
+ if n := hub.CloseAccountUpgrades(fwdOwner); n != 1 {
+ t.Fatalf("CloseAccountUpgrades(%q) with a socket open closed %d, want 1", fwdOwner, n)
+ }
+ // Every upgrade the app saw must close, the held socket among them. The
+ // in-hook handshake above was cancelled before it reached the
+ // transport; should its stream still have reached the app before its
+ // reset, its close is counted too, rather than standing in for the
+ // held socket's.
+ deadline := time.After(2 * time.Second)
+ for closes := 0; ; closes++ {
+ if _, ups := app.counts(); closes >= ups {
+ break
+ }
+ select {
+ case <-app.closed:
+ case <-deadline:
+ t.Fatal("2 s after CloseAccountUpgrades the app's end of the socket is still open")
+ }
+ }
}
// polWideRate keeps the per-instance limit out of a plan-throttle test's
@@ -335,8 +364,7 @@ func TestForwardPlanThrottleExemptsTheTunnelAtTheBox(t *testing.T) {
// TestForwardUpgradeCloseCancelsTheRequest (deferred minor, Task 5):
// CloseAccountUpgrades does not only count a forward row's tracked upgrade,
// it cancels the context of the request it tracked, which is what ends the
-// proxied connection. Driven directly, since no upgrade stays open across the
-// tunnel (#471).
+// proxied connection. Driven directly.
func TestForwardUpgradeCloseCancelsTheRequest(t *testing.T) {
_, hub, _, _ := policyScene(t)
hub.SetPlanGovernedFor(func(rt registry.Route) bool { return rt.Account == fwdOwner })
diff --git a/internal/edge/tunnel.go b/internal/edge/tunnel.go
index 3e30eb333..667561ec3 100644
--- a/internal/edge/tunnel.go
+++ b/internal/edge/tunnel.go
@@ -14,6 +14,7 @@ import (
"crypto/subtle"
"encoding/hex"
"fmt"
+ "io"
"log"
"net"
"net/http"
@@ -106,6 +107,11 @@ type TunnelHub struct {
// tunnel's h2 connection is built, just before it publishes the
// connection.
afterAuth func(name string)
+ // edge is the Edge this hub serves for, set by Edge.EnableTunnels: its
+ // registry of open upgrades is where transportFor reserves (#471 spec
+ // §4.6.2). nil on a hub used without EnableTunnels, which then refuses
+ // every upgrade (errNoAdmission).
+ edge *Edge
}
func NewTunnelHub(host string, clients map[string]string) *TunnelHub {
@@ -435,10 +441,29 @@ type roundTripperFunc func(*http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+// tunnelBusyBody is TWS-C03, the body of the 503 a visitor gets when the
+// box's channel already carries its maximum of open upgrades (spec §4.8).
+const tunnelBusyBody = "Too many open connections to this app's box. Try again shortly."
+
+// channelRefusal is an upgrade refusal that names its channel, so the
+// proxies' error handlers can say which box it was about: fleetProxy picks
+// the channel inside its transport, out of their sight.
+type channelRefusal struct {
+ channel string
+ err error
+}
+
+func (c *channelRefusal) Error() string { return fmt.Sprintf("tunnel %q: %v", c.channel, c.err) }
+func (c *channelRefusal) Unwrap() error { return c.err }
+
// transportFor resolves the channel PER REQUEST, so a proxy built before a
-// reconnect uses the fresh channel afterwards with no reload needed.
+// reconnect uses the fresh channel afterwards with no reload needed. An
+// upgrade request goes down the channel only through roundTripUpgrade.
func (h *TunnelHub) transportFor(name string) http.RoundTripper {
return roundTripperFunc(func(req *http.Request) (*http.Response, error) {
+ if isUpgradeRequest(req) {
+ return h.roundTripUpgrade(name, req)
+ }
tc := h.channel(name)
if tc == nil {
return nil, fmt.Errorf("tunnel %q not connected", name)
@@ -446,3 +471,75 @@ func (h *TunnelHub) transportFor(name string) http.RoundTripper {
return tc.cc.RoundTrip(req)
})
}
+
+// roundTripUpgrade sends an upgrade down channel name (spec §4.3, §4.6.2).
+// Holding nothing, it refuses an upgrade the hub's upgrade branch did not
+// admit (or that reached a hub with no edge), one for a channel whose box
+// did not advertise the capability, and one whose Upgrade token is not one
+// valid token. Otherwise it reserves, which refuses a stale tenancy or a
+// channel at its cap, and sends the request with tunnelclient's
+// RoundTripUpgrade under the reservation's stream context.
+//
+// The reservation is released here on a transport error, by the returned
+// body's Close (the upgraded connection on a 101, the plain body on any
+// other answer), or by its backstop when the request ends.
+func (h *TunnelHub) roundTripUpgrade(name string, req *http.Request) (*http.Response, error) {
+ adm, admitted := upgradeAdmissionFrom(req.Context())
+ e := h.edge
+ if !admitted || e == nil {
+ return nil, errNoAdmission
+ }
+ tc := h.channel(name)
+ if tc == nil {
+ return nil, fmt.Errorf("tunnel %q not connected", name)
+ }
+ if tc.caps != tunnelclient.CapUpgrade {
+ return nil, &channelRefusal{channel: name, err: errTunnelNoUpgrade}
+ }
+ if !tunnelclient.ValidUpgradeToken(req.Header.Get("Upgrade")) {
+ return nil, fmt.Errorf("tunnel %q: the Upgrade token is not one token of at most %d bytes", name, tunnelclient.MaxUpgradeTokenLen)
+ }
+ r, streamCtx, err := e.reserveUpgrade(req.Context(), adm, tc, h.upgradeCap)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := tunnelclient.RoundTripUpgrade(streamCtx, tc.cc, req)
+ if err != nil {
+ r.release(relTransport)
+ return nil, err
+ }
+ if uc, ok := resp.Body.(*tunnelclient.UpgradeConn); ok && resp.StatusCode == http.StatusSwitchingProtocols {
+ r.attach(nil, uc)
+ resp.Body = &reservedConn{UpgradeConn: uc, r: r}
+ return resp, nil
+ }
+ r.attach(nil, resp.Body)
+ resp.Body = &reservedBody{ReadCloser: resp.Body, r: r}
+ return resp, nil
+}
+
+// reservedConn is a 101's upgraded connection whose Close releases its
+// reservation, which closes the connection. Read, Write and CloseWrite are
+// the connection's own, so the reverse proxy splices and half-closes it as
+// it would any backend connection.
+type reservedConn struct {
+ *tunnelclient.UpgradeConn
+ r *upgradeReservation
+}
+
+func (c *reservedConn) Close() error {
+ c.r.release(relBody)
+ return nil
+}
+
+// reservedBody is any other answer's body, whose Close releases its
+// reservation, which closes the body.
+type reservedBody struct {
+ io.ReadCloser
+ r *upgradeReservation
+}
+
+func (b *reservedBody) Close() error {
+ b.r.release(relBody)
+ return nil
+}
diff --git a/internal/edge/tunnel_upgrade_test.go b/internal/edge/tunnel_upgrade_test.go
new file mode 100644
index 000000000..143ab861d
--- /dev/null
+++ b/internal/edge/tunnel_upgrade_test.go
@@ -0,0 +1,508 @@
+package edge
+
+// Tunnel WebSockets (#471) Task 5: the hub's marker is on. An admitted
+// upgrade to a fleet app crosses the tunnel and answers the app's 101; the
+// transport refuses an upgrade with no admission, to a box without the
+// capability, past the channel's cap, or whose tenancy went stale, and
+// gives the channel's slot back when the request ends however it ended.
+//
+// The scenes are policyScene and forwardHubAndBox (fleetforward_test.go):
+// a real hub Edge and a real box Edge, the box dialled in by the real
+// tunnelclient loop. Accounts: fwdOwner ("bah") owns fleets home and away;
+// fwdOther ("baj") is the second account.
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apperr"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+// twsBusyText is TWS-C03, the 503 body when a box's channel is at its cap,
+// as http.Error writes it (with its newline).
+const twsBusyText = "Too many open connections to this app's box. Try again shortly.\n"
+
+// rawUpgrade sends one WebSocket handshake for host to the hub on a raw
+// connection, with the Connection header written as connLines (one line
+// each), and returns the connection, its reader and the answer, with the
+// body read when it is not a 101. It reports errors rather than failing the
+// test, so a goroutine may call it.
+func rawUpgrade(hubURL, host string, connLines ...string) (net.Conn, *bufio.Reader, *http.Response, string, error) {
+ if len(connLines) == 0 {
+ connLines = []string{"Upgrade"}
+ }
+ c, err := net.Dial("tcp", strings.TrimPrefix(hubURL, "http://"))
+ if err != nil {
+ return nil, nil, nil, "", err
+ }
+ c.SetDeadline(time.Now().Add(10 * time.Second))
+ var b strings.Builder
+ fmt.Fprintf(&b, "GET /socket HTTP/1.1\r\nHost: %s\r\n", host)
+ for _, l := range connLines {
+ fmt.Fprintf(&b, "Connection: %s\r\n", l)
+ }
+ b.WriteString("Upgrade: websocket\r\n\r\n")
+ if _, err := io.WriteString(c, b.String()); err != nil {
+ c.Close()
+ return nil, nil, nil, "", err
+ }
+ br := bufio.NewReader(c)
+ resp, err := http.ReadResponse(br, nil)
+ if err != nil {
+ c.Close()
+ return nil, nil, nil, "", err
+ }
+ body := ""
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ bb, _ := io.ReadAll(resp.Body)
+ body = string(bb)
+ }
+ return c, br, resp, body, nil
+}
+
+// echoes checks the socket on c carries msg to the app and its echo back.
+func echoes(t *testing.T, c net.Conn, br *bufio.Reader, msg string) {
+ t.Helper()
+ if _, err := io.WriteString(c, msg+"\n"); err != nil {
+ t.Fatalf("write %q: %v", msg, err)
+ }
+ line, err := br.ReadString('\n')
+ if err != nil || line != "echo:"+msg+"\n" {
+ t.Fatalf("read %q, %v; want the app's echo of %q", line, err, msg)
+ }
+}
+
+// waitOpen waits up to 2 s for the registry's count on tc to be want (no
+// entry for 0).
+func waitOpen(t *testing.T, e *Edge, tc *tunnelConn, want int, what string) {
+ t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ n, ok := openCount(e, tc)
+ if n == want && ok == (want != 0) {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("%s: the channel's open count is %d (entry %v) after 2 s, want %d", what, n, ok, want)
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+}
+
+// wantCause waits up to 2 s for the sink to hold a record for status with
+// cause: the request's noted cause, as the edge files it.
+func wantCause(t *testing.T, sink *memErrSink, status int, cause string) {
+ t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ for _, r := range sink.snap() {
+ if r.Status == status && r.Cause == cause {
+ return
+ }
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("no %d with cause %q was filed within 2 s; filed: %+v", status, cause, sink.snap())
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+}
+
+func TestForwardUpgradeAnswers101(t *testing.T) {
+ hubURL, _, _, app := policyScene(t)
+ c, br, resp, body := polUpgrade(t, hubURL)
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("handshake: %d %q, want the app's 101", resp.StatusCode, body)
+ }
+ if got := resp.Header.Get("Upgrade"); !strings.EqualFold(got, "websocket") {
+ t.Fatalf("101 Upgrade %q, want websocket", got)
+ }
+ echoes(t, c, br, "hello")
+ echoes(t, c, br, "and again")
+ if _, ups := app.counts(); ups != 1 {
+ t.Fatalf("the app saw %d upgrades, want 1", ups)
+ }
+}
+
+// Review Focus 2: a browser that sends Connection on two lines is admitted
+// through the upgrade branch (the hub counted its socket) and gets the 101,
+// rather than reaching the box as a plain GET.
+func TestUpgradeOnASecondConnectionLine(t *testing.T) {
+ hubURL, hub, _, app := policyScene(t)
+ tc := hub.tunnels.channel("home/box-1")
+ if tc == nil {
+ t.Fatal("home/box-1 has no channel connection")
+ }
+ c, br, resp, body, err := rawUpgrade(hubURL, polHost, "keep-alive", "Upgrade")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("handshake with two Connection lines: %d %q, want the app's 101", resp.StatusCode, body)
+ }
+ if n, ok := openCount(hub, tc); n != 1 || !ok {
+ t.Fatalf("with the socket open the channel's open count is %d (entry %v), want 1", n, ok)
+ }
+ echoes(t, c, br, "two lines")
+ if gets, ups := app.counts(); ups != 1 || gets != 0 {
+ t.Fatalf("the app saw %d upgrades and %d GETs, want 1 and 0", ups, gets)
+ }
+}
+
+// An upgrade that never came through the upgrade branch carries no
+// admission, and the transport refuses it before anything reaches the box.
+// Control: the same call with the admission the branch writes gets the
+// app's 101, and closing its body gives the channel's slot back.
+func TestUpgradeWithoutAdmissionIsRefused(t *testing.T) {
+ _, hub, _, app := policyScene(t)
+ tc := hub.tunnels.channel("home/box-1")
+ rt := hub.tunnels.transportFor("home/box-1")
+
+ if _, err := rt.RoundTrip(wsRequest()); !errors.Is(err, errNoAdmission) {
+ t.Fatalf("an upgrade with no admission: %v, want errNoAdmission", err)
+ }
+ if _, ups := app.counts(); ups != 0 {
+ t.Fatalf("the app saw %d upgrades, want 0", ups)
+ }
+ if n, ok := openCount(hub, tc); ok || n != 0 {
+ t.Fatalf("after the refusal the open count is %d (entry %v), want none", n, ok)
+ }
+
+ ten, ok := tenancyAt(hub, polHost)
+ if !ok || ten.Arm != ArmForward {
+ t.Fatalf("%s served %v with tenancy %+v, want the forward arm", polHost, ok, ten)
+ }
+ req := wsRequest()
+ req = req.WithContext(withUpgradeAdmission(req.Context(), upgradeAdmission{Host: polHost, Path: "/cable", Tenancy: ten}))
+ resp, err := rt.RoundTrip(req)
+ if err != nil {
+ t.Fatalf("an admitted upgrade: %v", err)
+ }
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("an admitted upgrade: %d, want 101", resp.StatusCode)
+ }
+ if _, ok := resp.Body.(io.ReadWriteCloser); !ok {
+ t.Fatalf("the 101's body is %T, want an io.ReadWriteCloser for the proxy", resp.Body)
+ }
+ if _, ok := resp.Body.(interface{ CloseWrite() error }); !ok {
+ t.Fatalf("the 101's body is %T, want CloseWrite kept for the proxy's half-close", resp.Body)
+ }
+ if n, ok := openCount(hub, tc); n != 1 || !ok {
+ t.Fatalf("with the socket open the count is %d (entry %v), want 1", n, ok)
+ }
+ resp.Body.Close()
+ if n, ok := openCount(hub, tc); ok || n != 0 {
+ t.Fatalf("after the body's Close the count is %d (entry %v), want none", n, ok)
+ }
+ if _, ups := app.counts(); ups != 1 {
+ t.Fatalf("the app saw %d upgrades, want 1", ups)
+ }
+}
+
+// An old box (no Carlos-Tunnel-Caps on its registration, no shim) keeps
+// today's 502 for an upgrade, now with its own cause. Control: a plain GET
+// to the same box answers.
+func TestOldBoxKeepsThe502(t *testing.T) {
+ const oldHost = "old.example.com"
+ app := &polBackend{closed: make(chan struct{}, 8)}
+ appAddr := startPolBackend(t, app)
+ hubURL, hub, box := forwardHubAndBox(t,
+ []registry.Route{forwardRow(oldHost, "away", fwdOwner)},
+ []registry.Route{{Host: oldHost, Kind: "instance", Status: "ready", Addr: appAddr, Account: fwdOwner, App: "shop"}},
+ nil)
+ sink := &memErrSink{}
+ hub.EnableErrors(sink)
+
+ // away/box-2 registers by hand without the capability and serves the
+ // box Edge with no shim, as a release before #471 does.
+ u, err := url.Parse(hubURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ conn, err := net.Dial("tcp", u.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { conn.Close() })
+ req := tunnelReq("away/box-2", fwdBox2Tok)
+ req.Host = hub.tunnels.Host()
+ if err := req.Write(conn); err != nil {
+ t.Fatal(err)
+ }
+ br := bufio.NewReader(conn)
+ resp, err := http.ReadResponse(br, req)
+ if err != nil || resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("registration = %v, %v; want 101", resp, err)
+ }
+ go tunnelclient.ServeWith(conn, box, tunnelclient.DefaultLimits)
+ waitForTunnelState(t, hub.tunnels, "away/box-2", "connected", e2eReconnectBound)
+ if tc := hub.tunnels.channel("away/box-2"); tc == nil || tc.caps != "" {
+ t.Fatalf("away/box-2 = %+v, want a channel with no caps", tc)
+ }
+
+ c, _, uresp, body, err := rawUpgrade(hubURL, oldHost)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Close()
+ if uresp.StatusCode != http.StatusBadGateway {
+ t.Fatalf("an upgrade to the old box: %d %q, want 502", uresp.StatusCode, body)
+ }
+ wantCause(t, sink, http.StatusBadGateway, "tunnel_upgrade_unsupported")
+ if gets, ups := app.counts(); gets != 0 || ups != 0 {
+ t.Fatalf("the app saw %d GETs and %d upgrades, want none", gets, ups)
+ }
+ gresp, b := fwdDo(t, hubURL, "GET", oldHost, "/", "", nil)
+ if gresp.StatusCode != http.StatusOK || string(b) != "ok" {
+ t.Fatalf("a plain GET to the old box: %d %q, want the app's 200", gresp.StatusCode, b)
+ }
+}
+
+// The per-channel cap (spec §4.8), lowered to 2 on this hub: two sockets
+// open, the third handshake is 503 with Retry-After 5 and TWS-C03, plain
+// requests still flow, and closing one socket admits a new handshake.
+func TestCapAnswers503(t *testing.T) {
+ hubURL, hub, _, _ := policySceneRates(t, polWideRate, polWideRate)
+ hub.tunnels.upgradeCap = 2
+ sink := &memErrSink{}
+ hub.EnableErrors(sink)
+ tc := hub.tunnels.channel("home/box-1")
+
+ var conns []net.Conn
+ for i := 1; i <= 2; i++ {
+ c, br, resp, body := polUpgrade(t, hubURL)
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("socket %d: %d %q, want 101", i, resp.StatusCode, body)
+ }
+ echoes(t, c, br, fmt.Sprintf("socket %d", i))
+ conns = append(conns, c)
+ }
+ _, _, resp, body := polUpgrade(t, hubURL)
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "5" || body != twsBusyText {
+ t.Fatalf("the third handshake: %d, Retry-After %q, body %q; want 503, 5 and TWS-C03", resp.StatusCode, resp.Header.Get("Retry-After"), body)
+ }
+ wantCause(t, sink, http.StatusServiceUnavailable, "tunnel_busy")
+ if gresp, b := fwdDo(t, hubURL, "GET", polHost, "/", "", nil); gresp.StatusCode != http.StatusOK || string(b) != "ok" {
+ t.Fatalf("a plain GET with both sockets open: %d %q, want 200", gresp.StatusCode, b)
+ }
+
+ conns[0].Close()
+ waitOpen(t, hub, tc, 1, "after one socket closed")
+ c, br, resp, body := polUpgrade(t, hubURL)
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("a handshake after one socket closed: %d %q, want 101", resp.StatusCode, body)
+ }
+ echoes(t, c, br, "socket 3")
+}
+
+// hungApp accepts TCP connections and never answers on them, like an app
+// still booting.
+func hungApp(t *testing.T) string {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var mu sync.Mutex
+ var held []net.Conn
+ go func() {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ mu.Lock()
+ held = append(held, c)
+ mu.Unlock()
+ }
+ }()
+ t.Cleanup(func() {
+ ln.Close()
+ mu.Lock()
+ defer mu.Unlock()
+ for _, c := range held {
+ c.Close()
+ }
+ })
+ return ln.Addr().String()
+}
+
+// Review Focus 1: the box's app never answers the handshake. While the
+// client waits the hub holds one reservation; when the client gives up the
+// request ends and the slot comes back within 2 s, and the box's other
+// traffic keeps flowing.
+func TestHungHandshakeReleasesAtRequestEnd(t *testing.T) {
+ const hungHost = "hung.example.com"
+ app := &polBackend{closed: make(chan struct{}, 8)}
+ appAddr := startPolBackend(t, app)
+ hubURL, hub, _ := forwardHubAndBox(t,
+ []registry.Route{forwardRow(hungHost, "home", fwdOwner), forwardRow(polHost, "home", fwdOwner)},
+ []registry.Route{
+ {Host: hungHost, Kind: "instance", Status: "ready", Addr: hungApp(t), Account: fwdOwner, App: "hung"},
+ {Host: polHost, Kind: "instance", Status: "ready", Addr: appAddr, Account: fwdOwner, App: "shop"},
+ }, nil)
+ tc := hub.tunnels.channel("home/box-1")
+
+ type answer struct {
+ resp *http.Response
+ err error
+ }
+ c, err := net.Dial("tcp", strings.TrimPrefix(hubURL, "http://"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", hungHost)
+ got := make(chan answer, 1)
+ c.SetReadDeadline(time.Now().Add(time.Second))
+ go func() {
+ resp, err := http.ReadResponse(bufio.NewReader(c), nil)
+ got <- answer{resp, err}
+ }()
+ waitOpen(t, hub, tc, 1, "while the handshake hangs")
+ a := <-got
+ var ne net.Error
+ if a.err == nil || !errors.As(a.err, &ne) || !ne.Timeout() {
+ t.Fatalf("the hung handshake: %+v, want no answer within 1 s", a)
+ }
+ c.Close() // the client gives up
+
+ waitOpen(t, hub, tc, 0, "after the client gave up")
+ if resp, b := fwdDo(t, hubURL, "GET", polHost, "/", "", nil); resp.StatusCode != http.StatusOK || string(b) != "ok" {
+ t.Fatalf("a plain GET to another host on the box: %d %q, want 200", resp.StatusCode, b)
+ }
+}
+
+// A TunnelHub used without EnableTunnels (P2-3) has no edge, and so no
+// registry to reserve in: it refuses an upgrade with errNoAdmission, with
+// or without an admission on the request, and does not panic. Control: a
+// plain request on the same capable channel answers.
+func TestHubWithoutEdgeRefusesUpgrades(t *testing.T) {
+ th := NewTunnelHub("tunnel.example.com", map[string]string{"t1": fwdT1Tok})
+ srv := httptest.NewServer(th)
+ t.Cleanup(srv.Close)
+ app := &polBackend{closed: make(chan struct{}, 8)}
+ stop := startFakeRemoteHost(t, srv.URL, "t1", fwdT1Tok, app)
+ t.Cleanup(stop)
+ waitForTunnelState(t, th, "t1", "connected", e2eReconnectBound)
+ if tc := th.channel("t1"); tc == nil || tc.caps != tunnelclient.CapUpgrade {
+ t.Fatalf("t1 = %+v, want a channel with the capability", tc)
+ }
+
+ rt := th.transportFor("t1")
+ roundTrip := func(req *http.Request) (resp *http.Response, err error) {
+ defer func() {
+ if p := recover(); p != nil {
+ t.Fatalf("RoundTrip panicked: %v", p)
+ }
+ }()
+ return rt.RoundTrip(req)
+ }
+ if _, err := roundTrip(wsRequest()); !errors.Is(err, errNoAdmission) {
+ t.Fatalf("an upgrade with no admission: %v, want errNoAdmission", err)
+ }
+ req := wsRequest()
+ req = req.WithContext(withUpgradeAdmission(req.Context(), upgradeAdmission{Host: polHost, Path: "/cable", Tenancy: upTenancy}))
+ if _, err := roundTrip(req); !errors.Is(err, errNoAdmission) {
+ t.Fatalf("an upgrade with an admission on a hub with no edge: %v, want errNoAdmission", err)
+ }
+ if _, ups := app.counts(); ups != 0 {
+ t.Fatalf("the app saw %d upgrades, want 0", ups)
+ }
+
+ plain, err := http.NewRequest("GET", "https://"+polHost+"/", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := roundTrip(plain)
+ if err != nil {
+ t.Fatalf("a plain request: %v", err)
+ }
+ b, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK || string(b) != "ok" {
+ t.Fatalf("a plain request: %d %q, want the app's 200", resp.StatusCode, b)
+ }
+}
+
+// An admission the hub's branch wrote on a map that a Reload then revoked
+// (the fleet's owner changed) is refused when the transport reserves: 502
+// with cause tunnel, and the app never sees the handshake. The pause is
+// reserveUpgrade's beforeReserve seam. Control: the same schedule with a
+// Reload that revokes nothing answers the app's 101.
+func TestStaleAdmissionIsRefused(t *testing.T) {
+ for _, revoke := range []bool{false, true} {
+ t.Run(map[bool]string{false: "control", true: "revoked"}[revoke], func(t *testing.T) {
+ hubURL, hub, _, app := policyScene(t)
+ sink := &memErrSink{}
+ hub.EnableErrors(sink)
+ paused, resume := make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ hub.open.beforeReserve = func() {
+ once.Do(func() {
+ close(paused)
+ <-resume
+ })
+ }
+ type answer struct {
+ c net.Conn
+ resp *http.Response
+ body string
+ err error
+ }
+ got := make(chan answer, 1)
+ go func() {
+ c, _, resp, body, err := rawUpgrade(hubURL, polHost)
+ got <- answer{c, resp, body, err}
+ }()
+ select {
+ case <-paused:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the handshake did not reach the reservation within 5 s")
+ }
+ if revoke {
+ setFleetOwner(t, hub, "home", fwdOther)
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ close(resume)
+ var a answer
+ select {
+ case a = <-got:
+ case <-time.After(5 * time.Second):
+ t.Fatal("no answer within 5 s of resuming")
+ }
+ if a.err != nil {
+ t.Fatal(a.err)
+ }
+ defer a.c.Close()
+ _, ups := app.counts()
+ if !revoke {
+ if a.resp.StatusCode != http.StatusSwitchingProtocols || ups != 1 {
+ t.Fatalf("control: %d %q, the app saw %d upgrades; want 101 and 1", a.resp.StatusCode, a.body, ups)
+ }
+ return
+ }
+ if a.resp.StatusCode != http.StatusBadGateway {
+ t.Fatalf("after the revoking Reload: %d %q, want 502", a.resp.StatusCode, a.body)
+ }
+ wantCause(t, sink, http.StatusBadGateway, apperr.CauseTunnel)
+ if ups != 0 {
+ t.Fatalf("the app saw %d upgrades, want 0", ups)
+ }
+ })
+ }
+}
diff --git a/internal/edge/upgrades_test.go b/internal/edge/upgrades_test.go
index 91331ea8a..1e9b2da67 100644
--- a/internal/edge/upgrades_test.go
+++ b/internal/edge/upgrades_test.go
@@ -3,8 +3,8 @@ package edge
// Tunnel WebSockets (#471) Task 3: the hub's registry of open upgrades, the
// reservation and its exactly-once release, the per-route tenancy record,
// the channel's capability and the scrub of client-sent marker headers.
-// Upgrades are still refused at the hub (TestUpgradesStillRefusedBeforeSwitchOn);
-// nothing calls reserveUpgrade outside these tests yet.
+// Task 5 switches the hub's marker on (tunnel_upgrade_test.go); these tests
+// drive the registry directly.
//
// Accounts: fwdOwner ("bah") owns fleets home and away; fwdOther ("baj")
// is the second, valid non-ops account, used for the -tunnel row.
@@ -600,21 +600,3 @@ func TestLimitsInvariant(t *testing.T) {
t.Errorf("NewTunnelHub's upgradeCap = %d, want tunnelUpgradeCap", h.upgradeCap)
}
}
-
-// Pins this task's dormancy: the hub still refuses an upgrade for a forward
-// row with today's 502, and the app never sees it. Task 5 replaces this
-// with the 101.
-func TestUpgradesStillRefusedBeforeSwitchOn(t *testing.T) {
- hubURL, _, _, app := policyScene(t)
- _, _, resp, body := polUpgrade(t, hubURL)
- if resp.StatusCode != http.StatusBadGateway {
- t.Fatalf("handshake = %d %q, want the hub's 502", resp.StatusCode, body)
- }
- if _, ups := app.counts(); ups != 0 {
- t.Fatalf("the app saw %d upgrades, want 0", ups)
- }
- // Control: the same scene serves a plain GET.
- if resp, b := fwdDo(t, hubURL, "GET", polHost, "/", "", nil); resp.StatusCode != http.StatusOK || string(b) != "ok" {
- t.Fatalf("GET = %d %q, want the app's 200", resp.StatusCode, b)
- }
-}