carlos / platform Public

Regional domains (#447): T7+T8 fix round 2 (two P2s)

P2-1: a capability request whose claim is gone, or held by another
app, once regionalMu is taken answers the byte-identical 404, before
any regional check, DNS lookup or write.

P2-2 (ruling 8): the claims-off attach converge (attachDomainClaim ->
AttachClaimProven) and the paths door (SetClaimPaths) run their
read and ETag-bound write under regionalMu, innermost in the lock
order.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev b057010c1461f531dae862b8d3bb8ebbe65a837d parent 142d152
4 files changed, +259 −3
  • internal/console/apidomains.go +22 −3
  • internal/console/apiplacements_put_test.go +5 −0
  • internal/console/claim_alias.go +18 −0
  • internal/console/regional_reverse_test.go +214 −0
diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index 0f47a06f6..2c2e3b425 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -681,8 +681,10 @@ const wildFailMsg = "too many wildcard attempts with no _acme-challenge CNAME in
// taken before the mutex: a request that read Catchall on, waited, and
// found it turned off and a regional name made under host meanwhile is
// judged as the false-to-true transition it now is. A claim that changed
-// between the read and the write (a writer outside the mutex: an attach
-// converge, a detach) is the retry answer, never a write over it. Every
+// between the read and the write (a writer outside the mutex, such as a
+// detach) is the retry answer, never a write over it. A claim gone or no
+// longer the caller's by the time the mutex is taken is the neutral 404,
+// the answer a lost CAS on such a claim gets. Every
// request takes the mutex, the disabling ones too: one path, and whether a
// request leaves Catchall on can depend on the claim it reads.
func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, ctx context.Context, acct *Account, app string, p Principal, host string, wantWildcard, wantCatchall *bool) (ok bool) {
@@ -696,6 +698,14 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
s.regionalMu.Lock()
defer s.regionalMu.Unlock()
cur, etag, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
+ if errors.Is(err, os.ErrNotExist) || (err == nil && (cur.Account != acct.Sqid || cur.App != app)) {
+ // The claim went, or changed hands, while this request waited for
+ // the mutex: the byte-identical 404 a lost CAS gets below, decided
+ // before any regional check, DNS lookup or write, so the answer
+ // does not depend on when the claim went.
+ http.NotFound(w, r)
+ return false
+ }
if err != nil {
log.Printf("console: api domains capabilities %s/%s %s: read after attach: %v", acct.Sqid, app, host, err)
jsonError(w, http.StatusBadGateway, capabilitiesRetryMsg)
@@ -978,7 +988,16 @@ func (s *Server) handleAPIDomainPaths(w http.ResponseWriter, r *http.Request) {
paths := *in.Paths
ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
defer cancel()
- changed, err := domains.SetClaimPaths(ctx, s.cfg.Releases, host, acct.Sqid, app, paths)
+ // SetClaimPaths copies the claim it reads, Catchall included, and writes
+ // it back against that read's ETag. A write that leaves a catch-all on
+ // takes regionalMu (#447, Paul's ruling 8), so its read and write both
+ // sit under it. No app or host lock is held here; SetClaimPaths takes
+ // none, so regionalMu stays the innermost lock.
+ changed, err := func() (bool, error) {
+ s.regionalMu.Lock()
+ defer s.regionalMu.Unlock()
+ return domains.SetClaimPaths(ctx, s.cfg.Releases, host, acct.Sqid, app, paths)
+ }()
if errors.Is(err, domains.ErrTooManyPaths) {
jsonError(w, http.StatusUnprocessableEntity,
fmt.Sprintf("a hostname may carry at most %d path prefixes", domains.MaxPathsPerClaim))
diff --git a/internal/console/apiplacements_put_test.go b/internal/console/apiplacements_put_test.go
index f79e15bca..e3faece44 100644
--- a/internal/console/apiplacements_put_test.go
+++ b/internal/console/apiplacements_put_test.go
@@ -210,6 +210,7 @@ type rdStore struct {
puts []string
failGet map[string]bool
failList map[string]bool
+ beforeGet func(key string)
beforePut func(key string)
}
@@ -221,7 +222,11 @@ func (s *rdStore) Get(ctx context.Context, key string) ([]byte, string, error) {
s.mu.Lock()
s.gets = append(s.gets, key)
fail := s.failGet[key]
+ hook := s.beforeGet
s.mu.Unlock()
+ if hook != nil {
+ hook(key)
+ }
if fail {
return nil, "", errors.New("rdStore: get refused")
}
diff --git a/internal/console/claim_alias.go b/internal/console/claim_alias.go
index bde52ce1c..53eb15c73 100644
--- a/internal/console/claim_alias.go
+++ b/internal/console/claim_alias.go
@@ -18,8 +18,26 @@ import (
// A short alias request finishes before the first renewal deadline. An
// issued call that fails to finish remains in the durable effect journal.
+//
+// Claims off, AttachClaimProven's converge copies the claim it reads,
+// Catchall included, and writes it back against that read's ETag. A write
+// that leaves a catch-all on takes regionalMu (#447, Paul's ruling 8), so
+// the call runs under it: its read, its decision and its write. Callers may
+// hold the app lock and the hostname exclusion (attachFirstRouteLocked) or
+// the account's plan lock, all taken before this; AttachClaimProven takes
+// no lock, so regionalMu stays innermost. A TXT proof lookup, made only on
+// a create or a pending claim, runs under it too, bounded by the request's
+// context.
+//
+// Host-claim mode is left as it is: there the placements PUT and the
+// capability door both refuse, so nothing can make a regional name or turn
+// a catch-all on for this write to race, and taking regionalMu inside the
+// alias registration's lifecycle would order an app mutation before it,
+// the reverse of the catch-all doors.
func (s *Server) attachDomainClaim(ctx context.Context, acct *Account, app string, incoming domains.Claim, now time.Time, prove func() bool) (bool, bool, bool, error) {
if !s.cfg.HostClaim {
+ s.regionalMu.Lock()
+ defer s.regionalMu.Unlock()
return domains.AttachClaimProven(ctx, s.cfg.Releases, incoming, now, prove)
}
a := s.cfg.ClaimAuthority
diff --git a/internal/console/regional_reverse_test.go b/internal/console/regional_reverse_test.go
index 63d9cbc75..01021ff7e 100644
--- a/internal/console/regional_reverse_test.go
+++ b/internal/console/regional_reverse_test.go
@@ -785,3 +785,217 @@ func TestCapabilityWriteIsBoundToItsRead(t *testing.T) {
t.Fatalf("%d domain-capabilities rows, want none", n)
}
}
+
+// capsAsync sends the attach door's capability request for host bound to
+// rdIE from a goroutine, headers kept: the neutral 404 is compared header
+// for header.
+func (w *regionalWorld) capsAsync(host, flags string) <-chan capsAnswer {
+ done := make(chan capsAnswer, 1)
+ go func() {
+ req, err := http.NewRequest(http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"),
+ strings.NewReader(`{"host":"`+host+`","route":"`+rdIE+`",`+flags+`}`))
+ if err != nil {
+ done <- capsAnswer{err: err}
+ return
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+w.token)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ done <- capsAnswer{err: err}
+ return
+ }
+ defer res.Body.Close()
+ raw, err := io.ReadAll(res.Body)
+ done <- capsAnswer{code: res.StatusCode, header: res.Header, out: string(raw), err: err}
+ }()
+ return done
+}
+
+type capsAnswer struct {
+ code int
+ header http.Header
+ out string
+ err error
+}
+
+// putCount is how many Puts went through st.
+func (s *rdStore) putCount() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return len(s.puts)
+}
+
+// TestCapabilityClaimGoneDuringTheMutexWait (T7+T8 R2 P2-1): a capability
+// request parked after the attach door's reads, before regionalMu, whose
+// claim is detached (or then taken by another app) while it waits, answers
+// the byte-identical 404 a lost CAS answers, with no write, no DNS lookup,
+// no audit row and no serial bump.
+func TestCapabilityClaimGoneDuringTheMutexWait(t *testing.T) {
+ ctx := context.Background()
+ const host = "cat.example.net"
+ for i, leg := range []struct {
+ name string
+ change func(t *testing.T, w *regionalWorld)
+ }{
+ {"detached", func(t *testing.T, w *regionalWorld) {
+ if removed, err := domains.DetachClaim(ctx, w.fx.rel, host, w.fx.sqid, "shop"); err != nil || !removed {
+ t.Fatalf("detach = %v, %v", removed, err)
+ }
+ }},
+ {"detached and taken by another app", func(t *testing.T, w *regionalWorld) {
+ if removed, err := domains.DetachClaim(ctx, w.fx.rel, host, w.fx.sqid, "shop"); err != nil || !removed {
+ t.Fatalf("detach = %v, %v", removed, err)
+ }
+ attachShopClaim(t, w.fx, w.fx.sqid, "other", host, "other.example.net")
+ }},
+ } {
+ t.Run(leg.name, func(t *testing.T) {
+ w := newRegionalWorld(t, fmt.Sprintf("code-rdrev-capgone-%d", i))
+ lookups := w.delegatedCounting()
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", host, rdIE)
+ st := w.wrap()
+ held, resume := parkCapability(t, capabilityBeforeDecision, host)
+ a := w.capsAsync(host, `"wildcard":true,"catchall":true`)
+ await(t, held, "the capability request at "+capabilityBeforeDecision)
+
+ leg.change(t, w)
+ raw, etag, rerr := w.fx.rel.Get(ctx, domains.ClaimKey(host))
+ puts := st.putCount()
+ before := serial(t, w.fx)
+ lookups.Store(0)
+
+ close(resume)
+ got := await(t, a, "the capability request's answer")
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ assertNotFound(t, "capability request whose claim went during the mutex wait",
+ canonicalNotFound(t), got.code, got.header, got.out)
+ if n := st.putCount(); n != puts {
+ t.Fatalf("%d store writes after the claim went, want none", n-puts)
+ }
+ raw2, etag2, rerr2 := w.fx.rel.Get(ctx, domains.ClaimKey(host))
+ if string(raw2) != string(raw) || etag2 != etag || errors.Is(rerr2, os.ErrNotExist) != errors.Is(rerr, os.ErrNotExist) {
+ t.Fatalf("claim %s changed: %s (%s, %v), was %s (%s, %v)", host, raw2, etag2, rerr2, raw, etag, rerr)
+ }
+ if n := lookups.Load(); n != 0 {
+ t.Fatalf("%d CNAME lookups for a claim the caller no longer holds, want none", n)
+ }
+ if got := serial(t, w.fx); got != before {
+ t.Fatalf("serial %d, was %d", got, before)
+ }
+ if n := eventsOf(t, w.fx.st, "shop", "domain-capabilities"); n != 0 {
+ t.Fatalf("%d domain-capabilities rows, want none", n)
+ }
+ })
+ }
+}
+
+// regionalMuWatch records, at every Get and Put of one key through an
+// rdStore, whether the server's regionalMu was held: a TryLock that fails
+// means someone holds it (no other request runs in these tests).
+type regionalMuWatch struct {
+ mu sync.Mutex
+ lastGetHeld bool
+ puts int
+ bad []string
+}
+
+func watchRegionalMu(srv *Server, st *rdStore, key string) *regionalMuWatch {
+ m := &regionalMuWatch{}
+ held := func() bool {
+ if srv.regionalMu.TryLock() {
+ srv.regionalMu.Unlock()
+ return false
+ }
+ return true
+ }
+ st.beforeGet = func(k string) {
+ if k != key {
+ return
+ }
+ h := held()
+ m.mu.Lock()
+ m.lastGetHeld = h
+ m.mu.Unlock()
+ }
+ st.beforePut = func(k string) {
+ if k != key {
+ return
+ }
+ h := held()
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.puts++
+ if !h {
+ m.bad = append(m.bad, "the write ran without regionalMu")
+ }
+ if !m.lastGetHeld {
+ m.bad = append(m.bad, "the read the write is bound to ran without regionalMu")
+ }
+ }
+ return m
+}
+
+// require fails unless exactly one write of the key ran, with regionalMu
+// held at it and at the read just before it.
+func (m *regionalMuWatch) require(t *testing.T, what string) {
+ t.Helper()
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.puts != 1 {
+ t.Fatalf("%s: %d claim writes, want 1", what, m.puts)
+ }
+ if len(m.bad) > 0 {
+ t.Fatalf("%s: %s", what, strings.Join(m.bad, "; "))
+ }
+}
+
+// catchallClaim is host attached to shop at rdIE with both capabilities on.
+func (w *regionalWorld) catchallClaim(t *testing.T, host string) {
+ t.Helper()
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", host, rdIE)
+ if _, err := domains.SetClaimCapabilities(context.Background(), w.fx.rel, host, w.fx.sqid, "shop", true, true); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestAttachConvergeHoldsRegionalMu (T7+T8 R2 P2-2, ruling 8): a re-attach
+// that repoints a claim whose catch-all is on, naming no capability, writes
+// the claim with the catch-all still on. Its read and its write both run
+// under regionalMu.
+func TestAttachConvergeHoldsRegionalMu(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdrev-convergemu")
+ const host = "cat.example.net"
+ w.catchallClaim(t, host)
+ m := watchRegionalMu(w.fx.srv, w.wrap(), domains.ClaimKey(host))
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"), w.token,
+ `{"host":"`+host+`","route":"`+rdUK+`"}`)
+ if code != http.StatusOK {
+ t.Fatalf("repoint = %d %s, want 200", code, out)
+ }
+ if c := w.claim(t, host); c.Route != rdUK || !c.Wildcard || !c.Catchall {
+ t.Fatalf("claim %s = %+v, want route %s with both capabilities kept", host, c, rdUK)
+ }
+ m.require(t, "the attach converge")
+}
+
+// TestPathsDoorHoldsRegionalMu (T7+T8 R2 P2-2, ruling 8): publishing a
+// prefix map on a claim whose catch-all is on writes the claim with the
+// catch-all still on. Its read and its write both run under regionalMu.
+func TestPathsDoorHoldsRegionalMu(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdrev-pathsmu")
+ const host = "cat.example.net"
+ w.catchallClaim(t, host)
+ m := watchRegionalMu(w.fx.srv, w.wrap(), domains.ClaimKey(host))
+ code, _, out := rawReq(t, http.MethodPut, domainsURL(w.fx, w.fx.sqid, "shop")+"/"+host+"/paths", w.token,
+ `{"paths":{"docs":"`+rdUK+`"}}`)
+ if code != http.StatusOK {
+ t.Fatalf("paths = %d %s, want 200", code, out)
+ }
+ if c := w.claim(t, host); c.Paths["docs"] != rdUK || !c.Wildcard || !c.Catchall {
+ t.Fatalf("claim %s = %+v, want the prefix with both capabilities kept", host, c)
+ }
+ m.require(t, "the paths door")
+}