carlos / platform Public

edge: a -tunnel login passes through only when next selects the tunnel row (#471 Task 6 fix round 2)

Astra re-review 1, P1: loginPassesThrough decided before `next` was
resolved, and static -tunnel rows keep hub prefix maps, so the password
for a gated prefix target could go down the front's tunnel. Ruling: a
login reaches the route whose gate rendered its form. The hub now
resolves `next` for every non-forward login as before; for an ungated
ArmTunnel front it reads the body bounded by gate.MaxFormBody, keeps the
bytes, and hands them on down the tunnel only when the selected route is
that front row itself (loginPassesThrough(front, target)). A gated
target's gate judges at the hub; an ungated non-forward target is 404.

Test-first: tunnel_login_test.go reproduces the misroute (the target's
password reached the front's box, 200) and now asserts the target-signed
cookie with nothing reaching the box; a login whose next selects an
ungated docs prefix is 404; next on the front passes with its body
intact. M18: a hub-gated -tunnel front whose prefix target has another
password signs the cookie for the target.

P2: closedBy judges each endpoint's recorded close time against the one
deadline, so work between the trigger and the check cannot pass a late
close.

Spec §4.5 and §7 (Task 6's card: reads Edge.ServeHTTP +file:ReadAll
+registry:Gate +whole:Route; new loginPassesThrough; seal unchanged).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 12e5531d62e097046407b539a03b7e64c03c5979 parent 021c730
4 files changed, +297 −55
  • docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md +24 −15
  • internal/edge/edge.go +39 −14
  • internal/edge/tunnel_login_test.go +190 −0
  • internal/edge/tunnel_ws_e2e_test.go +44 −26

Intent

Human

<task-notification> <task-id>a58070cdd3a43a333</task-id> <tool-use-id>toolu_01MhMZNoxBU3pV9t79eynSKx</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a58070cdd3a43a333.output</output-file> <status>completed</status> <summary>Agent "#471 Task 6: production-wired witness" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE_WITH_CONCERNS **Commit:** `021c7307` on `design-tunnel-websockets-471`, on top of `eef20b79`. Not pushed. It holds the production fix, the three test fixes, and the spec changes to §4.5 and §7. **Tests:** the e2e cases pass under `-race` with no data races. The edge login, gate and neighbouring tests pass, and so do the darwin, windows and linux/arm64 builds. What changed for each finding: 1. **Case 2b (your ruling):** restored as the brief states, with the gate only on the box's row; before the fix it failed with a 404 on the login. A login to an ungated `-tunnel` row on the hub now passes down the tunnel to the box, as a forward row's does. A `-tunnel` row gated at the hub still judges the login itself, and an ungated ordinary row still answers 404; both are now extra sub-tests. 2. **Connection matching:** each handshake carries a unique id in its query, and the test waits for the app socket with that id. 3. **Closure bounds:** both endpoints must close before one deadline taken at the trigger. Earlier mutations still fail the cases against the new check. 4. **Trusted child:** it now runs under the parent test's deadline, gets its own `-test.timeout`, is killed and reaped on any abnormal exit, and a scanner error fails the test. With a 26 s parent timeout the child timed out after 6 s, the parent failed, and no `edge.test` process was left. **Concerns:** - **One mutation survives.** Letting every `-tunnel` row pass its login through, gated at the hub or not, changes nothing visible here. The hub's gate still recognises and judges the login POST, so behaviour only differs on a host with prefix routes, and the scene has none. The hub-gated case does confirm the hub judges the login: if the login crossed the tunnel, the box's ungated row would answer 404. - **The census card changed.** `Edge.ServeHTTP` now shows a `sites` row (`-whole:Route`), because the forward-row check moved into the new helper. `loginPassesThrough` is a new unit (`+registry:Gate`, `+whole:Route` x2). The seal is unchanged. It is written into spec §7 as earlier tasks did; there is no approval request and no overlay until Task 9. The fix report is appended to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-tunnel-websockets-471/.superpowers/sdd/2026-10-30-tunnel-websockets/task-6-report.md`, with your ruling recorded. Scratch is removed and no processes are left running.</result> <usage><subagent_tokens>372747</subagent_tokens><tool_uses>26</tool_uses><duration_ms>574803</duration_ms></usage> </task-notification>

Human

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

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

diff --git a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
index 8d2c8f3ff..93ae14191 100644
--- a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
+++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
@@ -526,7 +526,7 @@ passes it; the box's `gate.Admit` runs before the box's upgrade branch
(`edge.go:2083-2104`) and strips it. A handshake without it gets the
gate's answer as an ordinary response (§4.3, last paragraph), never a
101. The witness logs in through the hub and then upgrades.
-The tunnel arm now passes the login through as well: a `POST /.carlos/gate` to an ungated `-tunnel` row goes down the tunnel to the box as a forward row's does (`loginPassesThrough`, Task 6 fix round 1), and a `-tunnel` row gated at the hub still judges the login itself.
+The tunnel arm now passes the login through too, but only when the login's target is the tunnel row itself: the hub resolves `next` as for any gated host, and a `POST /.carlos/gate` goes down the tunnel to the box only when `next` selects that ungated `-tunnel` row (`loginPassesThrough`, Task 6 fix rounds 1 and 2); a prefix target's gate judges its own login at the hub, an ungated non-tunnel target answers 404, and a `-tunnel` row gated at the hub judges its login itself.
### 4.6 One enforcement point, and `CloseAccountUpgrades` on a real socket
@@ -1073,20 +1073,29 @@ changed, and why the card has no row for it:
The seal is unchanged.
-Task 6's card (fix round 1, the controller's ruling that a `-tunnel`
-row's login passes through, §4.5) changes two rows from Task 5's:
-
-- `sites` `Edge.ServeHTTP`, `-whole:Route`: the `loginPost` expression
- no longer calls `up.route.IsForward()` itself; it calls
- `loginPassesThrough(up)`.
-- `new` `loginPassesThrough` (edge.go): `+registry:Gate`,
- `+whole:Route` x2. It decides, from the route row and the tenancy
- `Reload` already put on the entry, that a login POST to a forward row
- (as before) or to an ungated `ArmTunnel` row is not this hub's to
- judge, so it is proxied down the tunnel unparsed. Serving only: no
- file, no root-owned state, nothing opened or followed; a row gated at
- the hub still judges the login here, and every other ungated row still
- answers 404.
+Task 6's card (fix rounds 1 and 2: the controller's rulings that a
+login for an ungated `-tunnel` row passes through to its box, and only
+when `next` selects that row itself, §4.5) changes two rows from Task
+5's:
+
+- `reads` `Edge.ServeHTTP`: `+file:ReadAll`, `+registry:Gate`,
+ `+whole:Route`. For a login POST arriving on an ungated `ArmTunnel`
+ row, the hub reads the request body itself (bounded by
+ `gate.MaxFormBody`, the same bound the gated path applies, a 413 past
+ it), parses it to resolve `next` exactly as for any gated host, and
+ keeps the bytes. The `ReadAll` is of the visitor's request body, not a
+ file; the `Gate` and `Route` reads are of the entry `Reload` already
+ built. The kept bytes are handed on intact only when the pass-through
+ below holds; otherwise the login goes on as before (a gated target's
+ gate judges it here, an ungated non-forward target answers 404).
+- `new` `loginPassesThrough(front, target)` (edge.go): `+registry:Gate`
+ x2, `+registry:Host` x2, `+whole:Route` x4. True only when `front` is
+ an ungated `ArmTunnel` row and `target`, the route `next` selected, is
+ that same row (same host, same tenancy, still ungated). So a login
+ reaches the route whose gate rendered its form: a prefix to another
+ app is never sent down the front's tunnel (Astra Task 6 re-review 1,
+ P1). Serving only: no file, no root-owned state, nothing opened or
+ followed, no new channel or account selectable.
The other rows (`reads` `Edge.Reload`; the two `new` tunnelclient `Read`
units) and the seal are unchanged. No overlay is proposed here (Task 9).
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index d245243e0..93ee63501 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -20,6 +20,7 @@ import (
"github.com/carlosframework/platform/internal/cliflag"
"bufio"
+ "bytes"
"context"
"crypto/ed25519"
"crypto/tls"
@@ -2020,15 +2021,30 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// here anyway), and the ungated-route 404 below does not fire: the POST
// reaches the fleet edge with its body and Content-Length intact.
//
- // The same holds for an UNGATED static -tunnel row (#471 spec §4.5):
- // its gate, if it has one, is the box's, on the box's own row, so the
- // hub passes the login down the tunnel like any other request and the
- // box judges it. A -tunnel row gated here is unchanged: this hub renders
- // the form and judges the password itself (loginPassesThrough).
+ // An UNGATED static -tunnel row is different (#471 spec §4.5): its gate,
+ // if it has one, is its box's, so a login for that row goes down the
+ // tunnel. But such a row keeps its prefix map here, and a prefix may
+ // select another app, whose gate rendered the form. So the login is
+ // resolved by `next` first, like any other, and passed down the tunnel
+ // only when `next` selects the -tunnel row itself (loginPassesThrough):
+ // a login reaches the route whose gate rendered its form. Its bounded
+ // body is kept for that, and handed on intact.
loginPost := r.Method == http.MethodPost && r.URL.Path == gate.LoginPath &&
- !loginPassesThrough(up)
+ !up.route.IsForward()
if loginPost {
- r.Body = http.MaxBytesReader(w, r.Body, gate.MaxFormBody)
+ front := up
+ var kept []byte
+ if front.tenancy.Arm == ArmTunnel && front.route.Gate == "" {
+ b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, gate.MaxFormBody))
+ if err != nil {
+ http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge)
+ return
+ }
+ kept = b
+ r.Body = io.NopCloser(bytes.NewReader(b))
+ } else {
+ r.Body = http.MaxBytesReader(w, r.Body, gate.MaxFormBody)
+ }
if err := r.ParseForm(); err != nil {
http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge)
return
@@ -2056,6 +2072,12 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if target, hit := e.lookupUpstreamPath(host, lookupPath); hit {
up = target
}
+ if kept != nil && loginPassesThrough(front, up) {
+ loginPost = false
+ r.Body = io.NopCloser(bytes.NewReader(kept))
+ r.ContentLength = int64(len(kept))
+ r.Form, r.PostForm = nil, nil
+ }
}
// The door's scope, checked against the FINAL upstream: after the login
@@ -3324,13 +3346,16 @@ func tunnelProxy(name string, hub *TunnelHub) *httputil.ReverseProxy {
}
}
-// loginPassesThrough reports whether a login POST to up is not this edge's
-// to judge and goes on to the box behind it, body intact: a forward row
-// (the fleet edge holds the gate; fleet public routes spec §4.8), or a
-// static -tunnel row with no gate here (#471 spec §4.5: the box holds it).
-// The arm is the tenancy Reload gave the entry, the one shared decision.
-func loginPassesThrough(up upstream) bool {
- return up.route.IsForward() || (up.tenancy.Arm == ArmTunnel && up.route.Gate == "")
+// loginPassesThrough reports whether a login POST that arrived on front, an
+// ungated static -tunnel row, and whose `next` selected target, goes down
+// front's tunnel to the box that holds the gate (#471 spec §4.5): only when
+// target is front itself, the same row under the same tenancy, still
+// ungated here. A prefix target (another app, gated or not) is never
+// passed: its gate at the hub judges it, or it answers 404. The arm is
+// the tenancy Reload gave the entry, the one shared decision.
+func loginPassesThrough(front, target upstream) bool {
+ return front.tenancy.Arm == ArmTunnel && front.route.Gate == "" &&
+ target.route.Host == front.route.Host && target.tenancy == front.tenancy && target.route.Gate == ""
}
// tunnelUpgradeError answers the tunnel transport's upgrade refusals for
diff --git a/internal/edge/tunnel_login_test.go b/internal/edge/tunnel_login_test.go
new file mode 100644
index 000000000..082320565
--- /dev/null
+++ b/internal/edge/tunnel_login_test.go
@@ -0,0 +1,190 @@
+package edge
+
+// A login POST on a static -tunnel row (#471 spec §4.5, Task 6 fix rounds
+// 1 and 2). The invariant: a login reaches the route whose gate rendered
+// its form. The hub resolves `next` against the host's routes, as it does
+// for any gated host, and passes the POST down the tunnel only when the
+// route `next` selects is the ungated -tunnel row itself, whose box holds
+// the gate. A gated target is judged by its own gate at the hub; an
+// ungated target that is not that tunnel row answers 404.
+//
+// The scene: front.example.com is a -tunnel row on the static channel t1,
+// whose box (a recorder) is dialed in by the real tunnelclient loop; its
+// prefix "paulca" selects gated.example.com (gated at the hub, its own
+// password) and its prefix "docs" selects docs.example.com (ungated, not
+// a tunnel row).
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const (
+ tlFront = "front.example.com"
+ tlTarget = "gated.example.com"
+ tlDocs = "docs.example.com"
+
+ tlFrontPass = "front password"
+ tlTargetPass = "target password"
+)
+
+// boxRecorder is the box behind t1: it records every request and its body.
+type boxRecorder struct {
+ mu sync.Mutex
+ seen []string // "METHOD path body"
+}
+
+func (b *boxRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ b.mu.Lock()
+ b.seen = append(b.seen, r.Method+" "+r.URL.Path+" "+string(body))
+ b.mu.Unlock()
+ io.WriteString(w, "the front box")
+}
+
+func (b *boxRecorder) take() []string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ out := b.seen
+ b.seen = nil
+ return out
+}
+
+// tunnelLoginScene builds the hub. frontGate is the -tunnel row's own gate
+// at the hub ("" for none). It returns the server, the two hashes, the box
+// recorder and how many requests docs.example.com's app saw.
+func tunnelLoginScene(t *testing.T, frontGate bool) (srv *httptest.Server, frontHash, targetHash string, box *boxRecorder, docsSeen *string) {
+ t.Helper()
+ target, _ := cookieEchoBackend(t, "the target app")
+ docs, docsSeen := hostEchoBackend(t, "the docs app")
+ var err error
+ if targetHash, err = gate.Hash(tlTargetPass); err != nil {
+ t.Fatal(err)
+ }
+ if frontHash, err = gate.Hash(tlFrontPass); err != nil {
+ t.Fatal(err)
+ }
+ reg := openReg(t)
+ for _, rt := range []registry.Route{
+ {Host: tlFront, Kind: "instance", Status: "ready", Tunnel: "t1", Account: fwdOwner, App: "front"},
+ {Host: tlTarget, Kind: "service", Status: "ready", Addr: target.Listener.Addr().String(), Gate: targetHash},
+ {Host: tlDocs, Kind: "service", Status: "ready", Addr: docs.Listener.Addr().String()},
+ } {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if frontGate {
+ if err := reg.SetGate(tlFront, frontHash); err != nil {
+ t.Fatal(err)
+ }
+ }
+ upsertPath(t, reg, tlFront, "paulca", tlTarget)
+ upsertPath(t, reg, tlFront, "docs", tlDocs)
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ srv = httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ u, err := url.Parse(srv.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ e.EnableTunnels(NewTunnelHub(u.Hostname(), map[string]string{"t1": fwdT1Tok}))
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if up, ok := e.lookupUpstreamPath(tlFront, "/"); !ok || up.tenancy.Arm != ArmTunnel {
+ t.Fatalf("%s is served %v under %+v, want the -tunnel arm", tlFront, ok, up.tenancy)
+ }
+ box = &boxRecorder{}
+ stop := startFakeRemoteHost(t, srv.URL, "t1", fwdT1Tok, box)
+ t.Cleanup(stop)
+ waitForTunnelState(t, e.tunnels, "t1", "connected", e2eReconnectBound)
+ return srv, frontHash, targetHash, box, docsSeen
+}
+
+// wantCookieFor checks resp is the gate's 303 to next with a cookie signed
+// for host under hash.
+func wantCookieFor(t *testing.T, resp *http.Response, next, host, hash, what string) {
+ t.Helper()
+ if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != next {
+ t.Fatalf("%s: %d -> %q, want 303 -> %s", what, resp.StatusCode, resp.Header.Get("Location"), next)
+ }
+ c := gateCookie(resp)
+ if c == "" || !gate.Verify(c, host, hash, time.Now()) {
+ t.Fatalf("%s: cookie %q does not verify for %s", what, c, host)
+ }
+}
+
+// P1 (Astra re-review 1): an ungated -tunnel front row with a prefix to a
+// gated app. The target's password, posted from the target's own form,
+// is judged at the hub by the target's gate; it never goes down the
+// front's tunnel. A login whose next selects an ungated route that is not
+// the tunnel row is a 404 that reaches nothing. Control: a login whose
+// next selects the front itself goes down the tunnel to its box, body
+// intact.
+func TestUngatedTunnelFrontLoginReachesTheGateThatRenderedIt(t *testing.T) {
+ srv, _, targetHash, box, docsSeen := tunnelLoginScene(t, false)
+
+ resp := doHost(t, srv, http.MethodGet, tlFront, "/paulca/x", "")
+ if b, _ := io.ReadAll(resp.Body); resp.StatusCode != http.StatusUnauthorized || !strings.Contains(string(b), tlTarget) {
+ t.Fatalf("GET /paulca/x: %d, want the target's 401 form", resp.StatusCode)
+ }
+ if got := box.take(); len(got) != 0 {
+ t.Fatalf("the front's box saw %q for the target's prefix", got)
+ }
+
+ wantCookieFor(t, postLogin(t, srv, tlFront, tlTargetPass, "/paulca/x"), "/paulca/x", tlTarget, targetHash,
+ "the target's password with next on its prefix")
+ if got := box.take(); len(got) != 0 {
+ t.Fatalf("the target's password went down the front's tunnel: the box saw %q", got)
+ }
+
+ if resp := postLogin(t, srv, tlFront, tlTargetPass, "/docs/x"); resp.StatusCode != http.StatusNotFound {
+ t.Fatalf("a login whose next selects the ungated docs route: %d, want 404", resp.StatusCode)
+ }
+ if got := box.take(); len(got) != 0 || *docsSeen != "" {
+ t.Fatalf("a login to the ungated docs route reached the box %q or the docs app %q", got, *docsSeen)
+ }
+
+ // Control: next selects the front row itself, whose gate is its box's.
+ for _, next := range []string{"/", "/elsewhere"} {
+ form := url.Values{"password": {tlFrontPass}, "next": {next}}.Encode()
+ resp := postLogin(t, srv, tlFront, tlFrontPass, next)
+ if b, _ := io.ReadAll(resp.Body); resp.StatusCode != http.StatusOK || string(b) != "the front box" {
+ t.Fatalf("a login for the front with next %q: %d %q, want the box's answer", next, resp.StatusCode, b)
+ }
+ if got := box.take(); len(got) != 1 || got[0] != "POST "+gate.LoginPath+" "+form {
+ t.Fatalf("the box saw %q, want the login POST with its body intact (%q)", got, form)
+ }
+ }
+}
+
+// M18 (Astra re-review 1): a -tunnel front row gated at the hub, whose
+// prefix selects a gated target with another password. The target's
+// password with next on the prefix gets a cookie signed for the target:
+// the hub resolved next, and the target's gate judged it. Control: the
+// front's own password with next on the front gets the front's cookie.
+// Neither goes down the tunnel.
+func TestHubGatedTunnelFrontPrefixLoginIsJudgedByItsTarget(t *testing.T) {
+ srv, frontHash, targetHash, box, _ := tunnelLoginScene(t, true)
+ wantCookieFor(t, postLogin(t, srv, tlFront, tlTargetPass, "/paulca/x"), "/paulca/x", tlTarget, targetHash,
+ "the target's password with next on its prefix")
+ wantCookieFor(t, postLogin(t, srv, tlFront, tlFrontPass, "/"), "/", tlFront, frontHash,
+ "control: the front's password with next on the front")
+ if got := box.take(); len(got) != 0 {
+ t.Fatalf("a login on a hub-gated -tunnel row went down the tunnel: the box saw %q", got)
+ }
+}
diff --git a/internal/edge/tunnel_ws_e2e_test.go b/internal/edge/tunnel_ws_e2e_test.go
index fc89e1ed5..182a183b1 100644
--- a/internal/edge/tunnel_ws_e2e_test.go
+++ b/internal/edge/tunnel_ws_e2e_test.go
@@ -114,6 +114,8 @@ type appConn struct {
ws *websocket.Conn
raw net.Conn // the accepted connection under ws
closed chan struct{}
+ // closedAt is when the app's end ended, set before closed closes.
+ closedAt time.Time
mu sync.Mutex
id string
@@ -187,6 +189,7 @@ func (a *cableApp) serve(ws *websocket.Conn) {
a.mu.Lock()
delete(a.conns, c)
a.mu.Unlock()
+ c.closedAt = time.Now()
close(c.closed)
}()
if id := r.URL.Query().Get(wsIDParam); id != "" {
@@ -994,6 +997,9 @@ type cableClient struct {
frames chan string // every frame but pings, in order
pings atomic.Int32
closed chan struct{}
+ // closedAt is when the client saw its socket end, set before closed
+ // closes.
+ closedAt time.Time
}
// openCable opens a socket to host through the hub with x/net/websocket
@@ -1021,7 +1027,10 @@ func (s *wsScene) openCable(t *testing.T, host, cookie string) (*cableClient, *a
}
c := &cableClient{ws: ws, frames: make(chan string, 1024), closed: make(chan struct{})}
go func() {
- defer close(c.closed)
+ defer func() {
+ c.closedAt = time.Now()
+ close(c.closed)
+ }()
for {
var f string
if err := websocket.Message.Receive(ws, &f); err != nil {
@@ -1083,40 +1092,49 @@ func (c *cableClient) echo(t *testing.T, text string) {
}
// closedBy requires the client's end c and the app's end ac (either may be
-// nil) to have closed before deadline: one bound, taken at the trigger, for
-// both.
+// nil) to have closed no later than deadline: one bound, taken at the
+// trigger, for both, judged on each end's recorded close time.
func closedBy(t *testing.T, deadline time.Time, what string, c *cableClient, ac *appConn) {
t.Helper()
timer := time.NewTimer(time.Until(deadline))
defer timer.Stop()
- for _, e := range []struct {
+ type end struct {
name string
ch <-chan struct{}
- set bool
- }{{"the client's socket", chOf(c), c != nil}, {"the app's socket", chOfApp(ac), ac != nil}} {
- if !e.set {
- continue
- }
- select {
- case <-e.ch:
- case <-timer.C:
- t.Fatalf("%s: %s was not closed by the deadline", what, e.name)
- }
+ at func() time.Time
}
-}
-
-func chOf(c *cableClient) <-chan struct{} {
- if c == nil {
- return nil
+ var ends []end
+ if c != nil {
+ ends = append(ends, end{"the client's socket", c.closed, func() time.Time { return c.closedAt }})
}
- return c.closed
-}
-
-func chOfApp(ac *appConn) <-chan struct{} {
- if ac == nil {
- return nil
+ if ac != nil {
+ ends = append(ends, end{"the app's socket", ac.closed, func() time.Time { return ac.closedAt }})
+ }
+ expired := false
+ for _, e := range ends {
+ if !expired {
+ select {
+ case <-e.ch:
+ case <-timer.C:
+ expired = true
+ }
+ }
+ if expired {
+ // The timer and a close may both have been ready; only the
+ // recorded time below decides.
+ select {
+ case <-e.ch:
+ default:
+ t.Fatalf("%s: %s was not closed by the deadline", what, e.name)
+ }
+ }
+ // The close is judged by when it happened, not by when this
+ // check got to it: work between the trigger and this call (a
+ // read, a count wait) cannot let a late close pass.
+ if at := e.at(); at.After(deadline) {
+ t.Fatalf("%s: %s closed %s after the deadline", what, e.name, at.Sub(deadline))
+ }
}
- return ac.closed
}
// notClosed checks ch has not closed.