carlos / platform Public

edge: a registration racing a revocation is not published (#471 Task 4 fix round 1)

Astra's Task 4 review, P1. This was there before this branch: TunnelHub's
registration checked a dynamic channel's credential once, before the
hijack and the h2 setup, and published the connection later without
checking again. A box that authenticated before a detach or rotation
Reload and published after it kept a live, selectable channel that
nothing closed, because a detach leaves the tenancy of its routes
unchanged, so the upgrade sweep keeps them too.

ServeHTTP now checks the credential again under TunnelHub.mu at the
moment it publishes, the lock SetDynamicAuth replaces the set under, so
publication and replacement exclude each other. A refused connection is
closed outside the lock. VerifyDynamic's lookup moves into
verifyDynamicLocked, which both share. TunnelHub.afterAuth is a test
seam, nil in production.

TestRegistrationRacingARevocationIsNotPublished pauses a registration
at the seam, runs a detach (or rotation) and Reload to completion, then
resumes: the channel is not published or selectable and the box's
connection is closed. A control with nothing revoked publishes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 3baa50b5d3bc99a7ec0988ea38302844e72ba326 parent f775474
3 files changed, +193 −3
  • docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md +8 −0
  • internal/edge/tunnel.go +39 −3
  • internal/edge/tunnel_register_race_test.go +146 −0

Intent

Attributed to this commit: 11.9 g CO₂e (841,228 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 50b7da731..c541b01f2 100644
--- a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
+++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
@@ -1035,6 +1035,14 @@ for it:
`reloadMu`, `hooks`, `reloadSeq` and `watchTick` fields, and the two
`reserveUpgrade` seams (`openUpgrades.beforeReserve` and `afterInsert`).
The `internal/edge` envelope re-pin covers them.
+- Fix round 1 (Astra P1, pre-existing): `TunnelHub.ServeHTTP` checks a
+ dynamic channel's credential again under `TunnelHub.mu` as it publishes
+ the connection, and closes a refused one outside the lock;
+ `VerifyDynamic` now does its lookup through `verifyDynamicLocked`, which
+ that check shares; a test seam, `TunnelHub.afterAuth`, nil in
+ production. They read only the in-memory credential set Reload already
+ applies, so the card shows no row for them, and the envelope re-pin
+ covers them.
The seal is unchanged. No overlay is proposed here (Task 9).
diff --git a/internal/edge/tunnel.go b/internal/edge/tunnel.go
index 1f6f808bc..3e30eb333 100644
--- a/internal/edge/tunnel.go
+++ b/internal/edge/tunnel.go
@@ -101,6 +101,11 @@ type TunnelHub struct {
// carry at once: tunnelUpgradeCap, set by NewTunnelHub, so a test can
// lower it on its own hub.
upgradeCap int
+ // afterAuth is a test seam, nil in production: ServeHTTP calls it with
+ // the channel name after the registration has authenticated and the
+ // tunnel's h2 connection is built, just before it publishes the
+ // connection.
+ afterAuth func(name string)
}
func NewTunnelHub(host string, clients map[string]string) *TunnelHub {
@@ -216,7 +221,29 @@ func (h *TunnelHub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn.Close()
return
}
+ if h.afterAuth != nil {
+ h.afterAuth(name)
+ }
h.mu.Lock()
+ // A dynamic channel's credential is checked again here, under h.mu, at
+ // the moment the connection is published. The check above ran before
+ // the hijack and the h2 setup, and a Reload may have replaced the set
+ // since (SetDynamicAuth, under the same lock): a detach or a rotation.
+ // Publishing on the old answer would leave a revoked box with a live,
+ // selectable channel that nothing closes, because a detach does not
+ // change the tenancy of the routes it serves. Under the lock, publish
+ // and replacement exclude each other: a connection published before a
+ // replacement is closed by SetDynamicAuth's detach pass (or kept on a
+ // rotation, as an already-live channel is), and one after it is
+ // refused here. The refused connection is closed outside the lock.
+ if viaDynamic {
+ if _, still := h.verifyDynamicLocked(name, token); !still {
+ h.mu.Unlock()
+ log.Printf("edge: tunnel %s: credential revoked during registration — closing", name)
+ conn.Close()
+ return
+ }
+ }
if old := h.conns[name]; old != nil {
old.raw.Close() // a re-register replaces the previous channel
}
@@ -274,13 +301,20 @@ func (h *TunnelHub) pingLoop(name string, cc *http2.ClientConn, raw net.Conn, dy
// bearer token, and the compare is constant-time so a wrong token leaks no
// prefix information by timing.
func (h *TunnelHub) VerifyDynamic(name, token string) (fleet string, ok bool) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.verifyDynamicLocked(name, token)
+}
+
+// verifyDynamicLocked is VerifyDynamic's answer against the current
+// dynamicAuth. h.mu must be held: ServeHTTP calls it again, under the lock,
+// as it publishes a dynamic channel's connection.
+func (h *TunnelHub) verifyDynamicLocked(name, token string) (fleet string, ok bool) {
fleet, _, hasSlash := strings.Cut(name, "/")
if !hasSlash || fleet == "" {
return "", false
}
- h.mu.Lock()
wantHash, known := h.dynamicAuth[name]
- h.mu.Unlock()
if !known || wantHash == "" {
return "", false
}
@@ -299,7 +333,9 @@ func (h *TunnelHub) VerifyDynamic(name, token string) (fleet string, ok bool) {
// rotation and detach: the next ServeHTTP call either hashes the presented
// token against a DIFFERENT stored hash (rotation: the name is still
// present, just under a new hash) or misses the map entirely (detach: the
-// name is gone). Either way, a new dial with the old token fails now.
+// name is gone). Either way, a new dial with the old token fails now. So
+// does a dial that authenticated before this call and publishes after it:
+// ServeHTTP checks the credential again under h.mu as it publishes.
//
// ROTATE and DETACH are deliberately asymmetric on an ALREADY-LIVE session,
// and that asymmetry is load-bearing, not an oversight:
diff --git a/internal/edge/tunnel_register_race_test.go b/internal/edge/tunnel_register_race_test.go
new file mode 100644
index 000000000..771e4fbd6
--- /dev/null
+++ b/internal/edge/tunnel_register_race_test.go
@@ -0,0 +1,146 @@
+package edge
+
+// Tunnel WebSockets (#471) Task 4, fix round 1 (Astra P1): a registration
+// that authenticated before a revoking Reload must not publish its channel
+// after it. TunnelHub.ServeHTTP re-checks a dynamic channel's credentials
+// under h.mu, the lock SetDynamicAuth replaces the set under, at the moment
+// it publishes the connection. The interleaving is driven by the afterAuth
+// seam, never by a sleep.
+
+import (
+ "bufio"
+ "net"
+ "net/http"
+ "net/url"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+func TestRegistrationRacingARevocationIsNotPublished(t *testing.T) {
+ const (
+ host = "shop.example.com"
+ name = "away/box-2"
+ )
+ for _, tc := range []struct {
+ desc string
+ revoke func(t *testing.T, reg *registry.Registry)
+ refused bool
+ }{
+ // Control: nothing changes while the registration is paused, and the
+ // same schedule publishes the channel.
+ {"unchanged", func(*testing.T, *registry.Registry) {}, false},
+ {"detached", func(t *testing.T, reg *registry.Registry) {
+ if err := reg.SetFleetBoxStatus("away", "box-2", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ auth, err := reg.FleetChannelAuth()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := auth[name]; ok {
+ t.Fatalf("read back: %s still has a credential", name)
+ }
+ }, true},
+ {"rotated", func(t *testing.T, reg *registry.Registry) {
+ hash := sha256Hex("box-2-token-rotated")
+ if err := reg.SetFleetBoxToken("away", "box-2", hash); err != nil {
+ t.Fatal(err)
+ }
+ auth, err := reg.FleetChannelAuth()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if auth[name] != hash {
+ t.Fatalf("read back: %s hash %q, want the rotated one", name, auth[name])
+ }
+ }, true},
+ } {
+ t.Run(tc.desc, func(t *testing.T) {
+ // box-2 (fleet away) is active in the registry and not connected;
+ // the fixture's box-1 Loop keeps fleet home's channel up.
+ hubURL, hub, _ := forwardHubAndBox(t, []registry.Route{forwardRow(host, "away", fwdOwner)}, nil, namedHandler("box-1"))
+ paused, resume := make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ hub.tunnels.afterAuth = func(n string) {
+ if n == name {
+ once.Do(func() {
+ close(paused)
+ <-resume
+ })
+ }
+ }
+ resumed := false
+ t.Cleanup(func() {
+ if !resumed {
+ close(resume)
+ }
+ })
+
+ // box-2 registers by hand with its current token.
+ u, err := url.Parse(hubURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ conn, err := net.Dial("tcp", u.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { conn.Close() })
+ req := tunnelReq(name, fwdBox2Tok)
+ req.Host = hub.tunnels.Host()
+ req.Header.Set(tunnelclient.CapsHeader, tunnelclient.CapUpgrade)
+ if err := req.Write(conn); err != nil {
+ t.Fatal(err)
+ }
+ resp, err := http.ReadResponse(bufio.NewReader(conn), req)
+ if err != nil || resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("registration = %v, %v; want 101", resp, err)
+ }
+ served := make(chan struct{})
+ go func() {
+ tunnelclient.ServeWith(conn, namedHandler("box-2"), tunnelclient.DefaultLimits)
+ close(served)
+ }()
+ select {
+ case <-paused:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the registration did not reach the publish point within 5 s")
+ }
+
+ // The revocation and the Reload that applies it, to completion.
+ tc.revoke(t, hub.reg)
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ resumed = true
+ close(resume)
+
+ if !tc.refused {
+ waitForTunnelState(t, hub.tunnels, name, "connected", e2eReconnectBound)
+ if resp, body := fwdDo(t, hubURL, "GET", host, "/", "", nil); resp.StatusCode != 200 || string(body) != "box-2" {
+ t.Fatalf("control: %s answered %d %q, want 200 from box-2", host, resp.StatusCode, body)
+ }
+ return
+ }
+ // The box's connection is closed: its server returns.
+ select {
+ case <-served:
+ case <-time.After(2 * time.Second):
+ t.Fatalf("2 s after resuming, %s's connection is still open", name)
+ }
+ if ch := hub.tunnels.channel(name); ch != nil {
+ t.Fatalf("%s's channel was published after its credential was %s", name, tc.desc)
+ }
+ if st := hub.tunnels.State(name); st == "connected" {
+ t.Fatalf("%s state %q after its credential was %s", name, st, tc.desc)
+ }
+ if resp, body := fwdDo(t, hubURL, "GET", host, "/", "", nil); string(body) == "box-2" {
+ t.Fatalf("%s answered %d from box-2 after its credential was %s", host, resp.StatusCode, tc.desc)
+ }
+ })
+ }
+}