carlos / platform Public

Regional domains (#447) Task 8: reverse doors, interleavings, fixed capabilities

No catch-all can be made above a regional name from any door, the
placements PUT and instance create serialise per host in both orders and
across a failed record write, and a regional claim's capabilities cannot
change at any writer (spec §15 step 5 part 2; W11, W14).

- setDomainCapabilities: on the Catchall false-to-true transition, after
  the regional check and before the enabling gate, regionalMu is taken
  (held through the write) and regionalDescendantRefusal runs; its 409 is
  RD-28, a failed listing 503.
- attachInstanceCatchall (API and browser doors): after
  customDomainRefusal, a parent-held pre-check (anyone not holding the
  parent gets today's catchallParentMsg, so RD-29 is no oracle), then
  regionalMu and the descendant scan (409 RD-29, 503), and
  ErrRegionalClaim from AttachInstanceCatchall answers RD-29 before
  claimRefusal.
- instanceCreateHook (test seam, atomic.Pointer, nil in production):
  "after-claim-check" in the create door, "after-record-write" inside the
  app lock and host exclusion in createRecordMarked and
  createRecordWithLifetime.
- regional_reverse_test.go: TestCatchallRefusedOverARegionalName,
  TestRegionalPutAndInstanceCreateSerialise (lifetimes off and on, both
  orders, lock-order checker), TestRegionalPutRefusesAPendingAllocation,
  TestRegionalClaimCapabilitiesAreFixed (W14 a/b/c, same values,
  route-less branch unreachable), TestDetachThenRecreateChangesCapabilities.

Mutation checks:
- capability door scan removed: catchall on example.com answers 200
- catch-all door scan removed: *.dog.example.net on a failed listing 200;
  scan 409 ignored (503 kept): *.example.com answers 200
- ErrRegionalClaim intercept removed: *.shop.example.com answers RD-26
- enabling gate moved before the scan: 1 CNAME lookup, want 0
- parent pre-check always admits: *.theirs.example.net answers RD-29 to a
  caller who does not hold the parent
- PUT pending test removed: the first PUT writes the claim (200) and
  recovery then writes the colliding record
- SetClaimCapabilities regional refusal removed: (c) writes (true, nil)
- door early refusal removed: (a) makes 1 CNAME lookup, then 502
- createRecordMarked recheck removed: lifetimes off, the resumed create 201
- lifetime create recheck removed: lifetimes on, the resumed create 201
- PUT without lockAppHost: the PUT never waits for the app lock (both modes)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 0cd1abde4ab0db564284245aa59a1f3c440b7b15 parent e856dc3
6 files changed, +699 −2
  • internal/console/apidomains.go +26 −0
  • internal/console/apiinstances.go +26 −0
  • internal/console/domaincatchall.go +33 −0
  • internal/console/hostsused.go +5 −1
  • internal/console/lifetimes_create.go +3 −1
  • internal/console/regional_reverse_test.go +606 −0
diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index b184ad229..58c55dd5f 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -699,6 +699,25 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
jsonError(w, http.StatusConflict, domains.ErrRegionalClaim.Error())
return false
}
+ // A catch-all on host covers every one-label name under it, and none of
+ // those may be regional (#447, spec §6.7). On the false-to-true
+ // transition only, the descendant scan runs under regionalMu, held until
+ // the write below is done, so a placements PUT creating a regional name
+ // under host cannot land between the scan and the write. Before the
+ // enabling gate: a refused change makes no CNAME lookup. Both 409 cases
+ // (a regional claim, or one the listing shows but could not read) answer
+ // RD-28, so the answer never says which name sits under host.
+ if catchall && !cur.Catchall {
+ s.regionalMu.Lock()
+ defer s.regionalMu.Unlock()
+ if ref := s.regionalDescendantRefusal(ctx, host); ref != nil {
+ if ref.Status == http.StatusConflict {
+ ref = &doorRefusal{http.StatusConflict, catchallOverRegionalMsg(host)}
+ }
+ jsonError(w, ref.Status, ref.Msg)
+ return false
+ }
+ }
// enabling is the false->true TRANSITION only — re-sending wildcard:true
// for a claim that already has it must not re-run the gate. Two reasons:
// the CNAME lookup is a live, sequential, request-path DNS round trip
@@ -754,6 +773,13 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
return true
}
+// catchallOverRegionalMsg is RD-28: the capability door's answer when a
+// regional claim, or a claim that could not be read, sits one label under
+// host.
+func catchallOverRegionalMsg(host string) string {
+ return "a catch-all on " + host + " would cover a regional domain under it, so it cannot be turned on."
+}
+
// wildcardEnablingRefusal is the gate a claim's Wildcard passes on its way
// from false to true: setDomainCapabilities runs it on that transition, and
// the placements door (apiplacements.go, #447) runs it when it creates a
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 62197c5b8..6811b2418 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -36,6 +36,7 @@ import (
"slices"
"strconv"
"strings"
+ "sync/atomic"
"time"
"github.com/carlosframework/platform/internal/gate"
@@ -60,6 +61,30 @@ const instanceStoreTimeout = 15 * time.Second
// serving a prefix.
const instanceListMax = 500
+// The instance create's stages instanceCreateHook names (#447, spec §13 W11).
+const (
+ // instanceCreateAfterClaimCheck: the door's holder and claim checks
+ // have been judged and admitted the host; no lock is held.
+ instanceCreateAfterClaimCheck = "after-claim-check"
+ // instanceCreateAfterRecordWrite: the record write returned with the
+ // record written, still inside the app lock and the host exclusion
+ // (createRecordMarked, createRecordWithLifetime).
+ instanceCreateAfterRecordWrite = "after-record-write"
+)
+
+// instanceCreateHook, when set, is called at each stage of an instance
+// create with the host. A TEST SEAM (nil in production): the interleaving
+// witnesses park a create there while a placements PUT runs. An
+// atomic.Pointer, as lifetimeLockHook is, so a test may set it while a
+// handler goroutine reads it.
+var instanceCreateHook atomic.Pointer[func(stage, host string)]
+
+func instanceCreateStage(stage, host string) {
+ if h := instanceCreateHook.Load(); h != nil {
+ (*h)(stage, host)
+ }
+}
+
// instanceGate is the preamble every instance verb shares, in the order the
// family fixed (handleAPIPromote): principal FIRST, budget second, then the
// deployment's own readiness. The order is load-bearing — a rate limit
@@ -1528,6 +1553,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
jsonError(w, http.StatusConflict, claimHeldSentence(host, hold))
return
}
+ instanceCreateStage(instanceCreateAfterClaimCheck, host)
// A fleet-placed app (customer-fleets plan, `carlos apps place`) governs
// every one of its instances' Region uniformly — spec's "one flag on the
// app, all its instances follow" (appPlacement, fleets.go) — so when a
diff --git a/internal/console/domaincatchall.go b/internal/console/domaincatchall.go
index 3dd9c9b65..dd43c3609 100644
--- a/internal/console/domaincatchall.go
+++ b/internal/console/domaincatchall.go
@@ -33,6 +33,11 @@ func catchallParentMsg(parent string) string {
return "attach " + parent + " to an app in this account first — an instance catch-all on *." + parent + " needs " + parent + " itself held by the same account"
}
+// instanceCatchallOverRegionalMsg is RD-29: an instance catch-all whose
+// parent is regional, or has a regional (or unreadable) claim one label
+// under it.
+const instanceCatchallOverRegionalMsg = "an instance catch-all cannot cover a regional domain."
+
// catchallParentRefused reports whether parent may never carry an instance
// catch-all on this deployment, decided from the name and the config alone.
//
@@ -96,11 +101,39 @@ func (s *Server) attachInstanceCatchall(ctx context.Context, acct *Account, app,
if ref := s.customDomainRefusal(acct, parent); ref != nil {
return false, ref
}
+ // No instance catch-all covers a regional name (#447, spec §6.7): not
+ // one under parent (the descendant scan), and not parent itself
+ // (domains.AttachInstanceCatchall's ErrRegionalClaim). regionalMu is held
+ // across the scan and the write, so a placements PUT cannot create a
+ // regional name under parent between them. Every 409 is RD-29.
+ //
+ // The scan answers only a caller whose account holds parent, verified,
+ // as AttachInstanceCatchall judges it: anyone else gets catchallParentMsg
+ // first, the answer they get today, so RD-29 never tells another
+ // account that a regional name sits under a domain it does not hold.
+ // AttachInstanceCatchall judges the parent again under its own write.
+ switch apex, err := domains.GetClaim(ctx, s.cfg.Releases, parent); {
+ case errors.Is(err, os.ErrNotExist), err == nil && (apex.Account != acct.Sqid || apex.Pending):
+ return false, &doorRefusal{http.StatusConflict, catchallParentMsg(parent)}
+ case err != nil:
+ return false, claimRefusal(domains.InstanceCatchallHost(parent), err)
+ }
+ s.regionalMu.Lock()
+ defer s.regionalMu.Unlock()
+ if ref := s.regionalDescendantRefusal(ctx, parent); ref != nil {
+ if ref.Status == http.StatusConflict {
+ ref = &doorRefusal{http.StatusConflict, instanceCatchallOverRegionalMsg}
+ }
+ return false, ref
+ }
created, err := domains.AttachInstanceCatchall(ctx, s.cfg.Releases, parent, acct.Sqid, app,
time.Now().UTC().Format(time.RFC3339), principal)
switch {
case errors.Is(err, domains.ErrParentNotHeld):
return false, &doorRefusal{http.StatusConflict, catchallParentMsg(parent)}
+ case errors.Is(err, domains.ErrRegionalClaim):
+ // Before claimRefusal, which answers the sentinel with RD-26.
+ return false, &doorRefusal{http.StatusConflict, instanceCatchallOverRegionalMsg}
case err != nil:
return false, claimRefusal(domains.InstanceCatchallHost(parent), err)
}
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
index 945722445..e38c0160d 100644
--- a/internal/console/hostsused.go
+++ b/internal/console/hostsused.go
@@ -584,7 +584,11 @@ func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) e
return err
}
}
- return provision.CreateRecord(ctx, s.cfg.Releases, rec)
+ if err := provision.CreateRecord(ctx, s.cfg.Releases, rec); err != nil {
+ return err
+ }
+ instanceCreateStage(instanceCreateAfterRecordWrite, rec.Host) // still under both locks
+ return nil
}
// createSidecarMarked is the sidecar door's create: a sidecar is always a
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go
index 95c009e11..5fadcf249 100644
--- a/internal/console/lifetimes_create.go
+++ b/internal/console/lifetimes_create.go
@@ -46,7 +46,9 @@ func (s *Server) createRecordWithLifetime(ctx context.Context, rec provision.Rec
var out *provision.Record
err := s.withAppHost(rec.Account, rec.App, rec.Host, func() error {
var err error
- out, err = s.createRecordWithLifetimeLocked(ctx, rec, lifetime)
+ if out, err = s.createRecordWithLifetimeLocked(ctx, rec, lifetime); err == nil {
+ instanceCreateStage(instanceCreateAfterRecordWrite, rec.Host) // still under both locks
+ }
return err
})
return out, err
diff --git a/internal/console/regional_reverse_test.go b/internal/console/regional_reverse_test.go
new file mode 100644
index 000000000..346a3ede6
--- /dev/null
+++ b/internal/console/regional_reverse_test.go
@@ -0,0 +1,606 @@
+package console
+
+// Regional domains (#447) Task 8 (spec §15 step 5, part 2): no catch-all
+// can be made above a regional name from any door (W11); the placements PUT
+// and instance create serialise per host in both orders and across a failed
+// record write (W11 rev 4 and rev 5); and a regional claim's capabilities
+// cannot change at any writer (W14). Every test goes through the real
+// console server, the real claim and record writers and the world the PUT's
+// own tests use (newRegionalWorld).
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// rdCatchallMsg is RD-28 (draft) for host.
+func rdCatchallMsg(host string) string {
+ return "a catch-all on " + host + " would cover a regional domain under it, so it cannot be turned on."
+}
+
+// rdInstanceCatchallMsg is RD-29 (draft).
+const rdInstanceCatchallMsg = "an instance catch-all cannot cover a regional domain."
+
+// rdInstWorld is the PUT's world whose app shop also has instances under
+// example.com, so an instance can be created at rdHost. With lifetimes on,
+// the console's bucket sits behind an ltStore (bucket); off, bucket is nil.
+type rdInstWorld struct {
+ *regionalWorld
+ bucket *ltStore
+}
+
+func newRDInstWorld(t *testing.T, code string, on bool) rdInstWorld {
+ t.Helper()
+ clock := useLifetimesClock(t)
+ w := newRegionalWorld(t, code)
+ if err := provision.PutManifest(context.Background(), w.fx.rel, w.fx.sqid, "shop",
+ provision.Manifest{Schema: 1, App: "shop", Domain: "example.com", Channel: "stable"}); err != nil {
+ t.Fatal(err)
+ }
+ iw := rdInstWorld{regionalWorld: w}
+ if on {
+ iw.bucket = &ltStore{Store: w.fx.rel}
+ w.fx.srv.cfg.Releases = iw.bucket
+ turnLifetimesOn(t, w.fx.srv, clock)
+ }
+ return iw
+}
+
+// rdAnswer is one HTTP answer.
+type rdAnswer struct {
+ code int
+ out string
+ err error
+}
+
+// rdDo sends a request without a *testing.T, for a goroutine.
+func rdDo(method, u, token, body string) rdAnswer {
+ req, err := http.NewRequest(method, u, strings.NewReader(body))
+ if err != nil {
+ return rdAnswer{err: err}
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+token)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return rdAnswer{err: err}
+ }
+ defer res.Body.Close()
+ raw, err := io.ReadAll(res.Body)
+ return rdAnswer{code: res.StatusCode, out: string(raw), err: err}
+}
+
+// createAt starts an instance create of host on app shop and returns the
+// channel its answer arrives on.
+func (w *regionalWorld) createAt(host string) <-chan rdAnswer {
+ done := make(chan rdAnswer, 1)
+ go func() {
+ done <- rdDo(http.MethodPost, instancesURL(w.fx, w.fx.sqid, "shop"), w.token, `{"host":"`+host+`"}`)
+ }()
+ return done
+}
+
+// putAsync starts the placements PUT of rdBoth at host.
+func (w *regionalWorld) putAsync(host string) <-chan rdAnswer {
+ done := make(chan rdAnswer, 1)
+ go func() {
+ done <- rdDo(http.MethodPut, placementsURL(w.fx, "shop", host), w.token,
+ `{"placements":[{"region":"ie","host":"`+rdIE+`"},{"region":"uk","host":"`+rdUK+`"}]}`)
+ }()
+ return done
+}
+
+// parkCreate sets instanceCreateHook to hold the create of host at stage
+// until resume is closed; held closes when it gets there.
+func parkCreate(t *testing.T, stage, host string) (held, resume chan struct{}) {
+ t.Helper()
+ held, resume = make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ h := func(s, h string) {
+ if s != stage || h != host {
+ return
+ }
+ once.Do(func() {
+ close(held)
+ <-resume
+ })
+ }
+ instanceCreateHook.Store(&h)
+ t.Cleanup(func() {
+ instanceCreateHook.Store(nil)
+ select { // a failed test never leaves the create parked
+ case <-resume:
+ default:
+ close(resume)
+ }
+ })
+ return held, resume
+}
+
+// await fails the test unless ch closes (or sends) within ten seconds: an
+// interleaving that never arrives is a failure, not a hang.
+func await[T any](t *testing.T, ch <-chan T, what string) T {
+ t.Helper()
+ select {
+ case v := <-ch:
+ return v
+ case <-time.After(10 * time.Second):
+ t.Fatalf("timed out waiting for %s", what)
+ panic("unreachable")
+ }
+}
+
+// requireRecordAt fails unless the shop record at host is there (want) or
+// absent (!want).
+func (w *regionalWorld) requireRecordAt(t *testing.T, host string, want bool, what string) {
+ t.Helper()
+ _, _, err := w.fx.rel.Get(context.Background(), provision.RecordKey(w.fx.sqid, "shop", host))
+ switch {
+ case want && err != nil:
+ t.Fatalf("%s: record %s: %v, want it written", what, host, err)
+ case !want && !errors.Is(err, os.ErrNotExist):
+ t.Fatalf("%s: record %s: %v, want none", what, host, err)
+ }
+}
+
+// capsReq is the attach door with flags for host bound to rdIE.
+func (w *regionalWorld) capsReq(t *testing.T, host, flags string) (int, string) {
+ t.Helper()
+ body := `{"host":"` + host + `","route":"` + rdIE + `"`
+ if flags != "" {
+ body += "," + flags
+ }
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"), w.token, body+"}")
+ return code, out
+}
+
+// delegatedCounting points the world at a delegation zone whose
+// _acme-challenge CNAMEs all delegate, counting every lookup.
+func (w *regionalWorld) delegatedCounting() *atomic.Int32 {
+ const zone = "acme.example.org"
+ var n atomic.Int32
+ w.fx.srv.delegationZone = zone
+ w.fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
+ n.Add(1)
+ return name + "." + zone + ".", nil
+ }
+ return &n
+}
+
+// TestCatchallRefusedOverARegionalName (W11): with shop.example.com
+// regional, no catch-all above it can be made from any door: the claim
+// capability (RD-28, before the enabling gate), and the instance catch-all
+// over example.com or over the regional name itself, from the API and the
+// browser (RD-29). An instance create at the name by the claim's own app is
+// RD-27.
+func TestCatchallRefusedOverARegionalName(t *testing.T) {
+ w := newRDInstWorld(t, "code-rdrev-catchall", false).regionalWorld
+ noCatchallProof(w.fx)
+ lookups := w.delegatedCounting()
+ ctx := context.Background()
+ w.mustPut(t, rdHost, rdBoth())
+ regional, regionalETag := regionalClaimBytes(t, w.fx.rel, rdHost)
+
+ // Catchall on example.com: refused before the enabling gate, so a
+ // request that also turns wildcard on makes no CNAME lookup.
+ const parent = "example.com"
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", parent, rdIE)
+ lookups.Store(0)
+ raw, etag := regionalClaimBytes(t, w.fx.rel, parent)
+ before := serial(t, w.fx)
+ code, out := w.capsReq(t, parent, `"wildcard":true,"catchall":true`)
+ requireRefusal(t, "wildcard and catchall on "+parent, code, out, http.StatusConflict, rdCatchallMsg(parent))
+ requireClaimUnchanged(t, w.fx.rel, parent, raw, etag, "wildcard and catchall on "+parent)
+ if n := lookups.Load(); n != 0 {
+ t.Fatalf("CNAME lookups = %d, want 0: the scan refuses before the enabling gate", n)
+ }
+ if _, err := domains.SetClaimCapabilities(ctx, w.fx.rel, parent, w.fx.sqid, "shop", true, false); err != nil {
+ t.Fatal(err)
+ }
+ raw, etag = regionalClaimBytes(t, w.fx.rel, parent)
+ code, out = w.capsReq(t, parent, `"catchall":true`)
+ requireRefusal(t, "catchall on "+parent, code, out, http.StatusConflict, rdCatchallMsg(parent))
+ requireClaimUnchanged(t, w.fx.rel, parent, raw, etag, "catchall on "+parent)
+ 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)
+ }
+
+ // A claim under the parent the listing shows but cannot read: RD-28
+ // too, so the answer never says which name sits there.
+ const unreadParent = "example.org"
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", unreadParent, rdIE)
+ if _, err := domains.SetClaimCapabilities(ctx, w.fx.rel, unreadParent, w.fx.sqid, "shop", true, false); err != nil {
+ t.Fatal(err)
+ }
+ putFixtureObject(t, w.fx.rel, domains.ClaimKey("bob."+unreadParent), []byte("not json"))
+ raw, etag = regionalClaimBytes(t, w.fx.rel, unreadParent)
+ code, out = w.capsReq(t, unreadParent, `"catchall":true`)
+ requireRefusal(t, "an unread claim under "+unreadParent, code, out, http.StatusConflict, rdCatchallMsg(unreadParent))
+ requireClaimUnchanged(t, w.fx.rel, unreadParent, raw, etag, "an unread claim under "+unreadParent)
+
+ // A parent with nothing regional under it takes its catch-all.
+ const free = "cat.example.net"
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", free, rdIE)
+ if code, out := w.capsReq(t, free, `"wildcard":true,"catchall":true`); code != http.StatusOK {
+ t.Fatalf("catchall on %s = %d %s, want 200", free, code, out)
+ }
+ if c := w.claim(t, free); !c.Wildcard || !c.Catchall {
+ t.Fatalf("claim %s = %+v, want both capabilities", free, c)
+ }
+
+ // A failed listing: 503, nothing written.
+ const listed = "dog.example.net"
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", listed, rdIE)
+ if _, err := domains.SetClaimCapabilities(ctx, w.fx.rel, listed, w.fx.sqid, "shop", true, false); err != nil {
+ t.Fatal(err)
+ }
+ raw, etag = regionalClaimBytes(t, w.fx.rel, listed)
+ st := w.wrap()
+ st.failList[domains.ClaimsPrefix] = true
+ code, out = w.capsReq(t, listed, `"catchall":true`)
+ requireRefusal(t, "a failed claim listing", code, out, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ requireClaimUnchanged(t, w.fx.rel, listed, raw, etag, "a failed claim listing")
+ // The instance catch-all door fails closed on the same listing.
+ code, _, out = rawReq(t, http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"), w.token, `{"host":"*.`+listed+`"}`)
+ requireRefusal(t, "an instance catch-all on a failed listing", code, out, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ claimAbsent(t, w.fx, "*."+listed)
+ w.fx.srv.cfg.Releases = w.fx.rel
+
+ // Instance catch-alls over example.com (the scan) and over the regional
+ // name itself (domains.AttachInstanceCatchall's regional parent), from
+ // the API door and the browser door.
+ b := signInPaul(t, w.fx)
+ csrf := sessionToken(t, w.fx, b)
+ for _, p := range []string{parent, rdHost} {
+ star := "*." + p
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"), w.token, `{"host":"`+star+`"}`)
+ requireRefusal(t, "API "+star, code, out, http.StatusConflict, rdInstanceCatchallMsg)
+ claimAbsent(t, w.fx, star)
+ code, _, page := postForm(t, b, w.fx.u("/apps/shop/domains/attach"), url.Values{"csrf": {csrf}, "host": {star}})
+ if code != http.StatusConflict || !strings.Contains(page, rdInstanceCatchallMsg) {
+ t.Fatalf("browser %s = %d, want 409 with RD-29:\n%s", star, code, page)
+ }
+ claimAbsent(t, w.fx, star)
+ }
+ // Another account's regional name under a parent the caller does not
+ // hold: the caller reads only today's "hold the parent first", the same
+ // as over a parent with nothing under it, so RD-29 is no oracle.
+ if err := writeRegionalClaim(w.fx.rel, "alice.theirs.example.net", "zzz", "blog", "alice-ie.example.net", false, false); err != nil {
+ t.Fatal(err)
+ }
+ for _, held := range []bool{false, true} {
+ if held {
+ attachShopClaim(t, w.fx, "zzz", "blog", "theirs.example.net", "theirs-ie.example.net")
+ }
+ code, _, theirs := rawReq(t, http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"), w.token, `{"host":"*.theirs.example.net"}`)
+ requireRefusal(t, fmt.Sprintf("*.theirs.example.net (parent held elsewhere %v)", held), code, theirs,
+ http.StatusConflict, catchallParentMsg("theirs.example.net"))
+ _, _, unclaimed := rawReq(t, http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"), w.token, `{"host":"*.none.example.net"}`)
+ if strings.ReplaceAll(theirs, "theirs.", "") != strings.ReplaceAll(unclaimed, "none.", "") {
+ t.Fatalf("over another account's regional name %q reads apart from an unclaimed parent %q", theirs, unclaimed)
+ }
+ }
+ claimAbsent(t, w.fx, "*.theirs.example.net")
+
+ // The control: a parent with nothing regional under it.
+ if code, _, out := rawReq(t, http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"), w.token, `{"host":"*.`+free+`"}`); code != http.StatusOK {
+ t.Fatalf("instance catch-all on %s = %d %s, want 200", free, code, out)
+ }
+
+ // The claim's own app cannot create an instance at the name.
+ code, out = rdCreate2(t, w, rdHost)
+ requireRefusal(t, "instance create at "+rdHost, code, out, http.StatusConflict, rdHeldMsg(rdHost))
+ w.requireRecordAt(t, rdHost, false, "instance create at "+rdHost)
+ requireClaimUnchanged(t, w.fx.rel, rdHost, regional, regionalETag, "every door above")
+}
+
+// rdCreate2 is an instance create of host on the world's app shop.
+func rdCreate2(t *testing.T, w *regionalWorld, host string) (int, string) {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodPost, instancesURL(w.fx, w.fx.sqid, "shop"), w.token, `{"host":"`+host+`"}`)
+ return code, out
+}
+
+// TestRegionalPutAndInstanceCreateSerialise (W11 rev 4), lifetimes off and
+// on. A create parked after its claim check (no claim yet) lets the PUT run
+// to completion and then 409s at the recheck under the host exclusion, with
+// no record. A create parked after its record write, inside the exclusion,
+// makes the PUT wait for the exclusion and then 409 on the walk, with no
+// claim. The lock-order checker sees no inversion in either.
+func TestRegionalPutAndInstanceCreateSerialise(t *testing.T) {
+ for _, on := range []bool{false, true} {
+ mode := map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on]
+ t.Run(mode+"/the PUT first", func(t *testing.T) {
+ iw := newRDInstWorld(t, "code-rdrev-ser-put", on)
+ w := iw.regionalWorld
+ c := installLockChecker(t)
+ held, resume := parkCreate(t, instanceCreateAfterClaimCheck, rdHost)
+ create := w.createAt(rdHost)
+ await(t, held, "the create to reach its claim check")
+ w.mustPut(t, rdHost, rdBoth())
+ close(resume)
+ got := await(t, create, "the resumed create")
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ requireRefusal(t, "the resumed create", got.code, got.out, http.StatusConflict, rdHeldMsg(rdHost))
+ w.requireRecordAt(t, rdHost, false, "the resumed create")
+ if !w.claim(t, rdHost).Regional() {
+ t.Fatal("the PUT's claim is not regional")
+ }
+ if on {
+ if n, err := w.fx.st.PendingForHost(rdHost, ""); err != nil || n != 0 {
+ t.Fatalf("PendingForHost = %d, %v, want 0", n, err)
+ }
+ }
+ c.check(t)
+ })
+ t.Run(mode+"/the create first", func(t *testing.T) {
+ iw := newRDInstWorld(t, "code-rdrev-ser-create", on)
+ w := iw.regionalWorld
+ c := installLockChecker(t)
+ // The PUT waiting for the app lock the parked create holds.
+ appKey := w.fx.sqid + "/shop"
+ var parked atomic.Bool
+ waiting := make(chan struct{})
+ var waitOnce sync.Once
+ inner := lifetimeLockHook.Load()
+ h := func(kind, key, event string) {
+ (*inner)(kind, key, event)
+ if parked.Load() && kind == "app" && key == appKey && event == lockWaiting {
+ waitOnce.Do(func() { close(waiting) })
+ }
+ }
+ lifetimeLockHook.Store(&h)
+ held, resume := parkCreate(t, instanceCreateAfterRecordWrite, rdHost)
+ create := w.createAt(rdHost)
+ await(t, held, "the create to write its record")
+ parked.Store(true)
+ w.requireRecordAt(t, rdHost, true, "the parked create")
+ put := w.putAsync(rdHost)
+ await(t, waiting, "the PUT to wait for the app lock")
+ w.requireNoClaim(t, rdHost, "the PUT waiting for the exclusion")
+ close(resume)
+ if got := await(t, create, "the create"); got.err != nil || got.code != http.StatusCreated {
+ t.Fatalf("create = %d %s %v, want 201", got.code, got.out, got.err)
+ }
+ got := await(t, put, "the PUT")
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ requireRefusal(t, "the PUT after the create", got.code, got.out, http.StatusConflict, hostUnavailableMsg)
+ w.requireNoClaim(t, rdHost, "the PUT after the create")
+ c.check(t)
+ })
+ }
+}
+
+// TestRegionalPutRefusesAPendingAllocation (W11 rev 5, R4 P2-1), lifetimes
+// on: a create whose record write fails after BeginAllocation leaves the
+// allocation pending and no record. The PUT refuses on the pending
+// operation (the neutral 409), a failed pending read is 503, and once
+// recovery writes the record the PUT refuses on the walk. No claim is
+// written at any point.
+func TestRegionalPutRefusesAPendingAllocation(t *testing.T) {
+ iw := newRDInstWorld(t, "code-rdrev-pending", true)
+ w := iw.regionalWorld
+ iw.bucket.setHook(failNth("put", provision.RecordKey(w.fx.sqid, "shop", rdHost), 1, true))
+ code, out := rdCreate2(t, w, rdHost)
+ iw.bucket.setHook(nil)
+ requireRefusal(t, "the create whose record write fails", code, out, http.StatusBadGateway, msgLifetimeCreatePending)
+ w.requireRecordAt(t, rdHost, false, "the failed record write")
+ if n, err := w.fx.st.PendingForHost(rdHost, ""); err != nil || n != 1 {
+ t.Fatalf("PendingForHost = %d, %v, want 1", n, err)
+ }
+
+ // Errorf, not Fatalf: under the mutation that drops the pending test the
+ // legs below still run and show recovery writing the colliding record.
+ noClaim := func(what string) {
+ t.Helper()
+ if _, _, err := w.fx.rel.Get(context.Background(), domains.ClaimKey(rdHost)); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("%s: claim %s: %v, want none written", what, rdHost, err)
+ }
+ }
+ code, out = w.put(t, rdHost, rdBoth())
+ if code != http.StatusConflict || cutoverErrorOf(out) != hostUnavailableMsg {
+ t.Errorf("PUT with the allocation pending = %d %s, want 409 %q", code, out, hostUnavailableMsg)
+ }
+ noClaim("the PUT with the allocation pending")
+
+ if _, err := w.fx.st.db.Exec(`ALTER TABLE record_migrations RENAME TO record_migrations_gone`); err != nil {
+ t.Fatal(err)
+ }
+ code, out = w.put(t, rdHost, rdBoth())
+ if code != http.StatusServiceUnavailable || cutoverErrorOf(out) != placementsUnreadableMsg {
+ t.Errorf("PUT with the pending read failing = %d %s, want 503", code, out)
+ }
+ noClaim("the PUT with the pending read failing")
+ if _, err := w.fx.st.db.Exec(`ALTER TABLE record_migrations_gone RENAME TO record_migrations`); err != nil {
+ t.Fatal(err)
+ }
+
+ recoverOn(t, w.fx.srv)
+ w.requireRecordAt(t, rdHost, true, "recovery")
+ if n, err := w.fx.st.PendingForHost(rdHost, ""); err != nil || n != 0 {
+ t.Fatalf("PendingForHost after recovery = %d, %v, want 0", n, err)
+ }
+ code, out = w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "the PUT after recovery", code, out, http.StatusConflict, hostUnavailableMsg)
+ noClaim("the PUT after recovery")
+}
+
+// TestRegionalClaimCapabilitiesAreFixed (W14, ruling 6): two regional
+// claims made by the PUT, shop.example.com with neither capability and
+// shop2.example.com with both. Every change, in both directions, is
+// refused at every writer: (a) the attach door naming a bound host, before
+// any CNAME lookup or wildFail count; (b) the PUT update; (c)
+// domains.SetClaimCapabilities. The same values are accepted and write
+// nothing. Bytes, ETag, serial and audit rows never move.
+func TestRegionalClaimCapabilitiesAreFixed(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdrev-fixed")
+ lookups := w.delegatedCounting()
+ ctx := context.Background()
+ const neither, both = rdHost, "shop2.example.com"
+ w.mustPut(t, neither, rdBoth())
+ withBoth := rdBoth()
+ withBoth.Wildcard, withBoth.Catchall = boolp(true), boolp(true)
+ w.mustPut(t, both, withBoth)
+ if c := w.claim(t, neither); c.Wildcard || c.Catchall {
+ t.Fatalf("%s = %+v, want neither capability", neither, c)
+ }
+ if c := w.claim(t, both); !c.Wildcard || !c.Catchall {
+ t.Fatalf("%s = %+v, want both capabilities", both, c)
+ }
+ lookups.Store(0)
+
+ type state struct {
+ raw, etag string
+ serial int64
+ capRows, placementRows int
+ }
+ snapshot := func(host string) state {
+ raw, etag := regionalClaimBytes(t, w.fx.rel, host)
+ return state{raw, etag, serial(t, w.fx),
+ eventsOf(t, w.fx.st, "shop", "domain-capabilities"), eventsOf(t, w.fx.st, "shop", "domain-placements")}
+ }
+ unchanged := func(host string, was state, what string) {
+ t.Helper()
+ requireClaimUnchanged(t, w.fx.rel, host, was.raw, was.etag, what)
+ if now := snapshot(host); now != was {
+ t.Fatalf("%s: serial %d rows %d/%d, was serial %d rows %d/%d", what,
+ now.serial, now.capRows, now.placementRows, was.serial, was.capRows, was.placementRows)
+ }
+ }
+ cases := []struct {
+ host, flags string
+ wildcard, catchall bool
+ changed bool
+ }{
+ {neither, `"wildcard":true`, true, false, true},
+ {neither, `"wildcard":true,"catchall":true`, true, true, true},
+ {both, `"catchall":false`, true, false, true},
+ {both, `"wildcard":false`, false, false, true}, // the cascade
+ {neither, `"wildcard":false,"catchall":false`, false, false, false},
+ {both, `"wildcard":true,"catchall":true`, true, true, false},
+ }
+ for _, c := range cases {
+ what := c.host + " " + c.flags
+ // (a) the attach door naming a bound host.
+ was := snapshot(c.host)
+ code, out := w.capsReq(t, c.host, c.flags)
+ if n := lookups.Load(); n != 0 {
+ t.Fatalf("(a) %s = %d %s after %d CNAME lookups, want none", what, code, out, n)
+ }
+ if c.changed {
+ requireRefusal(t, "(a) "+what, code, out, http.StatusConflict, domains.ErrRegionalClaim.Error())
+ } else if code != http.StatusOK {
+ t.Fatalf("(a) %s = %d %s, want 200", what, code, out)
+ }
+ unchanged(c.host, was, "(a) "+what)
+
+ // (b) the PUT update naming the same values.
+ body := rdBoth()
+ body.Wildcard, body.Catchall = boolp(c.wildcard), boolp(c.catchall)
+ if c.flags == `"catchall":false` {
+ body.Wildcard = nil
+ }
+ code, out = w.put(t, c.host, body)
+ if c.changed {
+ requireRefusal(t, "(b) "+what, code, out, http.StatusConflict, domains.ErrRegionalClaim.Error())
+ } else if code != http.StatusOK {
+ t.Fatalf("(b) %s = %d %s, want 200", what, code, out)
+ }
+ unchanged(c.host, was, "(b) "+what)
+
+ // (c) the claim writer itself.
+ changed, err := domains.SetClaimCapabilities(ctx, w.fx.rel, c.host, w.fx.sqid, "shop", c.wildcard, c.catchall)
+ if c.changed && (changed || !errors.Is(err, domains.ErrRegionalClaim)) {
+ t.Fatalf("(c) %s = %v, %v, want ErrRegionalClaim", what, changed, err)
+ } else if !c.changed && (changed || err != nil) {
+ t.Fatalf("(c) %s = %v, %v, want false, nil", what, changed, err)
+ }
+ unchanged(c.host, was, "(c) "+what)
+ }
+ if n := lookups.Load(); n != 0 {
+ t.Fatalf("CNAME lookups = %d, want 0", n)
+ }
+ if n := wildFailHits(w.fx.srv); n != 0 {
+ t.Fatalf("wildFail counted %d, want 0", n)
+ }
+
+ // The attach door's route-less own-claim branch (apidomains.go, a claim
+ // with Route "") is unreachable for a regional claim: the writer refuses
+ // a regional claim whose Route is not a bound host, every claim the PUT
+ // writes has one, and an attach naming no route is never answered by
+ // that branch.
+ for _, h := range []string{neither, both} {
+ if c := w.claim(t, h); c.Route == "" {
+ t.Fatalf("%s has no Route", h)
+ }
+ }
+ cur, etag, err := domains.GetClaimETag(ctx, w.fx.rel, neither)
+ if err != nil {
+ t.Fatal(err)
+ }
+ next := *cur
+ next.Route = ""
+ if changed, err := domains.SetClaimPlacements(ctx, w.fx.rel, next, cur, etag); changed || !errors.Is(err, domains.ErrBadPlacements) {
+ t.Fatalf("SetClaimPlacements with no Route = %v, %v, want ErrBadPlacements", changed, err)
+ }
+ was := snapshot(neither)
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"), w.token,
+ `{"host":"`+neither+`","wildcard":true}`)
+ if code == http.StatusOK {
+ t.Fatalf("attach naming no route = %d %s: answered as a route-less claim", code, out)
+ }
+ unchanged(neither, was, "attach naming no route")
+ w.mustPut(t, neither, rdSet("uk="+rdUK))
+ if c := w.claim(t, neither); c.Route != rdUK {
+ t.Fatalf("route after an update = %q, want %s", c.Route, rdUK)
+ }
+}
+
+// TestDetachThenRecreateChangesCapabilities (Review Focus 4): the way to
+// change a regional claim's capabilities is to detach it and create it
+// again. The new claim carries both, verified with proof on, and nothing of
+// the old claim's bytes remains.
+func TestDetachThenRecreateChangesCapabilities(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdrev-recreate")
+ w.delegatedCounting()
+ w.mustPut(t, rdHost, rdBoth())
+ old, _ := regionalClaimBytes(t, w.fx.rel, rdHost)
+ code, _, out := rawReq(t, http.MethodDelete, domainsURL(w.fx, w.fx.sqid, "shop")+"/"+rdHost, w.token, "")
+ if code != http.StatusOK || !strings.Contains(out, `"removed":true`) {
+ t.Fatalf("detach = %d %s", code, out)
+ }
+ w.requireNoClaim(t, rdHost, "the detach")
+
+ w.fx.srv.cfg.DomainProof = true
+ w.fx.srv.lookupTXT = txtFor(w.fx.srv, w.fx.sqid, rdHost)
+ body := rdBoth()
+ body.Wildcard, body.Catchall = boolp(true), boolp(true)
+ w.mustPut(t, rdHost, body)
+ c := w.claim(t, rdHost)
+ if !c.Wildcard || !c.Catchall || c.Pending || !c.Regional() {
+ t.Fatalf("recreated claim = %+v, want regional, verified, with both capabilities", c)
+ }
+ if raw, _ := regionalClaimBytes(t, w.fx.rel, rdHost); raw == old {
+ t.Fatalf("recreated claim bytes equal the old claim's: %s", raw)
+ }
+}