carlos / platform Public

edge: the production-wired witness for tunnel WebSockets (#471 Task 6)

TestTunnelWebSocketEndToEnd drives a real hub (New, EnableTunnels,
EnableStatic, Reload, forward rows through PutForward) served over TLS
on a tracking listener, the real tunnelclient.Loop dialing it over https
as home/box-1 and t1, a real box Edge on a unix-socket instance row
behind the gate, and an Action Cable shaped x/net/websocket app. Spec
§8.2 cases 1-8, 10-12, 14-16 run as sub-tests on the one scene; case 9
(hub restart) is Task 7's.

The Loop verifies the hub's certificate against the system pool, so the
witness re-runs itself as a child with SSL_CERT_FILE naming a fixture CA
(runTrustedChild, trusted_child_test.go, linux only). No production
trust seam. TestTrustedChildIsNeeded: a child trusting an unrelated CA
never connects and logs "x509: certificate signed by unknown authority".

Case 2b puts the gate on the hub's -tunnel row: the hub 404s a login
POST to an ungated non-forward row, so a box-only gate cannot be logged
into through the hub (checked).

19 production mutations, each fails its case (task-6-report.md),
including the brief's two: upgradeCap 0 (case 2 gets 503) and a no-op
sweepUpgrades (case 15 times out). -race clean. Census card unchanged
(seal 1379d066...5e7).

Carry-in from the Task 5 review: TestStaleAdmissionIsRefused unblocks
its paused handshake through a deferred sync.Once, so a failed Reload
no longer leaves the handler blocked on resume.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev eef20b79cca9bc4dc59705ea9e5df7004820d546 parent 10151ad
3 files changed, +2,095 −1
  • internal/edge/trusted_child_test.go +191 −0
  • internal/edge/tunnel_upgrade_test.go +7 −1
  • internal/edge/tunnel_ws_e2e_test.go +1,897 −0

Intent

Human

<task-notification> <task-id>brp7shea3</task-id> <tool-use-id>toolu_015L9UWxR8UDVWuSZx478wf8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/brp7shea3.output</output-file> <status>completed</status> <summary>Background command "Run Astra review of Plan 6 Task 6" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a26e7645db516d417</task-id> <tool-use-id>toolu_01Q4NEbHcer78uaKTSv3QMtF</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. Census seal `b611b6ff…` is unchanged, with no re-proposal needed, because only a test file changed. **Commit:** `37a06e98` "instance-control: stage the tty exe test under a tenant account (rootfs plan 6)" **Tests:** `TestTTYExeUsesItsOwnSources` passes using `domains.Sqid(7)` and app `shop`, and the instancectl tests for cmd, tty, sweep, stop, reset, rootfs and the client pass; vet and gofmt are clean and the root-read census tests still pass.</result> <usage><subagent_tokens>317481</subagent_tokens><tool_uses>5</tool_uses><duration_ms>54336</duration_ms></usage> </task-notification>

Attributed to this commit: 8.90 g CO₂e (939,629 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/internal/edge/trusted_child_test.go b/internal/edge/trusted_child_test.go
new file mode 100644
index 000000000..05c84c77f
--- /dev/null
+++ b/internal/edge/trusted_child_test.go
@@ -0,0 +1,191 @@
+//go:build linux
+
+package edge
+
+// The trusted child (#471 plan P1-1). The witnesses run the real
+// tunnelclient.Loop over real TLS, and Dial verifies the hub's certificate
+// against the system pool: it builds its own tls.Config with no RootCAs
+// (internal/tunnelclient/tunnelclient.go). There is no production seam to
+// trust a test CA, and none is added. Instead the test re-runs its own
+// binary as a child process with SSL_CERT_FILE naming a fixture CA. Go's
+// Linux pool reads that variable when it first loads, and the variable is
+// set before the child starts, so before anything in it loads the roots.
+// Verification stays on: TestTrustedChildIsNeeded shows a child trusting
+// an unrelated CA never connects.
+//
+// Linux only: macOS and Windows do not read SSL_CERT_FILE. CI runs Linux.
+
+import (
+ "bufio"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/pem"
+ "flag"
+ "math/big"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+const (
+ trustedChildEnv = "CARLOS_TEST_TRUSTED_CHILD"
+ trustedCertEnv = "CARLOS_TEST_TRUSTED_CERT"
+ trustedKeyEnv = "CARLOS_TEST_TRUSTED_KEY"
+)
+
+// tlsFixture is a fresh CA and a leaf it signed for 127.0.0.1, ::1,
+// example.com and *.example.com. ServerTLS serves the leaf; it is set only
+// in the child.
+type tlsFixture struct {
+ CAFile, CertFile, KeyFile string
+ ServerTLS *tls.Config
+}
+
+// newTLSFixture writes a fresh ECDSA CA (ca.pem) and a leaf it signed
+// (leaf.pem, leaf-key.pem) into dir.
+func newTLSFixture(t *testing.T, dir string) tlsFixture {
+ t.Helper()
+ caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ caTmpl := &x509.Certificate{
+ SerialNumber: big.NewInt(1),
+ Subject: pkix.Name{CommonName: "carlos test CA"},
+ NotBefore: now.Add(-time.Hour),
+ NotAfter: now.Add(24 * time.Hour),
+ IsCA: true,
+ BasicConstraintsValid: true,
+ KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
+ }
+ caDER, err := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ca, err := x509.ParseCertificate(caDER)
+ if err != nil {
+ t.Fatal(err)
+ }
+ leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ leafTmpl := &x509.Certificate{
+ SerialNumber: big.NewInt(2),
+ Subject: pkix.Name{CommonName: "example.com"},
+ NotBefore: now.Add(-time.Hour),
+ NotAfter: now.Add(24 * time.Hour),
+ KeyUsage: x509.KeyUsageDigitalSignature,
+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.IPv6loopback},
+ DNSNames: []string{"example.com", "*.example.com"},
+ }
+ leafDER, err := x509.CreateCertificate(rand.Reader, leafTmpl, ca, &leafKey.PublicKey, caKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ keyDER, err := x509.MarshalECPrivateKey(leafKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fx := tlsFixture{
+ CAFile: filepath.Join(dir, "ca.pem"),
+ CertFile: filepath.Join(dir, "leaf.pem"),
+ KeyFile: filepath.Join(dir, "leaf-key.pem"),
+ }
+ for path, block := range map[string]*pem.Block{
+ fx.CAFile: {Type: "CERTIFICATE", Bytes: caDER},
+ fx.CertFile: {Type: "CERTIFICATE", Bytes: leafDER},
+ fx.KeyFile: {Type: "EC PRIVATE KEY", Bytes: keyDER},
+ } {
+ if err := os.WriteFile(path, pem.EncodeToMemory(block), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return fx
+}
+
+// runTrustedChild is the first statement of every test that runs the real
+// Loop over TLS: `child, fx := runTrustedChild(t); if !child { return }`.
+//
+// In the parent (CARLOS_TEST_TRUSTED_CHILD unset) it writes a fixture,
+// runs this test again in a child process whose SSL_CERT_FILE is the
+// fixture's CA and whose SSL_CERT_DIR is empty, streams the child's output
+// into t.Log, fails the test if the child fails, and returns false. In the
+// child it returns true and the fixture, whose ServerTLS the hub serves.
+func runTrustedChild(t *testing.T) (child bool, fx tlsFixture) {
+ t.Helper()
+ return runChild(t, false)
+}
+
+// runChild is runTrustedChild; with wrongCA the child trusts a second,
+// unrelated CA instead of the one that signed the leaf.
+func runChild(t *testing.T, wrongCA bool) (bool, tlsFixture) {
+ t.Helper()
+ if os.Getenv(trustedChildEnv) == "1" {
+ cert, err := tls.LoadX509KeyPair(os.Getenv(trustedCertEnv), os.Getenv(trustedKeyEnv))
+ if err != nil {
+ t.Fatalf("trusted child: the leaf: %v", err)
+ }
+ return true, tlsFixture{
+ CertFile: os.Getenv(trustedCertEnv),
+ KeyFile: os.Getenv(trustedKeyEnv),
+ ServerTLS: &tls.Config{Certificates: []tls.Certificate{cert}},
+ }
+ }
+ fx := newTLSFixture(t, t.TempDir())
+ trust := fx.CAFile
+ if wrongCA {
+ trust = newTLSFixture(t, t.TempDir()).CAFile
+ }
+ cmd := exec.Command(os.Args[0], childArgs(t)...)
+ cmd.Env = append(os.Environ(),
+ "SSL_CERT_FILE="+trust,
+ "SSL_CERT_DIR="+t.TempDir(),
+ trustedChildEnv+"=1",
+ trustedCertEnv+"="+fx.CertFile,
+ trustedKeyEnv+"="+fx.KeyFile,
+ )
+ out, err := cmd.StdoutPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd.Stderr = cmd.Stdout
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ sc := bufio.NewScanner(out)
+ sc.Buffer(make([]byte, 64<<10), 1<<20)
+ for sc.Scan() {
+ t.Log(sc.Text())
+ }
+ if err := cmd.Wait(); err != nil {
+ t.Fatalf("the trusted child failed: %v", err)
+ }
+ return false, fx
+}
+
+// childArgs runs this test, and the sub-tests the parent's -test.run
+// selects under it, once and verbosely.
+func childArgs(t *testing.T) []string {
+ pattern := "^" + t.Name() + "$"
+ if f := flag.Lookup("test.run"); f != nil {
+ if _, sub, ok := strings.Cut(f.Value.String(), "/"); ok && sub != "" {
+ pattern += "/" + sub
+ }
+ }
+ args := []string{"-test.run", pattern, "-test.count=1", "-test.v"}
+ if testing.Short() {
+ args = append(args, "-test.short")
+ }
+ return args
+}
diff --git a/internal/edge/tunnel_upgrade_test.go b/internal/edge/tunnel_upgrade_test.go
index 143ab861d..e741595a5 100644
--- a/internal/edge/tunnel_upgrade_test.go
+++ b/internal/edge/tunnel_upgrade_test.go
@@ -449,6 +449,12 @@ func TestStaleAdmissionIsRefused(t *testing.T) {
sink := &memErrSink{}
hub.EnableErrors(sink)
paused, resume := make(chan struct{}), make(chan struct{})
+ // unblock lets the paused handshake go, once: below, and on
+ // every early exit (a failed Reload), so its handler never
+ // stays blocked on resume after the test returns.
+ var unblockOnce sync.Once
+ unblock := func() { unblockOnce.Do(func() { close(resume) }) }
+ defer unblock()
var once sync.Once
hub.open.beforeReserve = func() {
once.Do(func() {
@@ -478,7 +484,7 @@ func TestStaleAdmissionIsRefused(t *testing.T) {
if err := hub.Reload(); err != nil {
t.Fatal(err)
}
- close(resume)
+ unblock()
var a answer
select {
case a = <-got:
diff --git a/internal/edge/tunnel_ws_e2e_test.go b/internal/edge/tunnel_ws_e2e_test.go
new file mode 100644
index 000000000..89ce1f350
--- /dev/null
+++ b/internal/edge/tunnel_ws_e2e_test.go
@@ -0,0 +1,1897 @@
+//go:build linux
+
+package edge
+
+// The production-wired witness for tunnel WebSockets (#471 spec §8.2,
+// plan Task 6). One scene, built from production parts only:
+//
+// - the hub: New + EnableTunnels + EnableStatic + Reload on a registry
+// holding fleets home and away (owner fwdOwner) with active boxes
+// home/box-1 and away/box-2, its forward rows minted through
+// PutForward, served by an http.Server on a TLS listener
+// (httptest.NewUnstartedServer + StartTLS) over a listener that keeps
+// every accepted connection;
+// - the box: New on a second registry whose instance rows point at a
+// unix socket, the shop's row behind the password gate, served by the
+// real tunnelclient.Loop dialing the hub over https as home/box-1 (and
+// as the static channel t1 for the -tunnel arm);
+// - the app: an x/net/websocket server on that socket, shaped like Action
+// Cable (subprotocol actioncable-v1-json only, same-origin check on
+// X-Forwarded-Proto and Host, welcome, a 200 ms ping, subscribe and
+// confirm, broadcasts, echoes);
+// - the client: x/net/websocket and raw handshakes over TLS to the hub,
+// with the public name as SNI and Host.
+//
+// The Loop verifies the hub's certificate against the system pool, so the
+// test runs in a trusted child (trusted_child_test.go).
+//
+// The test seams it touches are the ones earlier tasks added, nil in
+// production: openUpgrades.afterInsert (to see each reservation and so
+// which releaser acted first). Case 12 also replaces one live proxy's
+// ModifyResponse and wraps its ErrorHandler to look from inside it, and
+// serves the same hub Edge from a second http.Server behind a wrapping
+// writer; no production seam is added.
+
+import (
+ "bufio"
+ "context"
+ "crypto/rand"
+ "crypto/sha1"
+ "crypto/tls"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ mrand "math/rand/v2"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "golang.org/x/crypto/bcrypt"
+ "golang.org/x/net/websocket"
+
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/ratelimit"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+const (
+ wsHost = "shop.example.com" // forward row on home, gated on the box
+ wsTunnelHost = "t.example.com" // the hub's -tunnel row, channel t1
+ wsLimitedHost = "limited.example.com" // forward row with the hub's burst 2
+ wsRawHost = "raw.example.com" // forward row the box answers by hand
+ wsOldHost = "old.example.com" // forward row on away, for the old box
+ wsOtherHost = "other.example.com" // a host case 16 changes
+
+ cableProtocol = "actioncable-v1-json"
+ cableChannel = `{"channel":"TestChannel"}`
+
+ wsWideRate = `{"rate":1,"burst":100000}` // never in the way
+ wsLimitedRate = `{"rate":1,"burst":2}` // the hub's: two, then 429
+ wsBoxRate = `{"rate":1,"burst":1}` // the box's own row, never judged
+
+ wsBox1 = "home/box-1"
+ wsBox2 = "away/box-2"
+)
+
+// errModifyFailed is what case 12's replaced ModifyResponse returns.
+var errModifyFailed = errors.New("test: ModifyResponse refused the 101")
+
+// ---- the app ---------------------------------------------------------------
+
+// seenReq is one request as the app saw it.
+type seenReq struct {
+ Host, Method, Path string
+ Header http.Header
+}
+
+// cableApp is the WebSocket app behind the box, Action Cable shaped.
+type cableApp struct {
+ mu sync.Mutex
+ seen []seenReq // every request that reached the app, in order
+ conns map[*appConn]struct{}
+ opened chan *appConn
+ srv *websocket.Server
+}
+
+// appConn is the app's end of one accepted socket.
+type appConn struct {
+ host string
+ hdr http.Header
+ ws *websocket.Conn
+ raw net.Conn // the accepted connection under ws
+ closed chan struct{}
+
+ mu sync.Mutex
+ id string
+ subscribed bool
+ backs chan string // decoded data of the client's replies to probes
+}
+
+func newCableApp() *cableApp {
+ a := &cableApp{conns: make(map[*appConn]struct{}), opened: make(chan *appConn, 1024)}
+ a.srv = &websocket.Server{
+ // Action Cable's same-origin rule and its one subprotocol.
+ Handshake: func(cfg *websocket.Config, r *http.Request) error {
+ if want := r.Header.Get("X-Forwarded-Proto") + "://" + r.Host; r.Header.Get("Origin") != want {
+ return fmt.Errorf("origin %q is not %q", r.Header.Get("Origin"), want)
+ }
+ if !slices.Contains(cfg.Protocol, cableProtocol) {
+ return fmt.Errorf("subprotocols %q lack %s", cfg.Protocol, cableProtocol)
+ }
+ cfg.Protocol = []string{cableProtocol}
+ return nil
+ },
+ Handler: func(ws *websocket.Conn) { a.serve(ws) },
+ }
+ return a
+}
+
+func (a *cableApp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ a.mu.Lock()
+ a.seen = append(a.seen, seenReq{Host: r.Host, Method: r.Method, Path: r.URL.Path, Header: r.Header.Clone()})
+ a.mu.Unlock()
+ switch r.URL.Path {
+ case "/cable":
+ a.srv.ServeHTTP(w, r)
+ case "/missing":
+ http.NotFound(w, r)
+ default:
+ io.WriteString(w, "plain:"+r.Host+r.URL.Path)
+ }
+}
+
+// seenFor is every request the app saw for host.
+func (a *cableApp) seenFor(host string) []seenReq {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ var out []seenReq
+ for _, s := range a.seen {
+ if s.Host == host {
+ out = append(out, s)
+ }
+ }
+ return out
+}
+
+func (a *cableApp) send(c *appConn, v any) error {
+ b, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+ return websocket.Message.Send(c.ws, string(b))
+}
+
+func (a *cableApp) serve(ws *websocket.Conn) {
+ r := ws.Request()
+ raw, _ := r.Context().Value(rawConnKey{}).(net.Conn)
+ c := &appConn{host: r.Host, hdr: r.Header.Clone(), ws: ws, raw: raw, closed: make(chan struct{}), backs: make(chan string, 256)}
+ a.mu.Lock()
+ a.conns[c] = struct{}{}
+ a.mu.Unlock()
+ defer func() {
+ ws.Close()
+ a.mu.Lock()
+ delete(a.conns, c)
+ a.mu.Unlock()
+ close(c.closed)
+ }()
+ select {
+ case a.opened <- c:
+ default:
+ }
+ a.send(c, map[string]any{"type": "welcome"})
+ go func() {
+ tick := time.NewTicker(200 * time.Millisecond)
+ defer tick.Stop()
+ for n := 1; ; n++ {
+ select {
+ case <-c.closed:
+ return
+ case <-tick.C:
+ a.send(c, map[string]any{"type": "ping", "message": n})
+ }
+ }
+ }()
+ for {
+ var frame string
+ if err := websocket.Message.Receive(ws, &frame); err != nil {
+ return
+ }
+ var cmd struct{ Command, Identifier, Data string }
+ if json.Unmarshal([]byte(frame), &cmd) != nil {
+ continue
+ }
+ switch cmd.Command {
+ case "subscribe":
+ c.mu.Lock()
+ c.id, c.subscribed = cmd.Identifier, true
+ c.mu.Unlock()
+ a.send(c, map[string]any{"identifier": cmd.Identifier, "type": "confirm_subscription"})
+ case "message":
+ var d struct{ Action, Text string }
+ if json.Unmarshal([]byte(cmd.Data), &d) != nil {
+ continue
+ }
+ switch d.Action {
+ case "echo": // the whole frame, back as it came
+ a.send(c, map[string]any{"identifier": cmd.Identifier, "message": map[string]string{"echo": frame}})
+ case "back":
+ c.backs <- d.Text
+ }
+ }
+ }
+}
+
+// rawConnKey carries the app's accepted connection on its requests'
+// contexts, so a test can drop it as a dying process would.
+type rawConnKey struct{}
+
+// broadcast sends text to every subscribed socket on host.
+func (a *cableApp) broadcast(host, text string) int {
+ a.mu.Lock()
+ var to []*appConn
+ for c := range a.conns {
+ c.mu.Lock()
+ if c.host == host && c.subscribed {
+ to = append(to, c)
+ }
+ c.mu.Unlock()
+ }
+ a.mu.Unlock()
+ for _, c := range to {
+ a.send(c, map[string]any{"identifier": c.id, "message": map[string]string{"text": text}})
+ }
+ return len(to)
+}
+
+// probe sends one app-initiated frame on c and returns its exact text.
+func (a *cableApp) probe(t *testing.T, c *appConn, payload string) string {
+ t.Helper()
+ c.mu.Lock()
+ id := c.id
+ c.mu.Unlock()
+ b, err := json.Marshal(map[string]any{"identifier": id, "message": map[string]string{"probe": payload}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := websocket.Message.Send(c.ws, string(b)); err != nil {
+ t.Fatalf("the app's probe: %v", err)
+ }
+ return string(b)
+}
+
+func (a *cableApp) closeAll() {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ for c := range a.conns {
+ c.ws.Close()
+ }
+}
+
+// drainOpened forgets sockets opened earlier, so the next one read is new.
+func (a *cableApp) drainOpened() {
+ for {
+ select {
+ case <-a.opened:
+ default:
+ return
+ }
+ }
+}
+
+func (a *cableApp) nextOpened(t *testing.T, host string) *appConn {
+ t.Helper()
+ select {
+ case c := <-a.opened:
+ if c.host != host {
+ t.Fatalf("the app opened a socket for %s, want %s", c.host, host)
+ }
+ return c
+ case <-time.After(5 * time.Second):
+ t.Fatalf("the app opened no socket for %s within 5 s", host)
+ return nil
+ }
+}
+
+// ---- the box's hand-written answers (case 12) ------------------------------
+
+// rawBox answers wsRawHost on the box in place of the box Edge, to give the
+// hub the in-band answers no real app behind the edge's own proxy can give.
+type rawBox struct{ arrived chan struct{} }
+
+func (b *rawBox) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ hijackAndSay := func(s string) {
+ conn, brw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ brw.WriteString(s)
+ brw.Flush()
+ io.Copy(io.Discard, conn) // until the hub resets the stream
+ }
+ switch r.URL.Path {
+ case "/malformed":
+ hijackAndSay("HTTP/1.1 101 Switching Protocols\r\nUpgrade websocket\r\n\r\n")
+ case "/wrongup":
+ hijackAndSay("HTTP/1.1 101 Switching Protocols\r\nUpgrade: h2c\r\nConnection: Upgrade\r\n\r\n")
+ case "/hang":
+ b.arrived <- struct{}{}
+ <-r.Context().Done()
+ default:
+ http.NotFound(w, r)
+ }
+}
+
+// ---- plumbing -------------------------------------------------------------
+
+// trackingListener keeps every connection it accepts, so a test can do
+// what the kernel does when the process dies: close all of them, hijacked
+// ones included (spec §8.2 case 9; Task 7).
+type trackingListener struct {
+ net.Listener
+ mu sync.Mutex
+ conns []net.Conn
+}
+
+func (l *trackingListener) Accept() (net.Conn, error) {
+ c, err := l.Listener.Accept()
+ if err == nil {
+ l.mu.Lock()
+ l.conns = append(l.conns, c)
+ l.mu.Unlock()
+ }
+ return c, err
+}
+
+func (l *trackingListener) closeAll() {
+ l.Listener.Close()
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ for _, c := range l.conns {
+ c.Close()
+ }
+}
+
+// callStore counts every call to a static store (spec §6, case 14).
+type callStore struct {
+ release.Store
+ n atomic.Int64
+}
+
+func (s *callStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.n.Add(1)
+ return s.Store.Get(ctx, key)
+}
+
+func (s *callStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ s.n.Add(1)
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (s *callStore) List(ctx context.Context, prefix string) ([]string, error) {
+ s.n.Add(1)
+ return s.Store.List(ctx, prefix)
+}
+
+func (s *callStore) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ s.n.Add(1)
+ return s.Store.ListDirs(ctx, prefix)
+}
+
+func (s *callStore) Delete(ctx context.Context, key string) error {
+ s.n.Add(1)
+ return s.Store.Delete(ctx, key)
+}
+
+// lineLog keeps the box loops' log lines.
+type lineLog struct {
+ mu sync.Mutex
+ lines []string
+}
+
+func (l *lineLog) add(s string) {
+ l.mu.Lock()
+ l.lines = append(l.lines, s)
+ l.mu.Unlock()
+}
+
+func (l *lineLog) contains(sub string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ for _, s := range l.lines {
+ if strings.Contains(s, sub) {
+ return true
+ }
+ }
+ return false
+}
+
+// notSupportedWriter's Hijack says http.ErrNotSupported; noHijackWriter
+// has no Hijack at all.
+type notSupportedWriter struct{ http.ResponseWriter }
+
+func (notSupportedWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ return nil, nil, http.ErrNotSupported
+}
+
+type noHijackWriter struct{ http.ResponseWriter }
+
+const (
+ wrapNone int32 = iota
+ wrapNotSupported
+ wrapNoHijack
+)
+
+// ---- the scene -------------------------------------------------------------
+
+type wsScene struct {
+ t *testing.T
+ hub, box *Edge
+ hubReg, boxReg *registry.Registry
+ srv, wrapSrv *httptest.Server
+ ln *trackingListener
+ addr, wrapAddr string
+ app *cableApp
+ raw *rawBox
+ hash string
+ sink *memErrSink
+ hubStore, boxStore *callStore
+ logs *lineLog
+ client *http.Client
+
+ throttle atomic.Bool // the plan throttle hook's answer for fwdOwner
+ inserts atomic.Int64
+ inserted chan *upgradeReservation // each reservation, as it is taken
+ noted map[*upgradeReservation]bool // guarded by hub.open.mu
+
+ // the wrapping server's mode and the barrier its handler waits on
+ // after the hub returns (case 12)
+ wrapMode atomic.Int32
+ wrapBarrier atomic.Pointer[chan struct{}]
+ wrapReturned chan struct{}
+
+ loopMu sync.Mutex
+ loops map[string]*loopHandle
+
+ cookieMu sync.Mutex
+ cookies map[string]string
+}
+
+// newWSScene builds the scene and starts the box's loops as home/box-1
+// and t1. It does not wait for them to connect.
+func newWSScene(t *testing.T, fx tlsFixture) *wsScene {
+ t.Helper()
+ // The hub's environment, read by New and Reload; set first.
+ t.Setenv("CARLOS_TUNNEL_HOST", "127.0.0.1")
+ t.Setenv("CARLOS_FLEET", "")
+ t.Setenv("CARLOS_RATE_LIMIT", "enforce")
+
+ hashB, err := bcrypt.GenerateFromPassword([]byte("right"), bcrypt.MinCost)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := &wsScene{
+ t: t, hash: string(hashB), app: newCableApp(), raw: &rawBox{arrived: make(chan struct{}, 16)},
+ sink: &memErrSink{}, logs: &lineLog{}, inserted: make(chan *upgradeReservation, 1024),
+ noted: make(map[*upgradeReservation]bool),
+ wrapReturned: make(chan struct{}, 16), loops: make(map[string]*loopHandle), cookies: make(map[string]string),
+ }
+ _, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ frozen := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
+
+ // The app on a unix socket.
+ sock := filepath.Join(t.TempDir(), "app.sock")
+ appLn, err := net.Listen("unix", sock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ appSrv := &http.Server{Handler: s.app, ConnContext: func(ctx context.Context, c net.Conn) context.Context {
+ return context.WithValue(ctx, rawConnKey{}, c)
+ }}
+ go appSrv.Serve(appLn)
+ t.Cleanup(func() {
+ appSrv.Close()
+ s.app.closeAll()
+ })
+
+ // The hub.
+ s.hubReg = openReg(t)
+ for _, f := range []string{"home", "away"} {
+ if err := s.hubReg.UpsertFleet(registry.Fleet{Name: f, Account: fwdOwner, Bucket: f + "-data"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, b := range []registry.FleetBox{
+ {Fleet: "home", Label: "box-1", TokenHash: sha256Hex(fwdBox1Tok), Status: "active"},
+ {Fleet: "away", Label: "box-2", TokenHash: sha256Hex(fwdBox2Tok), Status: "active"},
+ } {
+ if err := s.hubReg.AddFleetBox(b); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, rt := range []registry.Route{
+ wsForward(wsHost, "home", wsWideRate),
+ wsForward(wsLimitedHost, "home", wsLimitedRate),
+ wsForward(wsRawHost, "home", wsWideRate),
+ wsForward(wsOldHost, "away", wsWideRate),
+ } {
+ if err := s.hubReg.PutForward(rt); err != nil {
+ t.Fatalf("PutForward(%s): %v", rt.Host, err)
+ }
+ }
+ if err := s.hubReg.Upsert(wsTunnelRow("t1")); err != nil {
+ t.Fatal(err)
+ }
+ // A -tunnel row is a platform row on the hub: its gate is the hub's
+ // (the hub 404s a login POST to an ungated non-forward row).
+ if err := s.hubReg.SetGate(wsTunnelHost, s.hash); err != nil {
+ t.Fatal(err)
+ }
+ s.hub, err = New(s.hubReg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(s.hub.probers.Stop)
+ s.hub.EnableTunnels(NewTunnelHub("127.0.0.1", map[string]string{"t1": fwdT1Tok}))
+ s.hubStore = &callStore{Store: release.NewDirStore(t.TempDir())}
+ s.hub.EnableStatic(s.hubStore, pub, filepath.Join(t.TempDir(), "cache"))
+ s.hub.EnableErrors(s.sink)
+ s.hub.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) {
+ if rt.Account != fwdOwner || !s.throttle.Load() {
+ return plans.Throttle{}, false
+ }
+ return plans.Throttle{Bandwidth: true, Awake: true, Until: time.Now().Add(time.Hour)}, true
+ })
+ s.hub.open.afterInsert = s.noteInsert
+ if err := s.hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+
+ // The box.
+ s.boxReg = openReg(t)
+ for _, rt := range []registry.Route{
+ wsBoxRow(wsHost, sock, ""),
+ wsBoxRow(wsTunnelHost, sock, ""),
+ wsBoxRow(wsLimitedHost, sock, wsBoxRate),
+ wsBoxRow(wsOldHost, sock, ""),
+ } {
+ if err := s.boxReg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.boxReg.SetGate(wsHost, s.hash); err != nil {
+ t.Fatal(err)
+ }
+ s.box, err = New(s.boxReg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(s.box.probers.Stop)
+ s.boxStore = &callStore{Store: release.NewDirStore(t.TempDir())}
+ s.box.EnableStatic(s.boxStore, pub, filepath.Join(t.TempDir(), "cache"))
+ if err := s.box.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range []*Edge{s.hub, s.box} {
+ if e.rateMode != RateEnforce {
+ t.Fatalf("rate mode %v, want enforce", e.rateMode)
+ }
+ e.rateLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000)
+ e.planLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000)
+ }
+ if got := s.box.current()[wsHost].route.Gate; got != s.hash {
+ t.Fatalf("the box's %s row has gate %q, want the scene's", wsHost, got)
+ }
+
+ // The hub's TLS server over the tracking listener, and a second one
+ // serving the same hub behind case 12's wrapping writers.
+ s.srv = httptest.NewUnstartedServer(s.hub)
+ s.ln = &trackingListener{Listener: s.srv.Listener}
+ s.srv.Listener = s.ln
+ s.srv.TLS = fx.ServerTLS
+ s.srv.StartTLS()
+ s.addr = s.ln.Addr().String()
+ s.wrapSrv = httptest.NewUnstartedServer(http.HandlerFunc(s.serveWrapped))
+ s.wrapSrv.TLS = fx.ServerTLS
+ s.wrapSrv.StartTLS()
+ s.wrapAddr = s.wrapSrv.Listener.Addr().String()
+ t.Cleanup(func() {
+ // The hub's connections first: a loop whose tunnel is still up
+ // returns only when its conn dies.
+ s.ln.closeAll()
+ s.srv.Close()
+ s.stopLoops()
+ if b := s.wrapBarrier.Load(); b != nil {
+ select {
+ case <-*b:
+ default:
+ close(*b)
+ }
+ }
+ s.wrapSrv.CloseClientConnections()
+ s.wrapSrv.Close()
+ })
+ s.client = &http.Client{
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, s.addr)
+ },
+ DisableKeepAlives: true,
+ },
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ Timeout: 10 * time.Second,
+ }
+
+ s.startLoop(wsBox1, wsBox1, fwdBox1Tok)
+ s.startLoop("t1", "t1", fwdT1Tok)
+ return s
+}
+
+func wsForward(host, fleet, rate string) registry.Route {
+ rt := forwardRow(host, fleet, fwdOwner)
+ rt.RateLimit = rate
+ return rt
+}
+
+func wsTunnelRow(channel string) registry.Route {
+ return registry.Route{Host: wsTunnelHost, Kind: "instance", Status: "ready", Tunnel: channel,
+ Account: fwdOwner, App: "shop", RateLimit: wsWideRate}
+}
+
+func wsBoxRow(host, sock, rate string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", Status: "ready", Socket: sock,
+ Account: fwdOwner, App: "shop", RateLimit: rate}
+}
+
+// loopHandle is one running box loop.
+type loopHandle struct {
+ cancel context.CancelFunc
+ done chan struct{}
+}
+
+// noteInsert is the hub's afterInsert seam: it hands each new reservation
+// to the test.
+func (s *wsScene) noteInsert() {
+ o := &s.hub.open
+ var fresh []*upgradeReservation
+ o.mu.Lock()
+ for _, set := range o.byHost {
+ for r := range set {
+ if !s.noted[r] {
+ s.noted[r] = true
+ fresh = append(fresh, r)
+ }
+ }
+ }
+ o.mu.Unlock()
+ s.inserts.Add(int64(len(fresh)))
+ for _, r := range fresh {
+ select {
+ case s.inserted <- r:
+ default:
+ }
+ }
+}
+
+func (s *wsScene) drainInserted() {
+ for {
+ select {
+ case <-s.inserted:
+ default:
+ return
+ }
+ }
+}
+
+func (s *wsScene) nextInserted(t *testing.T) *upgradeReservation {
+ t.Helper()
+ select {
+ case r := <-s.inserted:
+ return r
+ case <-time.After(5 * time.Second):
+ t.Fatal("no reservation was taken within 5 s")
+ return nil
+ }
+}
+
+// serveWrapped is the second server's handler: the hub behind the current
+// wrapping writer, then the barrier, so the request stays live.
+func (s *wsScene) serveWrapped(w http.ResponseWriter, r *http.Request) {
+ switch s.wrapMode.Load() {
+ case wrapNotSupported:
+ w = notSupportedWriter{w}
+ case wrapNoHijack:
+ w = noHijackWriter{w}
+ }
+ s.hub.ServeHTTP(w, r)
+ s.wrapReturned <- struct{}{}
+ if b := s.wrapBarrier.Load(); b != nil {
+ <-*b
+ }
+}
+
+// startLoop runs a box loop dialing as channel name, kept under key.
+func (s *wsScene) startLoop(key, name, token string) {
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ t := s.t
+ go func() {
+ defer close(done)
+ tunnelclient.Loop(ctx, tunnelclient.Config{
+ URL: "https://" + s.addr, Name: name, Token: token, Handler: s.boxHandler(),
+ Logf: func(format string, args ...any) {
+ line := fmt.Sprintf("box %s: "+format, append([]any{key}, args...)...)
+ s.logs.add(line)
+ t.Log(line)
+ },
+ })
+ }()
+ s.loopMu.Lock()
+ if old := s.loops[key]; old != nil {
+ s.loopMu.Unlock()
+ cancel()
+ t.Fatalf("loop %s already running", key)
+ }
+ s.loops[key] = &loopHandle{cancel: cancel, done: done}
+ s.loopMu.Unlock()
+}
+
+func (s *wsScene) stopLoop(key string) { s.cancelLoop(key)() }
+
+// cancelLoop cancels a loop's context and returns a func that waits for
+// the loop to return.
+func (s *wsScene) cancelLoop(key string) (wait func()) {
+ s.loopMu.Lock()
+ h := s.loops[key]
+ s.loopMu.Unlock()
+ if h == nil {
+ return func() {}
+ }
+ h.cancel()
+ return func() {
+ <-h.done
+ s.loopMu.Lock()
+ if s.loops[key] == h {
+ delete(s.loops, key)
+ }
+ s.loopMu.Unlock()
+ }
+}
+
+func (s *wsScene) stopLoops() {
+ s.loopMu.Lock()
+ var names []string
+ for n := range s.loops {
+ names = append(names, n)
+ }
+ s.loopMu.Unlock()
+ for _, n := range names {
+ s.stopLoop(n)
+ }
+}
+
+// boxHandler is what the box's loops serve: the box Edge, but wsRawHost
+// answered by hand.
+func (s *wsScene) boxHandler() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Host == wsRawHost {
+ s.raw.ServeHTTP(w, r)
+ return
+ }
+ s.box.ServeHTTP(w, r)
+ })
+}
+
+func (s *wsScene) channel(t *testing.T, name string) *tunnelConn {
+ t.Helper()
+ tc := s.hub.tunnels.channel(name)
+ if tc == nil {
+ t.Fatalf("%s has no channel connection", name)
+ }
+ return tc
+}
+
+// waitChannel waits up to within for name to be connected on a connection
+// other than old (nil: any).
+func (s *wsScene) waitChannel(t *testing.T, name string, old *tunnelConn, within time.Duration) *tunnelConn {
+ t.Helper()
+ deadline := time.Now().Add(within)
+ for {
+ if tc := s.hub.tunnels.channel(name); tc != nil && tc != old {
+ return tc
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("%s did not connect (anew) within %s", name, within)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func (s *wsScene) dialTLS(t *testing.T, addr, host string) *tls.Conn {
+ t.Helper()
+ c, err := tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp", addr, &tls.Config{ServerName: host})
+ if err != nil {
+ t.Fatalf("TLS to the hub as %s: %v", host, err)
+ }
+ t.Cleanup(func() { c.Close() })
+ return c
+}
+
+// hs is one raw handshake's outcome.
+type hs struct {
+ conn net.Conn
+ br *bufio.Reader
+ resp *http.Response
+ body string
+ key string
+}
+
+// sendHandshake writes a browser's WebSocket handshake for host and path on
+// a new TLS connection to addr, with the gate cookie when cookie is set and
+// the Upgrade token tok. It does not read the answer.
+func (s *wsScene) sendHandshake(t *testing.T, addr, host, path, cookie, tok string) hs {
+ t.Helper()
+ c := s.dialTLS(t, addr, host)
+ c.SetDeadline(time.Now().Add(15 * time.Second))
+ k := make([]byte, 16)
+ rand.Read(k)
+ key := base64.StdEncoding.EncodeToString(k)
+ var b strings.Builder
+ fmt.Fprintf(&b, "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: %s\r\n", path, host, tok)
+ fmt.Fprintf(&b, "Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: %s\r\nSec-WebSocket-Protocol: %s\r\nOrigin: https://%s\r\n", key, cableProtocol, host)
+ if cookie != "" {
+ fmt.Fprintf(&b, "Cookie: %s=%s\r\n", gate.CookieName, cookie)
+ }
+ b.WriteString("\r\n")
+ if _, err := io.WriteString(c, b.String()); err != nil {
+ t.Fatalf("handshake write: %v", err)
+ }
+ return hs{conn: c, br: bufio.NewReader(c), key: key}
+}
+
+// read reads the handshake's answer, and its body when it is not a 101.
+func (h *hs) read(t *testing.T) {
+ t.Helper()
+ resp, err := http.ReadResponse(h.br, nil)
+ if err != nil {
+ t.Fatalf("handshake answer: %v", err)
+ }
+ h.resp = resp
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ b, _ := io.ReadAll(resp.Body)
+ h.body = string(b)
+ }
+}
+
+func (s *wsScene) handshake(t *testing.T, host, path, cookie string) hs {
+ t.Helper()
+ h := s.sendHandshake(t, s.addr, host, path, cookie, "websocket")
+ h.read(t)
+ return h
+}
+
+// wantStatus checks a handshake was answered with status.
+func wantStatus(t *testing.T, h hs, status int, what string) {
+ t.Helper()
+ if h.resp.StatusCode != status {
+ t.Fatalf("%s: %d %q, want %d", what, h.resp.StatusCode, h.body, status)
+ }
+}
+
+func acceptFor(key string) string {
+ sum := sha1.Sum([]byte(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))
+ return base64.StdEncoding.EncodeToString(sum[:])
+}
+
+// do sends one plain request to the hub for host, over TLS.
+func (s *wsScene) do(t *testing.T, method, host, path, cookie string, hdr http.Header, body string) (*http.Response, string) {
+ t.Helper()
+ var rd io.Reader
+ if body != "" {
+ rd = strings.NewReader(body)
+ }
+ req, err := http.NewRequest(method, "https://"+host+path, rd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for k, v := range hdr {
+ req.Header[k] = v
+ }
+ if cookie != "" {
+ req.AddCookie(&http.Cookie{Name: gate.CookieName, Value: cookie})
+ }
+ resp, err := s.client.Do(req)
+ if err != nil {
+ t.Fatalf("%s https://%s%s: %v", method, host, path, err)
+ }
+ b, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ return resp, string(b)
+}
+
+// login logs in through the hub, as a browser posts the gate's form, and
+// returns the gate cookie.
+func (s *wsScene) login(t *testing.T, host string) string {
+ t.Helper()
+ resp, body := s.do(t, http.MethodPost, host, gate.LoginPath, "",
+ http.Header{"Content-Type": {"application/x-www-form-urlencoded"}}, "password=right&next=%2Fcable")
+ if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != "/cable" {
+ t.Fatalf("login to %s: %d -> %q %q, want 303 -> /cable", host, resp.StatusCode, resp.Header.Get("Location"), body)
+ }
+ for _, c := range resp.Cookies() {
+ if c.Name == gate.CookieName && c.Value != "" {
+ return c.Value
+ }
+ }
+ t.Fatalf("login to %s set no %s cookie", host, gate.CookieName)
+ return ""
+}
+
+// cookie is a gate cookie for host from one login through the hub, kept:
+// the gate limits login attempts per client and host.
+func (s *wsScene) cookie(t *testing.T, host string) string {
+ t.Helper()
+ s.cookieMu.Lock()
+ defer s.cookieMu.Unlock()
+ if c := s.cookies[host]; c != "" {
+ return c
+ }
+ c := s.login(t, host)
+ s.cookies[host] = c
+ return c
+}
+
+// cableClient is the browser's end of one socket.
+type cableClient struct {
+ ws *websocket.Conn
+ frames chan string // every frame but pings, in order
+ pings atomic.Int32
+ closed chan struct{}
+}
+
+// openCable opens a socket to host through the hub with x/net/websocket
+// and returns it with the app's end.
+func (s *wsScene) openCable(t *testing.T, host, cookie string) (*cableClient, *appConn) {
+ t.Helper()
+ s.app.drainOpened()
+ conn := s.dialTLS(t, s.addr, host)
+ cfg, err := websocket.NewConfig("wss://"+host+"/cable", "https://"+host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfg.Protocol = []string{cableProtocol}
+ if cookie != "" {
+ cfg.Header = http.Header{"Cookie": {gate.CookieName + "=" + cookie}}
+ }
+ conn.SetDeadline(time.Now().Add(10 * time.Second))
+ ws, err := websocket.NewClient(cfg, conn)
+ if err != nil {
+ t.Fatalf("the socket to %s: %v", host, err)
+ }
+ conn.SetDeadline(time.Time{})
+ if got := ws.Config().Protocol; len(got) != 1 || got[0] != cableProtocol {
+ t.Fatalf("the 101's subprotocol is %q, want %s", got, cableProtocol)
+ }
+ c := &cableClient{ws: ws, frames: make(chan string, 1024), closed: make(chan struct{})}
+ go func() {
+ defer close(c.closed)
+ for {
+ var f string
+ if err := websocket.Message.Receive(ws, &f); err != nil {
+ return
+ }
+ var m struct{ Type string }
+ if json.Unmarshal([]byte(f), &m) == nil && m.Type == "ping" {
+ c.pings.Add(1)
+ continue
+ }
+ select {
+ case c.frames <- f:
+ default:
+ }
+ }
+ }()
+ t.Cleanup(func() { ws.Close() })
+ return c, s.app.nextOpened(t, host)
+}
+
+func (c *cableClient) next(t *testing.T) string {
+ t.Helper()
+ select {
+ case f := <-c.frames:
+ return f
+ case <-c.closed:
+ t.Fatal("the client's socket closed while a frame was awaited")
+ case <-time.After(5 * time.Second):
+ t.Fatal("no frame within 5 s")
+ }
+ return ""
+}
+
+func (c *cableClient) send(t *testing.T, v any) string {
+ t.Helper()
+ b, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := websocket.Message.Send(c.ws, string(b)); err != nil {
+ t.Fatalf("the client's send: %v", err)
+ }
+ return string(b)
+}
+
+// echo sends one message through and checks the app's echo of it.
+func (c *cableClient) echo(t *testing.T, text string) {
+ t.Helper()
+ data, _ := json.Marshal(map[string]string{"action": "echo", "text": text})
+ sent := c.send(t, map[string]string{"command": "message", "identifier": cableChannel, "data": string(data)})
+ var got struct {
+ Identifier string
+ Message struct{ Echo string }
+ }
+ f := c.next(t)
+ if err := json.Unmarshal([]byte(f), &got); err != nil || got.Message.Echo != sent {
+ t.Fatalf("echo: got %q, want the app to have seen exactly %q", f, sent)
+ }
+}
+
+// waitClosed waits for ch to close within d.
+func waitClosed(t *testing.T, ch <-chan struct{}, d time.Duration, what string) {
+ t.Helper()
+ select {
+ case <-ch:
+ case <-time.After(d):
+ t.Fatalf("%s: not closed within %s", what, d)
+ }
+}
+
+// notClosed checks ch has not closed.
+func notClosed(t *testing.T, ch <-chan struct{}, what string) {
+ t.Helper()
+ select {
+ case <-ch:
+ t.Fatalf("%s closed", what)
+ default:
+ }
+}
+
+// payload is a deterministic test string of mixed bytes: ASCII, JSON
+// escapes and multi-byte UTF-8.
+func payload(r *mrand.Rand, i int) string {
+ const alphabet = "abcXYZ019 \"\\/{}[]:,\t\né✓€😀
<>&"
+ runes := []rune(alphabet)
+ n := 1 + r.IntN(2048)
+ var b strings.Builder
+ fmt.Fprintf(&b, "%03d:", i)
+ for range n {
+ b.WriteRune(runes[r.IntN(len(runes))])
+ }
+ return b.String()
+}
+
+// subscribe sends Action Cable's subscribe and waits for the confirmation.
+func (c *cableClient) subscribe(t *testing.T) {
+ t.Helper()
+ c.send(t, map[string]string{"command": "subscribe", "identifier": cableChannel})
+ var got struct{ Identifier, Type string }
+ if f := c.next(t); json.Unmarshal([]byte(f), &got) != nil || got.Type != "confirm_subscription" || got.Identifier != cableChannel {
+ t.Fatalf("after subscribe: %q, want confirm_subscription for %s", f, cableChannel)
+ }
+}
+
+// openShop logs in and opens a socket to wsHost.
+func (s *wsScene) openShop(t *testing.T) (*cableClient, *appConn) {
+ t.Helper()
+ c, ac := s.openCable(t, wsHost, s.cookie(t, wsHost))
+ if f := c.next(t); f != `{"type":"welcome"}` {
+ t.Fatalf("first frame %q, want the welcome", f)
+ }
+ c.subscribe(t)
+ return c, ac
+}
+
+// fullExchange is spec §8.2 case 2 against host: login, the handshake
+// (101, the app's accept, the subprotocol), welcome, pings, subscribe and
+// confirm, a broadcast, 100 echoes each way byte for byte, and what the
+// app saw of the handshake.
+func (s *wsScene) fullExchange(t *testing.T, host string) {
+ cookie := s.login(t, host)
+
+ // The handshake as a browser sends it, read raw.
+ h := s.handshake(t, host, "/cable", cookie)
+ wantStatus(t, h, http.StatusSwitchingProtocols, "the handshake")
+ if got := h.resp.Header.Get("Sec-WebSocket-Protocol"); got != cableProtocol {
+ t.Fatalf("101 Sec-WebSocket-Protocol %q, want %s", got, cableProtocol)
+ }
+ if got, want := h.resp.Header.Get("Sec-WebSocket-Accept"), acceptFor(h.key); got != want {
+ t.Fatalf("101 Sec-WebSocket-Accept %q, want the app's %q", got, want)
+ }
+ h.conn.Close()
+
+ c, ac := s.openCable(t, host, cookie)
+ if f := c.next(t); f != `{"type":"welcome"}` {
+ t.Fatalf("first frame %q, want the welcome", f)
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for c.pings.Load() < 2 {
+ if time.Now().After(deadline) {
+ t.Fatalf("%d pings within 2 s, want 2", c.pings.Load())
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ c.subscribe(t)
+ if n := s.app.broadcast(host, "hello, subscribers"); n != 1 {
+ t.Fatalf("the broadcast reached %d sockets, want 1", n)
+ }
+ var bc struct {
+ Identifier string
+ Message struct{ Text string }
+ }
+ if f := c.next(t); json.Unmarshal([]byte(f), &bc) != nil || bc.Message.Text != "hello, subscribers" || bc.Identifier != cableChannel {
+ t.Fatalf("broadcast frame %q", f)
+ }
+
+ r := mrand.New(mrand.NewPCG(471, 6))
+ for i := range 100 {
+ c.echo(t, payload(r, i))
+ }
+ for i := range 100 {
+ sent := s.app.probe(t, ac, payload(r, i))
+ got := c.next(t)
+ if got != sent {
+ t.Fatalf("probe %d: the client got %q, the app sent %q", i, got, sent)
+ }
+ data, _ := json.Marshal(map[string]string{"action": "back", "text": got})
+ c.send(t, map[string]string{"command": "message", "identifier": cableChannel, "data": string(data)})
+ select {
+ case back := <-ac.backs:
+ if back != sent {
+ t.Fatalf("probe %d: the app got back %q, sent %q", i, back, sent)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatalf("probe %d: no reply reached the app within 5 s", i)
+ }
+ }
+
+ if ck := ac.hdr.Get("Cookie"); strings.Contains(ck, gate.CookieName) {
+ t.Fatalf("the app saw the gate cookie: Cookie %q", ck)
+ }
+ if got := ac.hdr.Get("X-Forwarded-Proto"); got != "https" {
+ t.Fatalf("the app saw X-Forwarded-Proto %q, want https", got)
+ }
+ c.ws.Close()
+ waitClosed(t, ac.closed, 2*time.Second, "the app's end after the client closed")
+}
+
+// ---- the witness ------------------------------------------------------------
+
+func TestTunnelWebSocketEndToEnd(t *testing.T) {
+ child, fx := runTrustedChild(t)
+ if !child {
+ return
+ }
+ s := newWSScene(t, fx)
+
+ // First: the real Loop trusted the fixture over real TLS.
+ waitForTunnelState(t, s.hub.tunnels, wsBox1, "connected", 5*time.Second)
+ waitForTunnelState(t, s.hub.tunnels, "t1", "connected", 5*time.Second)
+ if tc := s.channel(t, wsBox1); tc.caps != tunnelclient.CapUpgrade {
+ t.Fatalf("%s registered with caps %q, want %s", wsBox1, tc.caps, tunnelclient.CapUpgrade)
+ }
+
+ // Case 14's baseline: what plain requests cost the static stores.
+ var baseHub, baseBox, markHub, markBox int64
+ t.Run("baseline", func(t *testing.T) {
+ h0, b0 := s.hubStore.n.Load(), s.boxStore.n.Load()
+ cookie := s.cookie(t, wsHost)
+ for range 3 {
+ if resp, body := s.do(t, "GET", wsHost, "/plain", cookie, nil, ""); resp.StatusCode != 200 || body != "plain:"+wsHost+"/plain" {
+ t.Fatalf("a plain GET: %d %q", resp.StatusCode, body)
+ }
+ }
+ baseHub, baseBox = s.hubStore.n.Load()-h0, s.boxStore.n.Load()-b0
+ t.Logf("plain-request baseline: hub store %d calls, box store %d", baseHub, baseBox)
+ markHub, markBox = s.hubStore.n.Load(), s.boxStore.n.Load()
+ })
+
+ t.Run("case01_gate", func(t *testing.T) {
+ tc := s.channel(t, wsBox1)
+ before := len(s.app.seenFor(wsHost))
+ h := s.handshake(t, wsHost, "/cable", "")
+ wantStatus(t, h, http.StatusUnauthorized, "a handshake with no cookie")
+ // Review Focus 3: a cookie whose expiry has passed is no cookie.
+ expired := gate.Mint(wsHost, s.hash, time.Now().Add(-time.Minute))
+ h = s.handshake(t, wsHost, "/cable", expired)
+ wantStatus(t, h, http.StatusUnauthorized, "a handshake with an expired cookie")
+ if n := len(s.app.seenFor(wsHost)); n != before {
+ t.Fatalf("the app saw %d requests, want none", n-before)
+ }
+ waitOpen(t, s.hub, tc, 0, "after the gate's answers")
+ // Control: the same handshake with a live cookie is the app's 101.
+ h = s.handshake(t, wsHost, "/cable", gate.Mint(wsHost, s.hash, time.Now().Add(time.Hour)))
+ wantStatus(t, h, http.StatusSwitchingProtocols, "control: a handshake with a live cookie")
+ h.conn.Close()
+ waitOpen(t, s.hub, tc, 0, "after the control closed")
+ })
+
+ t.Run("case02_full", func(t *testing.T) {
+ s.fullExchange(t, wsHost)
+ waitOpen(t, s.hub, s.channel(t, wsBox1), 0, "after case 2")
+ })
+
+ t.Run("case02b_tunnel_arm", func(t *testing.T) {
+ ten, ok := tenancyAt(s.hub, wsTunnelHost)
+ if !ok || ten.Arm != ArmTunnel || ten.Tunnel != "t1" {
+ t.Fatalf("%s is served %v under %+v, want the -tunnel arm on t1", wsTunnelHost, ok, ten)
+ }
+ s.fullExchange(t, wsTunnelHost)
+ waitOpen(t, s.hub, s.channel(t, "t1"), 0, "after case 2b")
+ })
+
+ t.Run("case03_close_account", func(t *testing.T) {
+ s.hub.SetPlanGovernedFor(func(rt registry.Route) bool { return rt.Account == fwdOwner })
+ defer s.hub.SetPlanGovernedFor(nil)
+ c, ac := s.openShop(t)
+ c.echo(t, "before the close")
+ if n := s.hub.CloseAccountUpgrades(fwdOwner); n != 1 {
+ t.Fatalf("CloseAccountUpgrades(%s) with one socket open closed %d, want 1", fwdOwner, n)
+ }
+ waitClosed(t, c.closed, 2*time.Second, "the client's socket")
+ waitClosed(t, ac.closed, 2*time.Second, "the app's socket")
+ if n := s.hub.CloseAccountUpgrades(fwdOwner); n != 0 {
+ t.Fatalf("a second CloseAccountUpgrades closed %d, want 0", n)
+ }
+ waitOpen(t, s.hub, s.channel(t, wsBox1), 0, "after the close")
+ })
+
+ t.Run("case04_plan_throttle", func(t *testing.T) {
+ cookie := s.cookie(t, wsHost)
+ before := len(s.app.seenFor(wsHost))
+ s.throttle.Store(true)
+ h := s.handshake(t, wsHost, "/cable", cookie)
+ s.throttle.Store(false)
+ wantStatus(t, h, http.StatusTooManyRequests, "a handshake while awake-throttled")
+ if got := h.resp.Header.Get("Retry-After"); got != "60" {
+ t.Fatalf("Retry-After %q, want 60", got)
+ }
+ if n := len(s.app.seenFor(wsHost)); n != before {
+ t.Fatalf("the app saw %d requests, want none", n-before)
+ }
+ // Control: the throttle lifted, the same handshake is a 101.
+ h = s.handshake(t, wsHost, "/cable", cookie)
+ wantStatus(t, h, http.StatusSwitchingProtocols, "control: unthrottled")
+ h.conn.Close()
+ })
+
+ t.Run("case05_rate_limit", func(t *testing.T) {
+ if got := s.box.current()[wsLimitedHost].rate.Burst; got != 1 {
+ t.Fatalf("the box's own row has burst %d, want 1", got)
+ }
+ if got := s.hub.current()[wsLimitedHost].rate.Burst; got != 2 {
+ t.Fatalf("the hub's row has burst %d, want 2", got)
+ }
+ for i := 1; i <= 2; i++ {
+ h := s.handshake(t, wsLimitedHost, "/cable", "")
+ wantStatus(t, h, http.StatusSwitchingProtocols, fmt.Sprintf("handshake %d (the box's burst of 1 must never judge)", i))
+ h.conn.Close()
+ }
+ h := s.handshake(t, wsLimitedHost, "/cable", "")
+ wantStatus(t, h, http.StatusTooManyRequests, "handshake 3, past the hub's burst")
+ if got := h.resp.Header.Get("Retry-After"); got != "1" || h.body != rateLimitBody {
+ t.Fatalf("handshake 3: Retry-After %q body %q, want 1 and the edge's body", got, h.body)
+ }
+ if n := len(s.app.seenFor(wsLimitedHost)); n != 2 {
+ t.Fatalf("the app saw %d handshakes, want 2", n)
+ }
+ })
+
+ t.Run("case06_app_closes", func(t *testing.T) {
+ // Two shapes: the app's close frame, and its connection dropped
+ // with no frame (a retiring generation's process exiting). The
+ // second is the transport's: the box's proxy sees EOF from the
+ // app, its handler returns and ends the stream, and the hub's
+ // proxy half-closes toward the client, which reads EOF.
+ for _, drop := range []bool{false, true} {
+ c, ac := s.openShop(t)
+ c.echo(t, "before the app closes")
+ if drop {
+ ac.raw.Close()
+ } else {
+ ac.ws.Close()
+ }
+ waitClosed(t, ac.closed, 2*time.Second, "the app's socket")
+ waitClosed(t, c.closed, 2*time.Second, fmt.Sprintf("the client's socket (dropped %v)", drop))
+ // The hub holds the slot until the client closes its side, as
+ // a browser does once it reads the close.
+ c.ws.Close()
+ waitOpen(t, s.hub, s.channel(t, wsBox1), 0, "after the app closed and the client followed")
+ }
+ })
+
+ t.Run("case10_plain_with_marker", func(t *testing.T) {
+ cookie := s.cookie(t, wsHost)
+ inserts := s.inserts.Load()
+ resp, body := s.do(t, "GET", wsHost, "/marked", cookie, http.Header{tunnelclient.UpgradeHeader: {"websocket"}}, "")
+ if resp.StatusCode != 200 || body != "plain:"+wsHost+"/marked" {
+ t.Fatalf("a plain GET with the marker: %d %q, want the app's plain answer", resp.StatusCode, body)
+ }
+ seen := s.app.seenFor(wsHost)
+ last := seen[len(seen)-1]
+ if last.Path != "/marked" || last.Method != "GET" {
+ t.Fatalf("the app's last request was %s %s", last.Method, last.Path)
+ }
+ for _, h := range []string{"Upgrade", tunnelclient.UpgradeHeader, tunnelclient.UpgradedHeader} {
+ if v, ok := last.Header[h]; ok {
+ t.Fatalf("the app saw %s: %q on a plain GET", h, v)
+ }
+ }
+ if strings.Contains(strings.ToLower(last.Header.Get("Connection")), "upgrade") {
+ t.Fatalf("the app saw Connection %q", last.Header.Get("Connection"))
+ }
+ if got := s.inserts.Load(); got != inserts {
+ t.Fatalf("the hub took %d reservations for a plain GET, want 0", got-inserts)
+ }
+ waitOpen(t, s.hub, s.channel(t, wsBox1), 0, "after the plain GET")
+ })
+
+ t.Run("case11_old_box", func(t *testing.T) {
+ // away/box-2 registers by hand without the capability and serves
+ // the box Edge with no shim, as a release before #471 does.
+ conn := s.dialTLS(t, s.addr, "127.0.0.1")
+ req := tunnelReq(wsBox2, fwdBox2Tok)
+ req.Host = s.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)
+ }
+ var served net.Conn = conn
+ if br.Buffered() > 0 {
+ served = &readerConn{Conn: conn, r: io.MultiReader(br, conn)}
+ }
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ tunnelclient.ServeWith(served, s.box, tunnelclient.DefaultLimits)
+ }()
+ t.Cleanup(func() {
+ s.hub.tunnels.CloseChannel(wsBox2)
+ conn.Close()
+ <-done
+ })
+ waitForTunnelState(t, s.hub.tunnels, wsBox2, "connected", 5*time.Second)
+ if tc := s.channel(t, wsBox2); tc.caps != "" {
+ t.Fatalf("%s has caps %q, want none", wsBox2, tc.caps)
+ }
+ h := s.handshake(t, wsOldHost, "/cable", "")
+ wantStatus(t, h, http.StatusBadGateway, "an upgrade to the old box")
+ wantCause(t, s.sink, http.StatusBadGateway, "tunnel_upgrade_unsupported")
+ if n := len(s.app.seenFor(wsOldHost)); n != 0 {
+ t.Fatalf("the app saw %d requests, want none", n)
+ }
+ // Control: a plain GET to the old box answers.
+ if resp, body := s.do(t, "GET", wsOldHost, "/", "", nil, ""); resp.StatusCode != 200 || body != "plain:"+wsOldHost+"/" {
+ t.Fatalf("a plain GET to the old box: %d %q", resp.StatusCode, body)
+ }
+ s.hub.tunnels.CloseChannel(wsBox2)
+ waitForTunnelState(t, s.hub.tunnels, wsBox2, "", 5*time.Second)
+ })
+
+ t.Run("case16_no_false_closes", func(t *testing.T) {
+ tc := s.channel(t, wsBox1)
+ c, ac := s.openShop(t)
+ for i := range 20 {
+ switch i % 3 {
+ case 0: // another host comes and goes
+ if i%2 == 0 {
+ if err := s.hubReg.Upsert(registry.Route{Host: wsOtherHost, Kind: "instance", Status: "ready", Addr: "127.0.0.1:9", Account: fwdOther, App: "other"}); err != nil {
+ t.Fatal(err)
+ }
+ } else if err := s.hubReg.Delete(wsOtherHost); err != nil {
+ t.Fatal(err)
+ }
+ case 1: // this box's token rotates
+ setBoxToken(t, s.hubReg, "home", "box-1", sha256Hex(fmt.Sprintf("rotated-%d", i)))
+ case 2: // the same forward row, re-minted unchanged
+ if err := s.hubReg.PutForward(wsForward(wsHost, "home", wsWideRate)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.hub.Reload(); err != nil {
+ t.Fatalf("Reload %d: %v", i, err)
+ }
+ c.echo(t, fmt.Sprintf("after reload %d", i))
+ notClosed(t, ac.closed, fmt.Sprintf("the app's socket after reload %d", i))
+ notClosed(t, c.closed, fmt.Sprintf("the client's socket after reload %d", i))
+ if n, _ := openCount(s.hub, tc); n != 1 {
+ t.Fatalf("after reload %d the channel's count is %d, want 1", i, n)
+ }
+ }
+ setBoxToken(t, s.hubReg, "home", "box-1", sha256Hex(fwdBox1Tok))
+ if err := s.hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ c.echo(t, "after the token came back")
+ c.ws.Close()
+ waitOpen(t, s.hub, tc, 0, "after case 16")
+ })
+
+ t.Run("case08_reregister_detach_rotate", func(t *testing.T) {
+ t.Run("reregistration", func(t *testing.T) {
+ old := s.channel(t, wsBox1)
+ c, ac := s.openShop(t)
+ c.echo(t, "before a second loop registers")
+ s.startLoop("second", wsBox1, fwdBox1Tok) // a second loop as home/box-1
+ waitClosed(t, c.closed, 2*time.Second, "the client's socket")
+ waitClosed(t, ac.closed, 2*time.Second, "the app's socket")
+ s.stopLoop("second")
+ waitOpen(t, s.hub, old, 0, "the replaced connection")
+ s.waitServing(t, 15*time.Second)
+ })
+ t.Run("detach", func(t *testing.T) {
+ c, ac := s.openShop(t)
+ setBoxStatus(t, s.hubReg, "home", "box-1", "detached")
+ if err := s.hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ waitClosed(t, c.closed, 2*time.Second, "the client's socket")
+ waitClosed(t, ac.closed, 2*time.Second, "the app's socket")
+ setBoxStatus(t, s.hubReg, "home", "box-1", "active")
+ if err := s.hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ s.waitServing(t, 15*time.Second)
+ })
+ t.Run("rotation", func(t *testing.T) {
+ tc := s.channel(t, wsBox1)
+ c, ac := s.openShop(t)
+ setBoxToken(t, s.hubReg, "home", "box-1", sha256Hex("a new token"))
+ if err := s.hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ c.echo(t, "after the rotation")
+ notClosed(t, ac.closed, "the app's socket after the rotation")
+ if s.hub.tunnels.channel(wsBox1) != tc {
+ t.Fatal("the rotation replaced the live channel")
+ }
+ setBoxToken(t, s.hubReg, "home", "box-1", sha256Hex(fwdBox1Tok))
+ if err := s.hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ c.echo(t, "after the token came back")
+ c.ws.Close()
+ waitOpen(t, s.hub, tc, 0, "after the rotation case")
+ })
+ })
+
+ t.Run("case07_tunnel_loss", func(t *testing.T) {
+ old := s.channel(t, wsBox1)
+ c, ac := s.openShop(t)
+ c.echo(t, "before the tunnel goes")
+ wait := s.cancelLoop(wsBox1)
+ waitClosed(t, c.closed, 10*time.Second, "the client's socket")
+ waitClosed(t, ac.closed, 10*time.Second, "the app's socket")
+ wait()
+ waitOpen(t, s.hub, old, 0, "the lost connection")
+ s.startLoop(wsBox1, wsBox1, fwdBox1Tok)
+ s.waitChannel(t, wsBox1, old, e2eReconnectBound)
+ c2, _ := s.openShop(t)
+ c2.echo(t, "after the loop restarted")
+ c2.ws.Close()
+ })
+
+ t.Run("case12_no_leaks", func(t *testing.T) { s.noLeaks(t) })
+
+ t.Run("case15_revocation", func(t *testing.T) { s.revocations(t) })
+
+ t.Run("case14_request_budget", func(t *testing.T) {
+ if baseHub != 0 || baseBox != 0 {
+ t.Logf("note: plain requests cost hub %d and box %d store calls", baseHub, baseBox)
+ }
+ if dh, db := s.hubStore.n.Load()-markHub, s.boxStore.n.Load()-markBox; dh != 0 || db != 0 {
+ t.Fatalf("the upgrade sub-tests made %d hub and %d box store calls, want 0", dh, db)
+ }
+ })
+}
+
+// readerConn replays what a bufio.Reader over-read before the conn.
+type readerConn struct {
+ net.Conn
+ r io.Reader
+}
+
+func (c *readerConn) Read(p []byte) (int, error) { return c.r.Read(p) }
+
+// setBoxToken rotates a fleet box's token hash and reads it back.
+func setBoxToken(t *testing.T, reg *registry.Registry, fleet, label, hash string) {
+ t.Helper()
+ if err := reg.SetFleetBoxToken(fleet, label, hash); err != nil {
+ t.Fatal(err)
+ }
+ if got := fleetBox(t, reg, fleet, label).TokenHash; got != hash {
+ t.Fatalf("read back: %s/%s token hash %q, want %q", fleet, label, got, hash)
+ }
+}
+
+// setBoxStatus sets a fleet box's status and reads it back.
+func setBoxStatus(t *testing.T, reg *registry.Registry, fleet, label, status string) {
+ t.Helper()
+ if err := reg.SetFleetBoxStatus(fleet, label, status); err != nil {
+ t.Fatal(err)
+ }
+ if got := fleetBox(t, reg, fleet, label).Status; got != status {
+ t.Fatalf("read back: %s/%s status %q, want %q", fleet, label, got, status)
+ }
+}
+
+func fleetBox(t *testing.T, reg *registry.Registry, fleet, label string) registry.FleetBox {
+ t.Helper()
+ boxes, err := reg.ListFleetBoxes(fleet)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, b := range boxes {
+ if b.Label == label {
+ return b
+ }
+ }
+ t.Fatalf("fleet %s has no box %s", fleet, label)
+ return registry.FleetBox{}
+}
+
+// waitServing waits for the shop's socket to open again through the hub
+// (a box re-dialing after a revocation, whose backoff may have grown).
+func (s *wsScene) waitServing(t *testing.T, within time.Duration) {
+ t.Helper()
+ cookie := gate.Mint(wsHost, s.hash, time.Now().Add(time.Hour))
+ deadline := time.Now().Add(within)
+ for {
+ if s.hub.tunnels.channel(wsBox1) != nil {
+ h := s.sendHandshake(t, s.addr, wsHost, "/cable", cookie, "websocket")
+ resp, err := http.ReadResponse(h.br, nil)
+ h.conn.Close()
+ if err == nil && resp.StatusCode == http.StatusSwitchingProtocols {
+ waitOpen(t, s.hub, s.channel(t, wsBox1), 0, "after the serving probe")
+ return
+ }
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("the shop's socket did not open again within %s", within)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// noLeaks is spec §8.2 case 12: 200 failed attempts on one channel at the
+// production cap, mixing every terminal path; the channel's count is 0
+// after each; two paths asserted by their first releaser; then a
+// successful upgrade on the same channel.
+func (s *wsScene) noLeaks(t *testing.T) {
+ if s.hub.tunnels.upgradeCap != tunnelUpgradeCap || tunnelUpgradeCap != 128 {
+ t.Fatalf("the hub's cap is %d (const %d), want the production 128", s.hub.tunnels.upgradeCap, tunnelUpgradeCap)
+ }
+ cookie := s.cookie(t, wsHost)
+ tc := s.channel(t, wsBox1)
+ cycle := []string{"no cookie", "404", "malformed 101", "wrong Upgrade", "long token", "client gone"}
+ special := map[int]string{40: "channel killed", 140: "channel killed", 70: "ModifyResponse fails", 100: "Hijack not supported", 130: "no Hijack"}
+ tally := map[string]int{}
+ for i := range 200 {
+ kind, ok := special[i]
+ if !ok {
+ kind = cycle[i%len(cycle)]
+ }
+ tally[kind]++
+ what := fmt.Sprintf("attempt %d (%s)", i, kind)
+ switch kind {
+ case "no cookie":
+ wantStatus(t, s.handshake(t, wsHost, "/cable", ""), http.StatusUnauthorized, what)
+ case "404":
+ wantStatus(t, s.handshake(t, wsHost, "/missing", cookie), http.StatusNotFound, what)
+ case "malformed 101":
+ wantStatus(t, s.handshake(t, wsRawHost, "/malformed", ""), http.StatusBadGateway, what)
+ case "wrong Upgrade":
+ wantStatus(t, s.handshake(t, wsRawHost, "/wrongup", ""), http.StatusBadGateway, what)
+ case "long token":
+ h := s.sendHandshake(t, s.addr, wsHost, "/cable", cookie, strings.Repeat("w", tunnelclient.MaxUpgradeTokenLen+1))
+ h.read(t)
+ wantStatus(t, h, http.StatusBadGateway, what)
+ case "client gone":
+ h := s.sendHandshake(t, s.addr, wsRawHost, "/hang", "", "websocket")
+ s.waitArrived(t, what)
+ h.conn.Close()
+ case "channel killed":
+ h := s.sendHandshake(t, s.addr, wsRawHost, "/hang", "", "websocket")
+ s.waitArrived(t, what)
+ s.hub.tunnels.CloseChannel(wsBox1)
+ h.read(t)
+ wantStatus(t, h, http.StatusBadGateway, what)
+ waitOpen(t, s.hub, tc, 0, what+": the killed connection")
+ tc = s.waitChannel(t, wsBox1, tc, e2eReconnectBound)
+ case "ModifyResponse fails":
+ s.modifyResponseFails(t, cookie, what)
+ case "Hijack not supported":
+ s.hijackNotSupported(t, cookie, what)
+ case "no Hijack":
+ s.noHijack(t, cookie, what)
+ }
+ waitOpen(t, s.hub, tc, 0, what)
+ }
+ t.Logf("case 12 attempts by path: %v", tally)
+ c, _ := s.openShop(t)
+ c.echo(t, "after 200 failures")
+ c.ws.Close()
+ waitOpen(t, s.hub, tc, 0, "after the successful upgrade")
+}
+
+func (s *wsScene) waitArrived(t *testing.T, what string) {
+ t.Helper()
+ select {
+ case <-s.raw.arrived:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("%s: the handshake did not reach the box within 5 s", what)
+ }
+}
+
+// modifyResponseFails: the scene's own fleetProxy for wsHost, with only its
+// ModifyResponse replaced by one that refuses the 101, and its error
+// handler wrapped to look before it answers. The proxy closes the 101's
+// body before calling the handler (reverseproxy.go:395-397), so from
+// inside it the reservation is already released, by the body.
+func (s *wsScene) modifyResponseFails(t *testing.T, cookie, what string) {
+ t.Helper()
+ // Reload installs the fleetProxy inside assetScrubbedProxy.
+ sp, ok := s.hub.current()[wsHost].proxy.(assetScrubbedProxy)
+ if !ok {
+ t.Fatalf("%s's proxy is %T", wsHost, s.hub.current()[wsHost].proxy)
+ }
+ rp := sp.proxy
+ s.drainInserted()
+ prodEH := rp.ErrorHandler
+ var inside atomic.Int32
+ inside.Store(-1)
+ rp.ModifyResponse = func(*http.Response) error { return errModifyFailed }
+ rp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
+ if errors.Is(err, errModifyFailed) {
+ select {
+ case res := <-s.inserted:
+ inside.Store(int32(res.firstReleaser()))
+ default:
+ }
+ }
+ prodEH(w, r, err)
+ }
+ s.channel(t, wsBox1) // orders the writes above before the serving goroutine's reads (TunnelHub.mu)
+ h := s.handshake(t, wsHost, "/cable", cookie)
+ wantStatus(t, h, http.StatusBadGateway, what)
+ if got := releaser(inside.Load()); got != relBody {
+ t.Fatalf("%s: from inside the error handler the first releaser is %d, want relBody (%d)", what, got, relBody)
+ }
+ // A fresh map, with a fresh proxy.
+ if err := s.hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// openWrapped sends the shop's handshake to the wrapping server in mode
+// and waits for the hub to return inside it, the barrier still held.
+func (s *wsScene) openWrapped(t *testing.T, cookie string, mode int32, what string) (hs, chan struct{}, *upgradeReservation, *appConn) {
+ t.Helper()
+ s.drainInserted()
+ s.app.drainOpened()
+ barrier := make(chan struct{})
+ s.wrapBarrier.Store(&barrier)
+ s.wrapMode.Store(mode)
+ h := s.sendHandshake(t, s.wrapAddr, wsHost, "/cable", cookie, "websocket")
+ res := s.nextInserted(t)
+ select {
+ case <-s.wrapReturned:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("%s: the hub did not return within 5 s", what)
+ }
+ return h, barrier, res, s.app.nextOpened(t, wsHost)
+}
+
+// hijackNotSupported: the hub behind a writer whose Hijack answers
+// http.ErrNotSupported, which countingWriter and slotWriter pass through
+// unchanged; the proxy returns before installing its body closer
+// (reverseproxy.go:854-857), so only the backstop releases.
+func (s *wsScene) hijackNotSupported(t *testing.T, cookie, what string) {
+ t.Helper()
+ tc := s.channel(t, wsBox1)
+ h, barrier, res, ac := s.openWrapped(t, cookie, wrapNotSupported, what)
+ if n, _ := openCount(s.hub, tc); n != 1 {
+ t.Fatalf("%s: with the request live the count is %d, want 1", what, n)
+ }
+ if got := res.firstReleaser(); got != relNone {
+ t.Fatalf("%s: with the request live the reservation was released by %d", what, got)
+ }
+ close(barrier)
+ h.read(t)
+ wantStatus(t, h, http.StatusBadGateway, what)
+ waitOpen(t, s.hub, tc, 0, what)
+ if got := res.firstReleaser(); got != relBackstop {
+ t.Fatalf("%s: the first releaser is %d, want relBackstop (%d)", what, got, relBackstop)
+ }
+ waitClosed(t, ac.closed, 2*time.Second, what+": the app's socket")
+}
+
+// noHijack: a writer with no Hijack at all. slotWriter's Hijack then
+// answers its own error, not http.ErrNotSupported, so the proxy installs
+// its body closer and closes the 101's body as it returns: the body
+// releases, while the request is still live.
+func (s *wsScene) noHijack(t *testing.T, cookie, what string) {
+ t.Helper()
+ tc := s.channel(t, wsBox1)
+ h, barrier, res, ac := s.openWrapped(t, cookie, wrapNoHijack, what)
+ deadline := time.Now().Add(2 * time.Second)
+ for res.firstReleaser() == relNone {
+ if time.Now().After(deadline) {
+ t.Fatalf("%s: not released within 2 s of the hub returning", what)
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if got := res.firstReleaser(); got != relBody {
+ t.Fatalf("%s: the first releaser is %d, want relBody (%d)", what, got, relBody)
+ }
+ close(barrier)
+ h.read(t)
+ wantStatus(t, h, http.StatusBadGateway, what)
+ waitOpen(t, s.hub, tc, 0, what)
+ waitClosed(t, ac.closed, 2*time.Second, what+": the app's socket")
+}
+
+// revocations is spec §8.2 case 15: on an account plans do not govern, a
+// change to what admitted an open socket closes it at both ends, after a
+// direct Reload within 2 s and with Watch on its real 2 s tick within 5 s
+// of the write; a new handshake is refused; the change undone, it opens
+// again.
+func (s *wsScene) revocations(t *testing.T) {
+ s.hub.SetPlanGovernedFor(nil)
+ for _, rv := range []struct {
+ name, host string
+ revoke func(t *testing.T)
+ restore func(t *testing.T)
+ }{
+ {"owner change", wsHost,
+ func(t *testing.T) { setFleetOwner(t, s.hub, "home", fwdOther) },
+ func(t *testing.T) { setFleetOwner(t, s.hub, "home", fwdOwner) }},
+ {"moved to away", wsHost,
+ func(t *testing.T) { s.putForward(t, wsForward(wsHost, "away", wsWideRate)) },
+ func(t *testing.T) { s.putForward(t, wsForward(wsHost, "home", wsWideRate)) }},
+ {"deleted", wsHost,
+ func(t *testing.T) {
+ if ok, err := s.hubReg.DeleteForward(wsHost); err != nil || !ok {
+ t.Fatalf("DeleteForward: %v, %v", ok, err)
+ }
+ if rt, err := s.hubReg.Get(wsHost); err != nil || rt != nil {
+ t.Fatalf("read back: %+v, %v; want no row", rt, err)
+ }
+ },
+ func(t *testing.T) { s.putForward(t, wsForward(wsHost, "home", wsWideRate)) }},
+ {"-tunnel row re-pointed", wsTunnelHost,
+ func(t *testing.T) { s.pointTunnel(t, "t2") },
+ func(t *testing.T) { s.pointTunnel(t, "t1") }},
+ } {
+ for _, watch := range []bool{false, true} {
+ name := rv.name + map[bool]string{false: ", direct Reload", true: ", Watch"}[watch]
+ t.Run(name, func(t *testing.T) {
+ cookie := s.cookie(t, rv.host)
+ c, ac := s.openCable(t, rv.host, cookie)
+ c.next(t) // welcome
+ c.subscribe(t)
+ c.echo(t, "before the revocation")
+ var stopWatch func()
+ if watch {
+ stop, done := make(chan struct{}), make(chan struct{})
+ go func() { defer close(done); s.hub.Watch(stop) }()
+ stopWatch = func() { close(stop); <-done }
+ defer func() {
+ if stopWatch != nil {
+ stopWatch()
+ }
+ }()
+ }
+ rv.revoke(t)
+ bound := 5 * time.Second
+ if !watch {
+ if err := s.hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ bound = 2 * time.Second
+ }
+ waitClosed(t, c.closed, bound, "the client's socket")
+ waitClosed(t, ac.closed, bound, "the app's socket")
+ before := len(s.app.seenFor(rv.host))
+ h := s.handshake(t, rv.host, "/cable", cookie)
+ if h.resp.StatusCode == http.StatusSwitchingProtocols {
+ t.Fatal("a new handshake after the revocation got a 101")
+ }
+ if n := len(s.app.seenFor(rv.host)); n != before {
+ t.Fatalf("the app saw %d requests after the revocation, want none", n-before)
+ }
+ t.Logf("the refused handshake: %d", h.resp.StatusCode)
+ if stopWatch != nil {
+ stopWatch()
+ stopWatch = nil
+ }
+ rv.restore(t)
+ if err := s.hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ // Control: undone, the same handshake opens a socket.
+ c2, _ := s.openCable(t, rv.host, cookie)
+ c2.next(t)
+ c2.subscribe(t)
+ c2.echo(t, "after the restore")
+ c2.ws.Close()
+ })
+ }
+ }
+}
+
+func (s *wsScene) putForward(t *testing.T, rt registry.Route) {
+ t.Helper()
+ if err := s.hubReg.PutForward(rt); err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.hubReg.Get(rt.Host)
+ if err != nil || got == nil || got.Region != rt.Region {
+ t.Fatalf("read back %s: %+v, %v; want region %q", rt.Host, got, err, rt.Region)
+ }
+}
+
+func (s *wsScene) pointTunnel(t *testing.T, channel string) {
+ t.Helper()
+ if err := s.hubReg.Upsert(wsTunnelRow(channel)); err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.hubReg.Get(wsTunnelHost)
+ if err != nil || got == nil || got.Tunnel != channel {
+ t.Fatalf("read back %s: %+v, %v; want tunnel %q", wsTunnelHost, got, err, channel)
+ }
+}
+
+// TestTrustedChildIsNeeded is the trusted child's negative control: the
+// same scene in a child that trusts an unrelated CA never connects, and
+// the box's log shows why. Verification is on; the fixture CA is what the
+// witnesses' loops trust, not a bypass.
+func TestTrustedChildIsNeeded(t *testing.T) {
+ child, fx := runChild(t, true)
+ if !child {
+ return
+ }
+ s := newWSScene(t, fx)
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if s.hub.tunnels.State(wsBox1) == "connected" {
+ t.Fatalf("%s connected while its loop trusts an unrelated CA", wsBox1)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ if !s.logs.contains("x509: certificate signed by unknown authority") {
+ t.Fatal("the box's log does not show the certificate refused")
+ }
+}