carlos / platform Public

edge: the hub's open-upgrades registry, reservation, tenancy and scrub (#471 Task 3)

Upgrades are still refused at the hub (TestUpgradesStillRefusedBeforeSwitchOn
pins today's 502); nothing calls reserveUpgrade outside tests yet.

- upgrades.go: tenancy, upgradeAdmission and its context helpers,
  openUpgrades (by host, counted per channel connection),
  upgradeReservation (attach, release once under sync.Once with a
  context.AfterFunc backstop on the inbound request, firstReleaser),
  reserveUpgrade (tenancy current and under the cap, under the
  registry's lock), tunnelUpgradeCap = 128, four sentinels. release
  cancels the stream context before closing the body (Task 2 carry).
- Reload records upstream.tenancy on ArmForward, ArmFleet (from
  FleetArmVerdict's served) and ArmTunnel (from the row); the alias folds
  copy it.
- TunnelHub: conn becomes channel (callers State and transportFor
  migrated), tunnelConn.caps from the registration, upgradeCap set by
  NewTunnelHub.
- Marker scrub: Edge.ServeHTTP deletes Carlos-Tunnel-Upgrade inbound;
  fleetProxy and tunnelProxy Rewrite delete both markers.
- tunnelclient.RoundTripUpgrade honours the box's marker only on a 200
  (Task 2 review carry); a marked non-200 passes through as a refusal.
- Spec §7 reconciled with Task 3's census card.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0fe483dba7919c9e427043ff796fca693e096d05 parent 249b38f
7 files changed, +995 −15
  • docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md +28 −0
  • internal/edge/edge.go +34 −1
  • internal/edge/tunnel.go +22 −11
  • internal/edge/upgrades.go +235 −0
  • internal/edge/upgrades_test.go +620 −0
  • internal/tunnelclient/upgrade.go +7 −3
  • internal/tunnelclient/upgrade_hub_test.go +49 −0

Intent

Human

<task-notification> <task-id>a0cf7c28884b23477</task-id> <tool-use-id>toolu_01Qny6BPrJijhYuVE25Gn8HE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a0cf7c28884b23477.output</output-file> <status>completed</status> <summary>Agent "#471 Task 0: copy deck" 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 Commit: 249b38f4 (not pushed). The packed-refs.lock error appeared, but the commit landed. Tests: the six `TestTunnelWebSocketsCopy*` tests pass (`go test . -run TestTunnelWebSocketsCopy -count=1`). With temporary edits, the gate failed when a built id's row was pending, and when a built row's text was missing from its named file. I restored both files afterwards. Editing a deck text with nothing built still passes. The gate checks built rows against their files and does not pin deck text to `copy-approved.json`. I checked TWS-C01 to C03 against `copy-approved.json` byte for byte with a script. Concerns: none. Files are in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-tunnel-websockets-471`: - `docs/superpowers/plans/2026-10-30-tunnel-websockets-copy.md` - `approved_tunnel_websockets_copy_test.go` - `.superpowers/sdd/2026-10-30-tunnel-websockets/task-0-report.md` (gitignored, so not in the commit)</result> <usage><subagent_tokens>49793</subagent_tokens><tool_uses>6</tool_uses><duration_ms>58926</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a7b99c53037969657</task-id> <tool-use-id>toolu_01EYoC4dVFnFXhc4mrVUFNe6</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a7b99c53037969657.output</output-file> <status>completed</status> <summary>Agent "Review Plan 6 Task 3" 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>**Spec compliance:** ✅ compliant. The `censusKeyExact` addition (plan9_b8_census_test.go:56) is extra but needed, and I approve it. **Task quality:** Approved. No Critical or Important findings. Findings: - **Minor:** Nothing enforces "only the Interactive* transitions write Record.Interactive" (interactive.go:15, provision.go:89). Today only interactive.go:74 and :86 assign it, but any `SetRecord*` change or a whole-record `UpdateRecord` call could set it. A short source test like `TestOnlyRunAdmitWritesRunKeys` covering every package that imports provision would close this. - **Minor:** The admission checks only that the ID is not empty, not its format (interactive.go:65). Only the console writes records and `RunAdmit` doesn't check ids either, so this is extra safety. The fix belongs in Task 12: check `interactive.ValidID` before `GrantKey`. - **Minor:** The stale-record judge test doesn't check that the mutation was never called (interactive_test.go:262). The reference test does, but zero puts and unchanged bytes already cover the outcome. - **Minor:** The reconcile hook test doesn't cover trashed apps, journal-handled hosts or fleet-collision hosts (interactive_test.go:276). The hook sits in the same place as `RunSeen`, so the risk is low. - **⚠️ Cross-task:** The marker survives a move (the test confirms it) and has no incarnation or box field. Moves, incarnation changes and stale markers are handled only by Task 9 (the move freeze), Task 11 (the sweep) and Task 12 (ownership, `PickupBy`, the incarnation refusal). Confirm each when it lands. - **⚠️ Cross-task:** No seed transition refuses an import starting while a session is open; seed.go:234 refuses only an open run. If anything catches that, it has to be Task 9. - **Checks, no finding:** - The hook fires on in-scope records, not only ones the box owns, exactly as `RunSeen` does. Ownership is Task 12's step 1. - Records without the marker are unchanged. - An older box binary that rewrites the record drops the marker. That only matters on a box that can't serve sessions anyway. - The root-read census overlay's claim is accurate (seal d62fb15b). Astra's approval on #280 is still owed. - `TestPlan9B8RecordWriteCensus` and `TestSetRecordInteractiveIsJudged` passed at f49c43b1. Review written to /home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/.superpowers/sdd/2026-10-24-rootfs-apps-6-interactive/task-3-review.md</result> <usage><subagent_tokens>112397</subagent_tokens><tool_uses>18</tool_uses><duration_ms>198768</duration_ms></usage> </task-notification>

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 0cb4f0ad7..b5b8cc269 100644
--- a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
+++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
@@ -983,6 +983,34 @@ rest of `UpgradeConn` (`Write`, `CloseWrite`, `Close`),
`UpgradeHandshakeTimeout` read nothing and have no row; the envelope
re-pin covers them.
+Task 3's card adds two units in `internal/edge` and re-pins its envelope:
+
+- `body` `Edge.ServeHTTP`: one header delete
+ (`r.Header.Del(tunnelclient.UpgradeHeader)`); read sites unchanged (29).
+- `reads` `Edge.Reload`: `+registry:Account`, `+registry:App`,
+ `+registry:Tunnel`. These are the `ArmTunnel` arm's tenancy, copied from
+ the row `t` that `Reload` already lists (`t.Account`, `t.App`,
+ `t.Tunnel`). They add no registry query and no file read. The
+ `ArmForward` and `ArmFleet` tenancy comes from `FleetArmVerdict`'s
+ `served`, which `Reload` already used to pick the fleet, so the card
+ shows no read for it. So "no `reads`" above stands in substance: the
+ class is the scanner naming three more fields of a row already in hand.
+ The reload mutex and the sweep call are Task 4's and will show on its
+ card.
+
+`TunnelHub.ServeHTTP` (records `caps`), `TunnelHub.State` and
+`transportFor` (now `channel`, which replaces `conn`), `NewTunnelHub`
+(sets `upgradeCap`), `fleetProxy` and `tunnelProxy` (their `Rewrite` calls
+the new `scrubTunnelMarkers`), and the new `upgrades.go` declarations
+(`tenancy`, `upgradeAdmission` with `withUpgradeAdmission` and
+`upgradeAdmissionFrom`, `openUpgrades`, `upgradeReservation` with
+`attach`, `release`, `firstReleaser` and `openUpgrades.remove`,
+`reserveUpgrade`, `tunnelUpgradeCap`, the four sentinels) read nothing.
+They have no row, so the `internal/edge` envelope re-pin covers them. The
+`internal/tunnelclient` envelope moves again for one condition in
+`RoundTripUpgrade`: the marker counts only on a 200 (Task 2 review). 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/edge/edge.go b/internal/edge/edge.go
index f6a9f8421..99bfcd2d6 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -64,6 +64,7 @@ import (
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/reqrec"
+ "github.com/carlosframework/platform/internal/tunnelclient"
)
// Default cache sizing for EnableCache: 4096 entries is comfortably above a
@@ -359,6 +360,10 @@ type Edge struct {
planLimiter *ratelimit.Limiter
upgradesMu sync.Mutex
upgrades map[string]map[*int]context.CancelFunc
+ // open is the hub's registry of upgraded streams over its tunnels
+ // (upgrades.go, #471): reservations by host and counts per channel
+ // connection. Its lock is never held with upgradesMu.
+ open openUpgrades
}
// RunOption configures the Edge that Run/RunWithActivator* builds, before it
@@ -469,6 +474,12 @@ type upstream struct {
// key the gate logs under.
regional regionalMode
regionalKey string
+ // tenancy is what this host is served under when it goes through a
+ // tunnel (upgrades.go): set by Reload for ArmForward, ArmFleet and
+ // ArmTunnel, zero for every other arm, copied by the alias folds with
+ // the rest of the entry. An open upgrade stays only while the current
+ // map still serves its host with the tenancy it was admitted under.
+ tenancy tenancy
}
// New builds an Edge over reg and performs the startup reload. act may be nil
@@ -826,6 +837,9 @@ func (e *Edge) Reload() error {
// genManaged: an activator-managed instance reached through its
// current generation (appSocketProxy), generations on only.
genManaged := false
+ // ten: the tenancy of a host served through a tunnel (upgrades.go),
+ // from the same value that picks the arm's destination below.
+ var ten tenancy
// served is the fleet arm's answer for this row (FleetArmVerdict's
// Arm): both fleet cases below take their fleet from it, and nothing
// else reaches a fleet's tunnel. The arm itself is DispatchArm, the
@@ -851,6 +865,7 @@ func (e *Edge) Reload() error {
p.ModifyResponse = e.responseModifier(t)
proxy = p
viaTunnel = true
+ ten = tenancy{Arm: ArmForward, Account: served.Account, App: served.App, Fleet: served.Fleet}
// Both reverse proxies get the Carlos-Purge response hook
// (purge_header.go): the app declares its own cache invalidations on
// the response it is already returning, and the edge applies them and
@@ -893,6 +908,7 @@ func (e *Edge) Reload() error {
p.ModifyResponse = e.responseModifier(t)
proxy = p
viaTunnel = true
+ ten = tenancy{Arm: ArmTunnel, Account: t.Account, App: t.App, Tunnel: t.Tunnel}
// Fleet placement (Region == "fleet/<name>", registry.FleetPlacement) is
// a customer-fleet route: its bytes leave the box over the SAME reverse
// channel a `-tunnel` binding uses, just resolved dynamically per
@@ -921,6 +937,7 @@ func (e *Edge) Reload() error {
p.ModifyResponse = e.responseModifier(t)
proxy = p
viaTunnel = true
+ ten = tenancy{Arm: ArmFleet, Account: served.Account, App: served.App, Fleet: served.Fleet}
case ArmSocket:
// An activator-managed instance's process binds a generation
// socket, not t.Socket, once generations are on (spec §7.1):
@@ -1100,7 +1117,7 @@ func (e *Edge) Reload() error {
t.Host, t.Socket))
}
m[t.Host] = upstream{proxy: proxy, route: t, hibernating: hib, viaTunnel: viaTunnel, genManaged: genManaged,
- rate: e.parseRateSettings(t)}
+ rate: e.parseRateSettings(t), tenancy: ten}
}
// Path routes, folded BEFORE aliases so an alias of a prefix-routed
// hostname inherits its map along with everything else it copies — an
@@ -1788,6 +1805,10 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !hopped {
r.Header.Del(assetFillHeader)
}
+ // The tunnel's upgrade marker (tunnelclient.UpgradeHeader, #471 §4.4)
+ // is this hub's to send, and only on a stream its upgrade branch
+ // admitted: never a client's, on any arm.
+ r.Header.Del(tunnelclient.UpgradeHeader)
// GeoIP steps 3-4 (geoip spec §8.1, §8.2): decide once, keep it on the
// context for setGeo and analytics, and expose the app-visible headers on
// r.Header so the cache's Vary matching sees exactly what the app will
@@ -3190,12 +3211,23 @@ func tunnelProxy(name string, hub *TunnelHub) *httputil.ReverseProxy {
pr.Out.URL.Host = pr.In.Host // h2 :authority = the real hostname
pr.Out.Host = pr.In.Host
scrubInboundPurgeHeader(pr)
+ scrubTunnelMarkers(pr)
},
Transport: hub.transportFor(name),
ErrorHandler: defaultProxyError(tunnelCause),
}
}
+// 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
+// the transport sets it after this Rewrite; Carlos-Tunnel-Upgraded is the
+// box's answer, never part of a request.
+func scrubTunnelMarkers(pr *httputil.ProxyRequest) {
+ pr.Out.Header.Del(tunnelclient.UpgradeHeader)
+ pr.Out.Header.Del(tunnelclient.UpgradedHeader)
+}
+
// errFleetDark is the sentinel fleetProxy's Transport returns when fleet has
// no connected channel at all — neither the route's bound box nor any
// fallback. fleetProxy's ErrorHandler recognizes it and answers a clean 503
@@ -3246,6 +3278,7 @@ func fleetProxy(fleet, boxLabel string, hub *TunnelHub) *httputil.ReverseProxy {
pr.Out.URL.Host = pr.In.Host // h2 :authority = the real hostname
pr.Out.Host = pr.In.Host
scrubInboundPurgeHeader(pr)
+ scrubTunnelMarkers(pr)
},
Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
name := fleetChannelFor(fleet, boxLabel, hub)
diff --git a/internal/edge/tunnel.go b/internal/edge/tunnel.go
index 7f619d995..1f6f808bc 100644
--- a/internal/edge/tunnel.go
+++ b/internal/edge/tunnel.go
@@ -24,6 +24,8 @@ import (
"golang.org/x/net/http/httpguts"
"golang.org/x/net/http2"
+
+ "github.com/carlosframework/platform/internal/tunnelclient"
)
const (
@@ -76,6 +78,10 @@ type tunnelConn struct {
// (fleet) credential source rather than the static env map — the one fact
// ServeHTTP knows and pingLoop needs for pingCadence.
dynamic bool
+ // caps is the box's Carlos-Tunnel-Caps from its registration, as sent
+ // ("" from a box that predates it). The hub sends an upgrade only to a
+ // connection whose caps are tunnelclient.CapUpgrade (spec §4.9).
+ caps string
}
type TunnelHub struct {
@@ -91,10 +97,14 @@ type TunnelHub struct {
// is always true for a dynamic name — ValidTunnelName-checked static
// names never contain "/".
dynamicAuth map[string]string
+ // upgradeCap is the most upgraded streams one channel connection may
+ // carry at once: tunnelUpgradeCap, set by NewTunnelHub, so a test can
+ // lower it on its own hub.
+ upgradeCap int
}
func NewTunnelHub(host string, clients map[string]string) *TunnelHub {
- return &TunnelHub{host: host, clients: clients, conns: make(map[string]*tunnelConn)}
+ return &TunnelHub{host: host, clients: clients, conns: make(map[string]*tunnelConn), upgradeCap: tunnelUpgradeCap}
}
func (h *TunnelHub) Host() string { return h.host }
@@ -210,7 +220,7 @@ func (h *TunnelHub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if old := h.conns[name]; old != nil {
old.raw.Close() // a re-register replaces the previous channel
}
- h.conns[name] = &tunnelConn{cc: cc, raw: conn, dynamic: viaDynamic}
+ h.conns[name] = &tunnelConn{cc: cc, raw: conn, dynamic: viaDynamic, caps: r.Header.Get(tunnelclient.CapsHeader)}
h.mu.Unlock()
log.Printf("edge: tunnel %s: connected from %s", name, conn.RemoteAddr())
go h.pingLoop(name, cc, conn, viaDynamic)
@@ -345,20 +355,21 @@ func (h *TunnelHub) CloseChannel(name string) {
h.mu.Unlock()
}
-func (h *TunnelHub) conn(name string) *http2.ClientConn {
+// channel is name's live connection, nil when it has none. The connection,
+// not just its HTTP/2 client, so that what the hub checks about a channel
+// (its caps, its count of open upgrades) is about the connection it then
+// streams on.
+func (h *TunnelHub) channel(name string) *tunnelConn {
h.mu.Lock()
defer h.mu.Unlock()
- if c := h.conns[name]; c != nil {
- return c.cc
- }
- return nil
+ return h.conns[name]
}
// State reports "connected" or "". The heartbeat's tunnel-state field comes
// from the host-side dial loop, not from here; today this is test-consumed
// only — no production caller reads it.
func (h *TunnelHub) State(name string) string {
- if h.conn(name) != nil {
+ if h.channel(name) != nil {
return "connected"
}
return ""
@@ -392,10 +403,10 @@ func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { r
// reconnect uses the fresh channel afterwards with no reload needed.
func (h *TunnelHub) transportFor(name string) http.RoundTripper {
return roundTripperFunc(func(req *http.Request) (*http.Response, error) {
- cc := h.conn(name)
- if cc == nil {
+ tc := h.channel(name)
+ if tc == nil {
return nil, fmt.Errorf("tunnel %q not connected", name)
}
- return cc.RoundTrip(req)
+ return tc.cc.RoundTrip(req)
})
}
diff --git a/internal/edge/upgrades.go b/internal/edge/upgrades.go
new file mode 100644
index 000000000..8e34f41b4
--- /dev/null
+++ b/internal/edge/upgrades.go
@@ -0,0 +1,235 @@
+package edge
+
+// The hub's open upgrades (tunnel WebSockets, #471 spec §4.6.1, §4.6.2,
+// §4.8): what a request was admitted under, the registry of upgraded
+// streams the hub has open on each channel connection, and the one object
+// that owns each of them, released exactly once.
+//
+// The lock rules (§4.6.1): openUpgrades.mu is never held together with
+// TunnelHub.mu or e.upgradesMu, and nothing runs under it but map
+// operations and lookupUpstreamPath, which is lock-free over the atomically
+// loaded map. A release closes streams, so it never runs under the lock.
+
+import (
+ "context"
+ "errors"
+ "io"
+ "sync"
+ "sync/atomic"
+)
+
+// tunnelUpgradeCap is how many upgraded streams the hub keeps open on one
+// channel connection (spec §4.8). With tunnelclient.DefaultLimits it keeps
+// both halves of the invariant TestLimitsInvariant asserts: below
+// MaxStreams, so plain requests always have stream slots, and within
+// ConnWindow less PlainHeadroom, so plain request bodies always have
+// connection credit.
+const tunnelUpgradeCap = 128
+
+// tenancy is what a served host was admitted under (spec §4.6.1): the
+// dispatch arm, and the account, app and fleet or tunnel the arm sends it
+// to. Reload sets it on the upstreams it builds for ArmForward and ArmFleet
+// (from FleetArmVerdict's Arm, the value that picks the proxy's fleet) and
+// for ArmTunnel (from the row); every other entry has the zero tenancy. An
+// alias copies its source's entry, and so its tenancy. Nothing else
+// computes it.
+type tenancy struct {
+ Arm Arm
+ Account, App, Fleet, Tunnel string
+}
+
+// upgradeAdmission is what the hub's upgrade branch admitted a request
+// under: its host and path, and the tenancy of the map entry it was
+// dispatched on. The transport re-checks it against the map when it
+// reserves (reserveUpgrade).
+type upgradeAdmission struct {
+ Host, Path string
+ Tenancy tenancy
+}
+
+type upgradeAdmissionKey struct{}
+
+// withUpgradeAdmission puts a on ctx, for the tunnel transport.
+func withUpgradeAdmission(ctx context.Context, a upgradeAdmission) context.Context {
+ return context.WithValue(ctx, upgradeAdmissionKey{}, a)
+}
+
+// upgradeAdmissionFrom reads the admission withUpgradeAdmission put on ctx.
+func upgradeAdmissionFrom(ctx context.Context) (upgradeAdmission, bool) {
+ a, ok := ctx.Value(upgradeAdmissionKey{}).(upgradeAdmission)
+ return a, ok
+}
+
+var (
+ // errTenancyStale: the map no longer serves the admission's host and
+ // path for the tenancy it was admitted under.
+ errTenancyStale = errors.New("edge: the upgrade's route no longer has the tenancy it was admitted under")
+ // errTunnelBusy: the channel connection has tunnelUpgradeCap upgrades
+ // open.
+ errTunnelBusy = errors.New("edge: the channel has its maximum of open upgrades")
+ // errTunnelNoUpgrade: the channel did not advertise the upgrade
+ // capability when it registered.
+ errTunnelNoUpgrade = errors.New("edge: the channel's box cannot carry upgrades")
+ // errNoAdmission: an upgrade reached the transport without coming
+ // through the upgrade branch.
+ errNoAdmission = errors.New("edge: an upgrade with no admission")
+)
+
+// openUpgrades is the hub's registry of reserved upgrades: by host, for
+// the sweep, and counted per channel connection, for the cap. A count is
+// keyed by the connection itself, so a replaced connection's streams,
+// which fail and release, decrement the old entry, which goes at zero.
+type openUpgrades struct {
+ mu sync.Mutex
+ byHost map[string]map[*upgradeReservation]struct{}
+ perConn map[*tunnelConn]int
+}
+
+// releaser names who released a reservation first. Tests read it;
+// production never does.
+type releaser int
+
+const (
+ relNone releaser = iota // not released
+ relTransport // the transport, on its own error paths
+ relBody // the response body's Close
+ relBackstop // the inbound request's end
+ relSweep // a Reload that no longer serves its tenancy
+)
+
+// upgradeReservation is one upgraded stream's hold on its channel (spec
+// §4.6.2). It is taken by reserveUpgrade and released by release, exactly
+// once, whichever of its releasers comes first.
+type upgradeReservation struct {
+ reg *openUpgrades
+ host string
+ path string
+ ten tenancy
+ tc *tunnelConn
+
+ cancel context.CancelFunc // the stream's context
+ once sync.Once
+ first atomic.Int32 // the releaser that acted
+
+ mu sync.Mutex // guards the fields below against release
+ released bool
+ pipe, body io.Closer
+ stopBackstop func() bool
+}
+
+// attach gives the reservation the stream's pipe and response body, either
+// of which may be nil, for release to close. Attached after the release,
+// they are closed at once.
+func (r *upgradeReservation) attach(pipe, body io.Closer) {
+ r.mu.Lock()
+ if !r.released {
+ r.pipe, r.body = pipe, body
+ r.mu.Unlock()
+ return
+ }
+ r.mu.Unlock()
+ closeAll(pipe, body)
+}
+
+func closeAll(cs ...io.Closer) {
+ for _, c := range cs {
+ if c != nil {
+ c.Close()
+ }
+ }
+}
+
+// release ends the reservation, once: it cancels the stream's context,
+// closes the attached pipe and body, takes the reservation out of the
+// registry, gives its channel's slot back and stops the backstop. Later
+// calls do nothing.
+//
+// The context goes first. x/net's response body Close returns at once only
+// when the stream's context has ended; otherwise it waits for the stream's
+// cleanup, which a stuck tunnel never lets finish.
+func (r *upgradeReservation) release(by releaser) {
+ r.once.Do(func() {
+ r.first.Store(int32(by))
+ r.cancel()
+ r.mu.Lock()
+ r.released = true
+ pipe, body, stop := r.pipe, r.body, r.stopBackstop
+ r.mu.Unlock()
+ closeAll(pipe, body)
+ r.reg.remove(r)
+ if stop != nil {
+ stop()
+ }
+ })
+}
+
+// firstReleaser is the releaser whose call acted, relNone before any.
+func (r *upgradeReservation) firstReleaser() releaser { return releaser(r.first.Load()) }
+
+// remove takes r out of the registry and gives its slot back. It runs
+// once per reservation, from release; the sweep may have taken r out of
+// byHost already.
+func (o *openUpgrades) remove(r *upgradeReservation) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if set := o.byHost[r.host]; set != nil {
+ delete(set, r)
+ if len(set) == 0 {
+ delete(o.byHost, r.host)
+ }
+ }
+ if n := o.perConn[r.tc] - 1; n > 0 {
+ o.perConn[r.tc] = n
+ } else {
+ delete(o.perConn, r.tc)
+ }
+}
+
+// reserveUpgrade takes a reservation for an admitted upgrade on channel
+// connection tc, or refuses it. Under the registry's lock, the current map
+// must still serve a's host and path for a's tenancy (else errTenancyStale)
+// and tc must have fewer than capN upgrades open (else errTunnelBusy).
+// Nothing is held after a refusal.
+//
+// It returns the reservation and the stream's context, which release
+// cancels: the caller runs the stream under it. A backstop on inbound, the
+// request's context, releases the reservation when the request ends,
+// whatever happened to the response.
+func (e *Edge) reserveUpgrade(inbound context.Context, a upgradeAdmission, tc *tunnelConn, capN int) (*upgradeReservation, context.Context, error) {
+ o := &e.open
+ o.mu.Lock()
+ up, ok := e.lookupUpstreamPath(a.Host, a.Path)
+ if !ok || a.Tenancy.Arm == ArmNone || up.tenancy != a.Tenancy {
+ o.mu.Unlock()
+ return nil, nil, errTenancyStale
+ }
+ if o.perConn[tc] >= capN {
+ o.mu.Unlock()
+ return nil, nil, errTunnelBusy
+ }
+ ctx, cancel := context.WithCancel(inbound)
+ r := &upgradeReservation{reg: o, host: a.Host, path: a.Path, ten: a.Tenancy, tc: tc, cancel: cancel}
+ if o.byHost == nil {
+ o.byHost = make(map[string]map[*upgradeReservation]struct{})
+ }
+ if o.perConn == nil {
+ o.perConn = make(map[*tunnelConn]int)
+ }
+ if o.byHost[a.Host] == nil {
+ o.byHost[a.Host] = make(map[*upgradeReservation]struct{})
+ }
+ o.byHost[a.Host][r] = struct{}{}
+ o.perConn[tc]++
+ o.mu.Unlock()
+
+ stop := context.AfterFunc(inbound, func() { r.release(relBackstop) })
+ r.mu.Lock()
+ if r.released {
+ r.mu.Unlock()
+ stop()
+ } else {
+ r.stopBackstop = stop
+ r.mu.Unlock()
+ }
+ return r, ctx, nil
+}
diff --git a/internal/edge/upgrades_test.go b/internal/edge/upgrades_test.go
new file mode 100644
index 000000000..87d93908d
--- /dev/null
+++ b/internal/edge/upgrades_test.go
@@ -0,0 +1,620 @@
+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.
+//
+// Accounts: fwdOwner ("bah") owns fleets home and away; "k3x" is the
+// second account the plan names for the -tunnel row.
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "golang.org/x/net/http2"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+const upHost = "shop.example.com"
+
+// upTenancy is the forward row's tenancy as Reload must record it.
+var upTenancy = tenancy{ArmForward, fwdOwner, "shop", "home", ""}
+
+// upgradeScene is forwardHubAndBox with the forward row for upHost and a
+// local instance row (the zero tenancy) on the hub, and the hub's channel
+// connection for home/box-1.
+func upgradeScene(t *testing.T) (hub *Edge, tc *tunnelConn) {
+ t.Helper()
+ _, hub, _ = forwardHubAndBox(t, []registry.Route{
+ forwardRow(upHost, "home", fwdOwner),
+ {Host: "local.example.com", Kind: "instance", Status: "ready", Socket: "/run/carlos/local.sock", Account: fwdOwner, App: "local"},
+ }, nil, namedHandler("box-1"))
+ tc = hub.tunnels.channel("home/box-1")
+ if tc == nil {
+ t.Fatal("home/box-1 has no channel connection")
+ }
+ return hub, tc
+}
+
+// openCount is the registry's count for tc, and whether it has an entry.
+func openCount(e *Edge, tc *tunnelConn) (int, bool) {
+ e.open.mu.Lock()
+ defer e.open.mu.Unlock()
+ n, ok := e.open.perConn[tc]
+ return n, ok
+}
+
+// heldFor is how many reservations the registry holds for host.
+func heldFor(e *Edge, host string) int {
+ e.open.mu.Lock()
+ defer e.open.mu.Unlock()
+ return len(e.open.byHost[host])
+}
+
+// countingCloser counts its Close calls.
+type countingCloser struct{ n atomic.Int32 }
+
+func (c *countingCloser) Close() error { c.n.Add(1); return nil }
+
+func TestTenancyComesFromReloadsArm(t *testing.T) {
+ const sock = "/run/carlos/shop-home.sock"
+ _, hub, _ := forwardHubAndBox(t, []registry.Route{
+ forwardRow(upHost, "home", fwdOwner),
+ {Host: "t.example.com", Kind: "instance", Status: "ready", Tunnel: "t1", Account: "k3x", App: "blog"},
+ // A fleet-placed instance (ArmFleet) and a platform alias of it.
+ {Host: "src.example.com", Kind: "instance", Status: "ready", Socket: sock,
+ Region: registry.PlacementTarget("home"), Account: fwdOwner, App: "shop"},
+ {Host: "alias.example.com", Kind: "instance", Status: "ready", Socket: sock,
+ Region: registry.PlacementTarget("home"), Account: fwdOwner, App: "shop", Platform: true},
+ {Host: "local.example.com", Kind: "instance", Status: "ready", Socket: "/run/carlos/local.sock",
+ Account: fwdOwner, App: "local"},
+ }, nil, namedHandler("box-1"))
+ // An attached hostname of the forward row (the alias fold).
+ if err := hub.reg.UpsertAlias(registry.RouteAlias{Alias: "www.example.com", Host: upHost, Account: fwdOwner, App: "shop"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ fleetTen := tenancy{ArmFleet, fwdOwner, "shop", "home", ""}
+ for host, want := range map[string]tenancy{
+ upHost: upTenancy,
+ "www.example.com": upTenancy,
+ "t.example.com": {ArmTunnel, "k3x", "blog", "", "t1"},
+ "src.example.com": fleetTen,
+ "alias.example.com": fleetTen,
+ "local.example.com": {},
+ } {
+ up, ok := hub.lookupUpstreamPath(host, "/cable")
+ if !ok {
+ t.Errorf("%s: no entry in the hub's map", host)
+ continue
+ }
+ if up.tenancy != want {
+ t.Errorf("%s: tenancy %+v, want %+v", host, up.tenancy, want)
+ }
+ }
+ if up := hub.current()["alias.example.com"]; !up.platformAlias {
+ t.Error("alias.example.com was not folded as a platform alias")
+ }
+ if up := hub.current()["www.example.com"]; !up.alias || up.platformAlias {
+ t.Error("www.example.com was not folded as an attached hostname")
+ }
+}
+
+func TestReserveUpgradeChecksTenancyAndCap(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ hub.tunnels.upgradeCap = 2
+ adm := upgradeAdmission{Host: upHost, Path: "/cable", Tenancy: upTenancy}
+ ctx := context.Background()
+
+ var held []*upgradeReservation
+ for i := 1; i <= 2; i++ {
+ r, sctx, err := hub.reserveUpgrade(ctx, adm, tc, hub.tunnels.upgradeCap)
+ if err != nil {
+ t.Fatalf("reservation %d: %v, want admitted under the cap of 2", i, err)
+ }
+ if sctx == nil || sctx.Err() != nil {
+ t.Fatalf("reservation %d: stream context %v, want a live one", i, sctx)
+ }
+ held = append(held, r)
+ }
+ if _, _, err := hub.reserveUpgrade(ctx, adm, tc, hub.tunnels.upgradeCap); !errors.Is(err, errTunnelBusy) {
+ t.Fatalf("reservation 3: %v, want errTunnelBusy", err)
+ }
+ if n, _ := openCount(hub, tc); n != 2 {
+ t.Fatalf("count after the refusal = %d, want 2", n)
+ }
+ held[0].release(relBody)
+ r, _, err := hub.reserveUpgrade(ctx, adm, tc, hub.tunnels.upgradeCap)
+ if err != nil {
+ t.Fatalf("after one release: %v, want admitted", err)
+ }
+ held = append(held[1:], r)
+
+ // Stale: the admission names fleet away; the host is served for home.
+ stale := adm
+ stale.Tenancy.Fleet = "away"
+ if _, _, err := hub.reserveUpgrade(ctx, stale, tc, 10); !errors.Is(err, errTenancyStale) {
+ t.Fatalf("stale admission: %v, want errTenancyStale", err)
+ }
+ // A host the map does not serve at all.
+ gone := adm
+ gone.Host = "gone.example.com"
+ if _, _, err := hub.reserveUpgrade(ctx, gone, tc, 10); !errors.Is(err, errTenancyStale) {
+ t.Fatalf("unserved host: %v, want errTenancyStale", err)
+ }
+ // A host served with no tunnel (the zero tenancy) is never reserved,
+ // even by an admission that names that zero tenancy.
+ if _, ok := hub.lookupUpstreamPath("local.example.com", "/cable"); !ok {
+ t.Fatal("local.example.com is not served")
+ }
+ if _, _, err := hub.reserveUpgrade(ctx, upgradeAdmission{Host: "local.example.com", Path: "/cable"}, tc, 10); !errors.Is(err, errTenancyStale) {
+ t.Fatalf("zero tenancy: %v, want errTenancyStale", err)
+ }
+ if n, _ := openCount(hub, tc); n != 2 || heldFor(hub, upHost) != 2 {
+ t.Fatalf("count %d, held %d after the stale refusals, want 2 and 2", n, heldFor(hub, upHost))
+ }
+ // Control on the same fixture and the same cap: the current tenancy is
+ // admitted.
+ r, _, err = hub.reserveUpgrade(ctx, adm, tc, 10)
+ if err != nil {
+ t.Fatalf("control: %v, want admitted", err)
+ }
+ held = append(held, r)
+ for _, r := range held {
+ r.release(relBody)
+ }
+ if n, ok := openCount(hub, tc); ok || n != 0 || heldFor(hub, upHost) != 0 {
+ t.Fatalf("after releasing all: count %d (entry %v), held %d; want no entry and 0", n, ok, heldFor(hub, upHost))
+ }
+}
+
+func TestReleaseIsExactlyOnce(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ adm := upgradeAdmission{Host: upHost, Path: "/cable", Tenancy: upTenancy}
+ inbound, cancelInbound := context.WithCancel(context.Background())
+ defer cancelInbound()
+ r, sctx, err := hub.reserveUpgrade(inbound, adm, tc, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A second reservation on the same connection stays open, so a double
+ // decrement shows as a count of 0 rather than hiding at the floor.
+ other, _, err := hub.reserveUpgrade(context.Background(), adm, tc, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer other.release(relBody)
+ pipe, body := &countingCloser{}, &countingCloser{}
+ r.attach(pipe, body)
+ if got := r.firstReleaser(); got != relNone {
+ t.Fatalf("firstReleaser before any release = %v, want relNone", got)
+ }
+
+ r.release(relBody)
+ r.release(relSweep)
+ cancelInbound() // the backstop
+ r.release(relTransport)
+
+ if sctx.Err() == nil {
+ t.Error("the stream context is still live after release")
+ }
+ if n, _ := openCount(hub, tc); n != 1 {
+ t.Fatalf("count = %d, want 1 (the other reservation): one release decrements once", n)
+ }
+ if got := heldFor(hub, upHost); got != 1 {
+ t.Fatalf("held for %s = %d, want 1", upHost, got)
+ }
+ if got := r.firstReleaser(); got != relBody {
+ t.Fatalf("firstReleaser = %v, want relBody", got)
+ }
+ if p, b := pipe.n.Load(), body.n.Load(); p != 1 || b != 1 {
+ t.Fatalf("pipe closed %d times, body %d, want 1 and 1", p, b)
+ }
+ // Attached after release: closed at once, still once each.
+ late1, late2 := &countingCloser{}, &countingCloser{}
+ r.attach(late1, late2)
+ if late1.n.Load() != 1 || late2.n.Load() != 1 {
+ t.Fatalf("attach after release closed %d and %d, want 1 and 1", late1.n.Load(), late2.n.Load())
+ }
+}
+
+func TestBackstopReleasesOnRequestEnd(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ adm := upgradeAdmission{Host: upHost, Path: "/cable", Tenancy: upTenancy}
+ inbound, cancelInbound := context.WithCancel(context.Background())
+ r, sctx, err := hub.reserveUpgrade(inbound, adm, tc, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := &countingCloser{}
+ r.attach(nil, body)
+ if n, _ := openCount(hub, tc); n != 1 {
+ t.Fatalf("count = %d, want 1", n)
+ }
+ cancelInbound()
+ deadline := time.Now().Add(time.Second)
+ for {
+ n, ok := openCount(hub, tc)
+ if !ok && n == 0 && r.firstReleaser() == relBackstop {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("1 s after the request ended: count %d (entry %v), firstReleaser %v; want released by the backstop", n, ok, r.firstReleaser())
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if sctx.Err() == nil || body.n.Load() != 1 || heldFor(hub, upHost) != 0 {
+ t.Fatalf("after the backstop: stream ctx %v, body closed %d, held %d", sctx.Err(), body.n.Load(), heldFor(hub, upHost))
+ }
+}
+
+// stuckConn is a box's end of the tunnel that can stop reading: once stuck
+// is closed, the read in flight takes one more write and never returns, so
+// every later hub write blocks on the unbuffered pipe.
+type stuckConn struct {
+ net.Conn
+ stuck, absorbed, unstick chan struct{}
+ once sync.Once
+}
+
+func (c *stuckConn) Read(p []byte) (int, error) {
+ n, err := c.Conn.Read(p)
+ select {
+ case <-c.stuck:
+ c.once.Do(func() { close(c.absorbed) })
+ <-c.unstick
+ return 0, net.ErrClosed
+ default:
+ }
+ return n, err
+}
+
+// stuckPair serves handler (through Mark, as Loop does) on a tunnel whose
+// box end can be made to stop reading.
+func stuckPair(t *testing.T, handler http.Handler) (*http2.ClientConn, *stuckConn) {
+ t.Helper()
+ boxEnd, hubEnd := net.Pipe()
+ sc := &stuckConn{Conn: boxEnd, stuck: make(chan struct{}), absorbed: make(chan struct{}), unstick: make(chan struct{})}
+ go tunnelclient.ServeWith(sc, tunnelclient.Mark(handler), tunnelclient.DefaultLimits)
+ cc, err := (&http2.Transport{}).NewClientConn(hubEnd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ select {
+ case <-sc.unstick:
+ default:
+ close(sc.unstick)
+ }
+ hubEnd.Close()
+ boxEnd.Close()
+ cc.Close()
+ })
+ return cc, sc
+}
+
+func wsRequest() *http.Request {
+ req, _ := http.NewRequest("GET", "https://"+upHost+"/cable", nil)
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "websocket")
+ return req
+}
+
+// Task 2's carry: release cancels the stream context before it closes the
+// body, because x/net's body Close returns at once only after that context
+// has ended; otherwise it waits for a stream cleanup that a stuck tunnel
+// never lets finish.
+func TestReleaseOnAStuckTunnelDoesNotBlock(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ cc, sc := stuckPair(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, brw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ brw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n")
+ brw.Flush()
+ io.Copy(io.Discard, conn)
+ }))
+ r, sctx, err := hub.reserveUpgrade(context.Background(), upgradeAdmission{Host: upHost, Path: "/cable", Tenancy: upTenancy}, tc, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := tunnelclient.RoundTripUpgrade(sctx, cc, wsRequest())
+ if err != nil || resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("RoundTripUpgrade = %v, %v; want the 101", resp, err)
+ }
+ up := resp.Body.(*tunnelclient.UpgradeConn)
+ r.attach(nil, up)
+
+ // Wedge the tunnel: the box stops reading; the write below is the last
+ // one it takes.
+ close(sc.stuck)
+ go up.Write([]byte("x"))
+ select {
+ case <-sc.absorbed:
+ case <-time.After(2 * time.Second):
+ t.Fatal("the box never took the last write")
+ }
+
+ done := make(chan struct{})
+ go func() {
+ r.release(relBody)
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("release blocked on a stuck tunnel for 2 s")
+ }
+ if n, ok := openCount(hub, tc); ok || n != 0 {
+ t.Fatalf("count %d (entry %v) after release, want no entry", n, ok)
+ }
+}
+
+// Task 2's carry: the reservation's context, passed to RoundTripUpgrade,
+// reaches the in-band read: a release while the box has hijacked and not
+// answered ends the handshake and resets the stream.
+func TestReleaseEndsTheHandshakeRead(t *testing.T) {
+ hub, tc := upgradeScene(t)
+ hijacked := make(chan struct{})
+ boxErr := make(chan error, 1)
+ cc, _ := stuckPair(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, _, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ close(hijacked)
+ _, err = conn.Read(make([]byte, 1))
+ boxErr <- err
+ }))
+ r, sctx, err := hub.reserveUpgrade(context.Background(), upgradeAdmission{Host: upHost, Path: "/cable", Tenancy: upTenancy}, tc, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ type result struct {
+ resp *http.Response
+ err error
+ }
+ got := make(chan result, 1)
+ go func() {
+ resp, err := tunnelclient.RoundTripUpgrade(sctx, cc, wsRequest())
+ got <- result{resp, err}
+ }()
+ select {
+ case <-hijacked:
+ case <-time.After(2 * time.Second):
+ t.Fatal("the box never hijacked")
+ }
+ r.release(relSweep)
+ select {
+ case res := <-got:
+ if res.err == nil {
+ t.Fatalf("RoundTripUpgrade = %v, nil; want an error after release", res.resp.Status)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("RoundTripUpgrade did not return within 1 s of release")
+ }
+ select {
+ case err := <-boxErr:
+ if err == nil || errors.Is(err, io.EOF) {
+ t.Fatalf("box Read = %v, want the stream's reset", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("the box's Read did not fail within 1 s: the stream was not reset")
+ }
+}
+
+func TestRegistrationRecordsCaps(t *testing.T) {
+ hubURL, hub, _ := forwardHubAndBox(t, nil, nil, namedHandler("box-1"))
+ // The real Loop advertises the capability.
+ if tc := hub.tunnels.channel("home/box-1"); tc == nil || tc.caps != tunnelclient.CapUpgrade {
+ t.Fatalf("home/box-1 caps = %+v, want %q", tc, tunnelclient.CapUpgrade)
+ }
+ // A registration written by hand, without the header (an old box).
+ 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("t1", fwdT1Tok)
+ 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)
+ }
+ if br.Buffered() != 0 {
+ t.Fatalf("%d bytes after the 101", br.Buffered())
+ }
+ go tunnelclient.ServeWith(conn, namedHandler("old"), tunnelclient.DefaultLimits)
+ waitForTunnelState(t, hub.tunnels, "t1", "connected", e2eReconnectBound)
+ tc := hub.tunnels.channel("t1")
+ if tc == nil || tc.caps != "" {
+ t.Fatalf("t1 caps = %+v, want \"\"", tc)
+ }
+}
+
+// boxView is what the box's handler saw of one request.
+type boxView struct {
+ method, upgrade string
+ isUpgrade bool
+ markers []string
+ keys []string
+}
+
+type viewRecorder struct {
+ mu sync.Mutex
+ seen []boxView
+}
+
+func (v *viewRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ var markers, keys []string
+ for k := range r.Header {
+ keys = append(keys, k)
+ if strings.EqualFold(k, tunnelclient.UpgradeHeader) || strings.EqualFold(k, tunnelclient.UpgradedHeader) {
+ markers = append(markers, k)
+ }
+ }
+ slices.Sort(keys)
+ v.mu.Lock()
+ v.seen = append(v.seen, boxView{r.Method, r.Header.Get("Upgrade"), isUpgradeRequest(r), markers, keys})
+ v.mu.Unlock()
+ io.WriteString(w, "ok")
+}
+
+func (v *viewRecorder) last(t *testing.T) boxView {
+ t.Helper()
+ v.mu.Lock()
+ defer v.mu.Unlock()
+ if len(v.seen) == 0 {
+ t.Fatal("the box saw no request")
+ }
+ return v.seen[len(v.seen)-1]
+}
+
+func TestTheMarkersAreScrubbedAtTheHub(t *testing.T) {
+ rec := &viewRecorder{}
+ local := &viewRecorder{}
+ localAddr := startPolBackend(t, local)
+ hubURL, hub, _ := forwardHubAndBox(t, []registry.Route{
+ forwardRow(upHost, "home", fwdOwner),
+ {Host: "t.example.com", Kind: "instance", Status: "ready", Tunnel: "t1", Account: fwdOwner, App: "shop"},
+ {Host: "local.example.com", Kind: "instance", Status: "ready", Addr: localAddr, Account: fwdOwner, App: "local"},
+ }, nil, rec)
+ stopT1 := startFakeRemoteHost(t, hubURL, "t1", fwdT1Tok, rec)
+ t.Cleanup(stopT1)
+ waitForTunnelState(t, hub.tunnels, "t1", "connected", e2eReconnectBound)
+
+ get := func(host string, marked bool) {
+ t.Helper()
+ req, err := http.NewRequest("GET", hubURL+"/cable", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = host
+ if marked {
+ req.Header.Set(tunnelclient.UpgradeHeader, "websocket")
+ req.Header.Set(tunnelclient.UpgradedHeader, "1")
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK || string(b) != "ok" {
+ t.Fatalf("GET %s (marked %v) = %d %q, want the box's 200", host, marked, resp.StatusCode, b)
+ }
+ }
+ for _, host := range []string{upHost, "t.example.com"} {
+ get(host, false)
+ control := rec.last(t)
+ get(host, true)
+ got := rec.last(t)
+ if len(got.markers) != 0 || got.isUpgrade || got.upgrade != "" || got.method != "GET" {
+ t.Errorf("%s: the box saw %+v, want a plain GET with neither marker", host, got)
+ }
+ if !slices.Equal(got.keys, control.keys) || got.method != control.method || got.isUpgrade != control.isUpgrade {
+ t.Errorf("%s: marked request reached the box as %+v, the control as %+v", host, got, control)
+ }
+ }
+ // The edge's own delete, on an arm with no tunnel Rewrite.
+ get("local.example.com", false)
+ control := local.last(t)
+ get("local.example.com", true)
+ got := local.last(t)
+ if slices.Contains(got.markers, tunnelclient.UpgradeHeader) {
+ t.Errorf("local.example.com: the app saw %s, want it deleted by the edge", tunnelclient.UpgradeHeader)
+ }
+ if got.isUpgrade || control.isUpgrade {
+ t.Errorf("local.example.com: an upgrade reached the app: %+v / %+v", got, control)
+ }
+}
+
+// The tunnel proxies' own Rewrite scrubs both markers, whatever reached
+// them: not every caller of a route's proxy passes Edge.ServeHTTP's delete
+// first. Control: another header goes through.
+func TestTunnelProxiesScrubTheMarkersInRewrite(t *testing.T) {
+ hub := NewTunnelHub("tunnel.example.com", nil)
+ for name, p := range map[string]*httputil.ReverseProxy{
+ "fleetProxy": fleetProxy("home", "box-1", hub),
+ "tunnelProxy": tunnelProxy("t1", hub),
+ } {
+ in := httptest.NewRequest("GET", "https://"+upHost+"/cable", nil)
+ in.Header.Set(tunnelclient.UpgradeHeader, "websocket")
+ in.Header.Set(tunnelclient.UpgradedHeader, "1")
+ in.Header.Set("X-Other", "kept")
+ pr := &httputil.ProxyRequest{In: in, Out: in.Clone(in.Context())}
+ p.Rewrite(pr)
+ for _, h := range []string{tunnelclient.UpgradeHeader, tunnelclient.UpgradedHeader} {
+ if v, ok := pr.Out.Header[h]; ok {
+ t.Errorf("%s: Rewrite left %s: %q", name, h, v)
+ }
+ }
+ if pr.Out.Header.Get("X-Other") != "kept" {
+ t.Errorf("%s: Rewrite dropped an ordinary header", name)
+ }
+ }
+}
+
+func TestLimitsInvariant(t *testing.T) {
+ l := tunnelclient.DefaultLimits
+ if !(tunnelUpgradeCap < int(l.MaxStreams)) {
+ t.Errorf("tunnelUpgradeCap %d >= MaxStreams %d", tunnelUpgradeCap, l.MaxStreams)
+ }
+ if need := int64(tunnelUpgradeCap)*int64(l.StreamWindow) + tunnelclient.PlainHeadroom; int64(l.ConnWindow) < need {
+ t.Errorf("ConnWindow %d < cap x StreamWindow + PlainHeadroom = %d", l.ConnWindow, need)
+ }
+ if tunnelUpgradeCap != 128 {
+ t.Errorf("tunnelUpgradeCap = %d, want 128 (spec §4.8)", tunnelUpgradeCap)
+ }
+ if h := NewTunnelHub("tunnel.example.com", nil); h.upgradeCap != tunnelUpgradeCap {
+ 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)
+ }
+}
diff --git a/internal/tunnelclient/upgrade.go b/internal/tunnelclient/upgrade.go
index 56d79f2aa..2314cb929 100644
--- a/internal/tunnelclient/upgrade.go
+++ b/internal/tunnelclient/upgrade.go
@@ -402,8 +402,9 @@ var hookHandshake func()
// Upgrade: <tok>) to the box on a new stream of cc. The stream's request
// body stays open as the hub's send side.
//
-// If the box answers without UpgradedHeader (the gate, a 404, a 502: any
-// refusal), that response comes back unchanged and its body is the stream.
+// If the box answers without UpgradedHeader on a 200 (the gate, a 404, a
+// 502: any refusal), that response comes back unchanged and its body is
+// the stream.
// If it hijacked, the app's in-band response must be a 101 for the same
// token, read within upgradeHandshakeTimeout and MaxUpgradeHeaderBytes;
// it comes back with Body an *UpgradeConn. Anything else is an error
@@ -439,9 +440,12 @@ func RoundTripUpgrade(ctx context.Context, cc *http2.ClientConn, req *http.Reque
pw.CloseWithError(err)
return nil, err
}
- if resp.Header.Get(UpgradedHeader) != "1" {
+ if resp.StatusCode != http.StatusOK || resp.Header.Get(UpgradedHeader) != "1" {
// The box answered without upgrading: nothing more goes to it.
// The request body is complete, so x/net watches ctx itself.
+ // The marker counts only on the shim's 200: a box that marks any
+ // other status is not keeping the shim's contract, and its answer
+ // is a refusal like any other.
stopCtx()
pw.Close()
return resp, nil
diff --git a/internal/tunnelclient/upgrade_hub_test.go b/internal/tunnelclient/upgrade_hub_test.go
index 74fb1733e..b5caef948 100644
--- a/internal/tunnelclient/upgrade_hub_test.go
+++ b/internal/tunnelclient/upgrade_hub_test.go
@@ -224,6 +224,55 @@ func TestRoundTripUpgradePassesRefusalsThrough(t *testing.T) {
}
}
+// The marker counts only on a 200 (#471 Task 2 review, carried to Task 3):
+// a box that marks any other status is not running the shim's contract, and
+// its answer goes through as an ordinary refusal. The handler is raw, not
+// Mark's, since the shim never marks anything but its hijack's 200. The
+// control on the same pair is a raw marked 200 with an in-band 101, which
+// is honoured.
+func TestRoundTripUpgradeHonoursTheMarkerOnlyOnA200(t *testing.T) {
+ cc := h2Pair(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set(UpgradedHeader, "1")
+ if r.URL.Path == "/refused" {
+ w.Header().Set("Location", "/.carlos/gate")
+ w.WriteHeader(http.StatusFound)
+ io.WriteString(w, "gate body")
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ io.WriteString(w, switching)
+ w.(http.Flusher).Flush()
+ io.Copy(io.Discard, r.Body)
+ }))
+
+ req := upgradeRequest("websocket")
+ req.URL.Path = "/refused"
+ resp, err := RoundTripUpgrade(context.Background(), cc, req)
+ if err != nil {
+ t.Fatalf("marked 302: %v, want the 302 as a refusal", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusFound || resp.Header.Get("Location") != "/.carlos/gate" {
+ t.Fatalf("marked 302: got %d %v, want the box's 302", resp.StatusCode, resp.Header)
+ }
+ if _, ok := resp.Body.(*UpgradeConn); ok {
+ t.Fatal("a marked 302's body is an UpgradeConn")
+ }
+ if b, err := io.ReadAll(resp.Body); err != nil || string(b) != "gate body" {
+ t.Fatalf("marked 302: body = %q, %v", b, err)
+ }
+
+ // Control: a raw marked 200 is the hijack's answer.
+ resp, err = RoundTripUpgrade(context.Background(), cc, upgradeRequest("websocket"))
+ if err != nil || resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("control: %v, %v; want the in-band 101", resp, err)
+ }
+ if _, ok := resp.Body.(*UpgradeConn); !ok {
+ t.Fatalf("control: body %T, want an UpgradeConn", resp.Body)
+ }
+ resp.Body.Close()
+}
+
// boxReadErr is what the box handler's first conn Read returned.
func boxReadErr(conn net.Conn, out chan<- error) {
_, err := conn.Read(make([]byte, 1))