carlos / platform Public

Regional domains (#447): T7+T8 fix round 1 (ruling 8): capability decisions under regionalMu, CAS-bound

P1 (covering routes): setDomainCapabilities, the one helper both attach
branches share, now takes regionalMu first, reads the claim under it,
decides ruling 6's refusal, the descendant scan and the enabling gate on
that read, and writes with the new domains.SetClaimCapabilitiesAt against
that read's ETag. A lost CAS writes nothing: the existing retry answer, or
the byte-identical 404 when the claim is gone or no longer the caller's.
Every capability request takes the mutex, disabling ones too. The
instance catch-all doors (Task 8) and the PUT already decide under the
mutex on fresh reads; AttachClaimProven's converge only preserves Catchall
from its own CAS-bound read.

P2-1: the PUT refuses TCP-backed targets (AddrsOrDefault nonempty, legacy
Addr and Addrs) with RD-20.

P2-2: on an update an omitted capability is the stored one, so an
unchanged catchall:true alone is accepted with no write, audit or serial
bump; the catchall-needs-wildcard 422 runs only on create.

Tests: TestStaleCapabilityRequestCannotRestoreACatchall (A parked after
its read, B turns catchall off, the PUT makes a regional child, A resumes:
RD-28, parent off, child intact), TestCapabilityWriteIsBoundToItsRead,
two TCP legs in TestPlacementsPutTargetRefusals, partial-body legs in W14.

Mutation checks:
- decision moved back to a pre-mutex read (write still CAS on a fresh
  read): TestStaleCapabilityRequestCannotRestoreACatchall fails (A 200)
- SetClaimCapabilitiesAt swapped for the rereading SetClaimCapabilities:
  TestCapabilityWriteIsBoundToItsRead fails (200)
- TCP check narrowed to Addr: the Addrs leg fails (200)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 5eb57d7194bb9e0f769f7cf24a476c0ac67864d4 parent 04464e3
5 files changed, +348 −59
  • internal/console/apidomains.go +69 −15
  • internal/console/apiplacements.go +18 −8
  • internal/console/apiplacements_put_test.go +6 −0
  • internal/console/regional_reverse_test.go +181 −0
  • internal/domains/claims.go +74 −36

Intent

Human

<agent-message from="af17d5e1dbe1fd0b0"> #447 build stopped again under ruling 7: the Astra review of Tasks 7+8 found another P1 in the covering-routes family. I haven't fixed it; Paul's go is needed. Branch regional-domains-447, tip 04464e34 (pushed). Progress: - T1-T6 done and reviewed. Ruling 7 is in for T4+T5: a claim's two rows are written in one transaction, and a pair-or-nothing guard test runs 300 seeded passes. T4+T5 R2 came back READY AFTER FIXES; its one P2, the §10.5 wording, is fixed. - T6's two P2s are fixed. - T7 placements PUT and T8 reverse doors are built. Their Astra R1 is NOT READY. - T9 regional readiness and CLI write is built but not reviewed. - T10-T13 not started. The P1 (I checked the citation and it holds): the capability door takes regionalMu and runs the regional-descendant scan only when its own earlier read says the parent's catch-all was off (internal/console/apidomains.go:710). The writer then rereads and writes the current claim. The race: 1. Request A reads a parent with catch-all on. 2. Request B turns the catch-all off. 3. A PUT creates a regional child. 4. A resumes, skips the scan, and turns the catch-all back on above the regional name. How far it reaches: on any box holding the regional rows, the regional apex is an exact key and beats the parent's star. The serving harm therefore falls only on boxes that haven't derived the claim, which is the class §10.5 already accepts. Admission still breaks ruling 4's "refused in both directions". The two P2s: the PUT accepts TCP-backed instance targets (serving fails closed, but admission should refuse them), and resending an unchanged catchall:true on its own returns 422. Options (posted on #447 and in the branch handoff): - A. Every write that leaves catch-all on takes regionalMu, rereads the claim under it, decides on that fresh read and writes against its ETag. Add a deterministic test of this exact sequence with a mutation check. Then one scoped Astra R2 (round 2 of 3 for T7+T8), plus the two P2 fixes. - B. Accept it as the §10.5 class and fix it as a P2 without stopping. - C. Park the branch. I recommend A: it's small and in one place. Send Paul's choice to resume me. My ledger is .superpowers/sdd/2026-10-28-regional-domains-447/progress.md. Scratch has moved to /home/paulca/.cache/rd447/; the old tmp directory was swept, though not by me. </agent-message>

Human

<task-notification> <task-id>af17d5e1dbe1fd0b0</task-id> <tool-use-id>toolu_011bnbJ7bqh5zfrwrsxENMze</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/c2acaf22-306d-491b-b2b6-addbf33b8e87/tasks/af17d5e1dbe1fd0b0.output</output-file> <status>completed</status> <summary>Agent "Controller: build regional domains #447" 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>The build has stopped again: the Astra review of Tasks 7+8 found another P1 in the covering-routes family, and ruling 7 says stop and report. Nothing is fixed yet; Paul needs to choose how to proceed. **What's done** (branch tip 04464e34, pushed): - **Ruling 7** is recorded in the ledger and on #447. Each regional domain's two rows (the apex and the `*.X` catch-all) are now written in one database transaction (27b5fec2). A guard test checks over 300 randomized runs that a box holds both rows or neither, and a test with a hand-route backend at `*.X` survives a restart. The round 2 re-review of Tasks 4+5 came back READY AFTER FIXES; its one P2 was spec wording in §10.5, now fixed (cdf906ab). - **Task 6's** two P2s are fixed (e856dc31): hostnames with a trailing dot now match, and the test no longer picks up deployment settings from the shell. - **Task 8** (reverse doors, race handling, fixed capabilities) is built (0cd1abde). - **Task 9** (regional readiness on the GET and the CLI write) is built (9ef198a0, b892cd42) but not reviewed yet. - Tasks 10 to 13 haven't started. **The P1.** The capability door only takes the regional lock and checks for regional names underneath when its own earlier read says the parent's catch-all is off (`internal/console/apidomains.go:710`). The write then applies to whatever the claim says by then. I checked the code and the race is real: 1. Request A reads a parent with catch-all on and pauses. 2. Request B turns the catch-all off. 3. A regional domain is created under the parent. 4. A resumes, skips the check, and turns the catch-all back on above the regional name. A box that holds the regional rows still serves the regional name correctly, because an exact name beats the parent's catch-all. So the serving harm falls only on boxes that haven't picked up the regional domain, the class §10.5 already accepts. But it breaks ruling 4's rule that overlap is refused in both directions. The review also found two P2s: the PUT accepts TCP-backed instances as targets (they then fail to serve, but should be refused up front), and resending an unchanged `catchall:true` on its own wrongly returns 422. **Decision needed** (posted on #447, in the branch handoff and sent to the root session): - **A. One lock for catch-all writes.** Every write that would leave catch-all on takes the regional lock, rereads the claim under it, decides on that fresh read and writes only if the claim hasn't changed since. Add a test of exactly this sequence that fails with the fix removed, then one scoped Astra re-review (round 2 of 3), plus the two P2 fixes. - **B. Accept it** as part of the §10.5 limit and fix it as a P2 without stopping. - **C. Park the branch** as built. I recommend A: it's a small change in one place and closes the gap rather than leaning on the limit. Scratch has moved to `/home/paulca/.cache/rd447/`. The old one at `/home/paulca/.cache/tmp/claude-1001/rd447/` disappeared mid-run; I didn't delete it, and it held only my scripts, logs and post drafts. The ledger to resume from is `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/regional-domains-447/.superpowers/sdd/2026-10-28-regional-domains-447/progress.md`.</result> <usage><subagent_tokens>330101</subagent_tokens><tool_uses>20</tool_uses><duration_ms>4447448</duration_ms></usage> </task-notification>

diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index dde148016..0f47a06f6 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -45,6 +45,7 @@ import (
"sort"
"strconv"
"strings"
+ "sync/atomic"
"time"
"github.com/carlosframework/platform/internal/certwarm"
@@ -661,21 +662,43 @@ const wildFailMsg = "too many wildcard attempts with no _acme-challenge CNAME in
// flip AFTER the underlying claim attach above has already succeeded and
// established ownership. ok=false means a response has already been
// written — the same resolveAliasRoute convention this file already uses.
+// Both attach branches that take capabilities (the alias and the
+// first-route one) call it; it is the one console writer that sets
+// Catchall from a caller's request.
//
// Absent fields mean "leave unchanged": the door reads the claim's CURRENT
// capabilities as the baseline and overrides only the field(s) the caller
// actually named, so a caller flipping catchall alone cannot accidentally
// clear an already-enabled wildcard, and vice versa.
+//
+// The read, every decision and the write sit under regionalMu (#447, Paul's
+// ruling 8). A catch-all on host covers every one-label name under it, and
+// none of those may be regional (spec §6.7); the placements PUT judges a
+// parent's Catchall under the same mutex. So this door takes regionalMu
+// first, reads the claim under it, decides the regional checks (ruling 6's
+// fixed capabilities, the descendant scan) on that read, and writes with a
+// CAS on that read's ETag (SetClaimCapabilitiesAt). No decision uses a read
+// 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
+// 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) {
if s.cfg.HostClaim {
jsonError(w, http.StatusConflict, claimRefusalText(errClaimAliasCapabilitiesUnsupported))
return false
}
principal := auditActor(p, acct)
- cur, err := domains.GetClaim(ctx, s.cfg.Releases, host)
+ capabilityStage(capabilityBeforeDecision, host)
+ // Held through the write, the audit and the serial bump.
+ s.regionalMu.Lock()
+ defer s.regionalMu.Unlock()
+ cur, etag, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
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, "could not update the hostname's capabilities — try again")
+ jsonError(w, http.StatusBadGateway, capabilitiesRetryMsg)
return false
}
wildcard, catchall := cur.Wildcard, cur.Catchall
@@ -694,22 +717,18 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
// A regional claim's capabilities are fixed when it is created (#447,
// spec §6.3): any change is refused before the DNS gate below, so no
// CNAME lookup, no wildFail count and no write. The same values fall
- // through to SetClaimCapabilities, which answers changed == false.
+ // through to SetClaimCapabilitiesAt, which answers changed == false.
if cur.Regional() && (wildcard != cur.Wildcard || catchall != cur.Catchall) {
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.
+ // On the false-to-true Catchall transition, judged on the read above,
+ // the descendant scan. 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. A claim whose Catchall is already on needs no
+ // scan: the PUT refuses a regional name under it while it is on.
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)}
@@ -744,7 +763,21 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
jsonError(w, http.StatusBadRequest, "that hostname is platform-managed")
return false
}
- capChanged, err := domains.SetClaimCapabilities(ctx, s.cfg.Releases, host, acct.Sqid, app, wildcard, catchall)
+ capChanged, err := domains.SetClaimCapabilitiesAt(ctx, s.cfg.Releases, host, cur, etag, acct.Sqid, app, wildcard, catchall)
+ if errors.Is(err, release.ErrCASConflict) {
+ // The claim changed after the read the decisions above were made on,
+ // and nothing was written. One more read says only how to answer,
+ // never whether to write: a claim gone or no longer the caller's is
+ // the byte-identical 404 below; any other change is the retry.
+ if now, rerr := domains.GetClaim(ctx, s.cfg.Releases, host); errors.Is(rerr, os.ErrNotExist) ||
+ (rerr == nil && (now.Account != acct.Sqid || now.App != app)) {
+ err = domains.ErrHostUnavailable
+ } else {
+ log.Printf("console: api domains capabilities %s/%s %s: claim changed since the read: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, capabilitiesRetryMsg)
+ return false
+ }
+ }
if errors.Is(err, domains.ErrCatchallNeedsWildcard) {
jsonError(w, http.StatusUnprocessableEntity, err.Error())
return false
@@ -759,7 +792,7 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
return false
} else if err != nil {
log.Printf("console: api domains capabilities %s/%s %s: %v", acct.Sqid, app, host, err)
- jsonError(w, http.StatusBadGateway, "could not update the hostname's capabilities — try again")
+ jsonError(w, http.StatusBadGateway, capabilitiesRetryMsg)
return false
}
if capChanged {
@@ -773,6 +806,27 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
return true
}
+// capabilitiesRetryMsg is the capability door's answer to a read or write
+// that did not go through, a lost compare-and-swap included: try again.
+const capabilitiesRetryMsg = "could not update the hostname's capabilities — try again"
+
+// capabilityBeforeDecision is the stage capabilityDoorHook names: in
+// setDomainCapabilities, after every read the attach door made and before
+// regionalMu is taken and the claim read that the decisions use.
+const capabilityBeforeDecision = "before-decision"
+
+// capabilityDoorHook, when set, is called at capabilityBeforeDecision with
+// the host. A TEST SEAM (nil in production): the ruling 8 witness parks a
+// capability request there while other writers run. An atomic.Pointer, as
+// instanceCreateHook is, so a test may set it while a handler reads it.
+var capabilityDoorHook atomic.Pointer[func(stage, host string)]
+
+func capabilityStage(stage, host string) {
+ if h := capabilityDoorHook.Load(); h != nil {
+ (*h)(stage, host)
+ }
+}
+
// 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.
diff --git a/internal/console/apiplacements.go b/internal/console/apiplacements.go
index 0edf6655a..0e2ed5479 100644
--- a/internal/console/apiplacements.go
+++ b/internal/console/apiplacements.go
@@ -477,12 +477,10 @@ func (s *Server) handleAPIDomainPlacementsPut(w http.ResponseWriter, r *http.Req
jsonError(w, ref.Status, ref.Msg)
return
}
+ // The capabilities a create writes: an absent field is false. An update
+ // judges the body against the stored claim instead (step 4).
wantWildcard := in.Wildcard != nil && *in.Wildcard
wantCatchall := in.Catchall != nil && *in.Catchall
- if wantCatchall && !wantWildcard {
- jsonError(w, http.StatusUnprocessableEntity, domains.ErrCatchallNeedsWildcard.Error())
- return
- }
// Step 4. The app lock and the hostname exclusion in every mode:
// instance create's regional recheck runs under that exclusion, and so
@@ -523,6 +521,9 @@ func (s *Server) handleAPIDomainPlacementsPut(w http.ResponseWriter, r *http.Req
case cur == nil:
case own && cur.Regional():
create = false
+ // An omitted capability is the stored one, so a body naming only
+ // an unchanged catchall:true is the same values, written nowhere
+ // (T7+T8 R1 P2-2); a named one that differs is refused.
if (in.Wildcard != nil && *in.Wildcard != cur.Wildcard) || (in.Catchall != nil && *in.Catchall != cur.Catchall) {
// Ruling 6: fixed at creation. The caller's own claim, so
// saying so reveals nothing.
@@ -544,6 +545,12 @@ func (s *Server) handleAPIDomainPlacementsPut(w http.ResponseWriter, r *http.Req
jsonError(w, http.StatusConflict, hostUnavailableMsg)
return
}
+ // A create writes the body's capabilities, absent ones false, and a
+ // catch-all nobody can serve TLS for is refused, nothing written.
+ if create && wantCatchall && !wantWildcard {
+ jsonError(w, http.StatusUnprocessableEntity, domains.ErrCatchallNeedsWildcard.Error())
+ return
+ }
// Step 5. One snapshot, shared by every check below and the answer.
var (
@@ -665,9 +672,9 @@ func onceProver(prove func() bool) func() bool {
// region a code (the home's name is ""), named once; each host a hostname,
// named once; and each host an instance record of acct/app in that region
// that can carry a regional name: an instance (no static or service
-// kind), not a replica, not fleet-placed. A host that is not one answers
-// RD-20 whatever the reason, so the door says nothing of other apps' and
-// accounts' instances. Sorted by nothing: body order is kept.
+// kind), not a replica, not fleet-placed, not TCP-backed (Addr or Addrs).
+// A host that is not one answers RD-20 whatever the reason, so the door
+// says nothing of other apps' and accounts' instances. Sorted by nothing: body order is kept.
func (s *Server) placementsBindings(ctx context.Context, acct *Account, app string, in []placementIn) ([]domains.Placement, *doorRefusal) {
if len(in) == 0 || len(in) > domains.MaxPlacements {
return nil, &doorRefusal{http.StatusBadRequest, placementsCountMsg}
@@ -708,7 +715,10 @@ func (s *Server) placementsBindings(ctx context.Context, acct *Account, app stri
for i, b := range set {
rec, ok := byHost[b.Host]
_, fleet := registry.FleetPlacement(rec.Region)
- if !ok || rec.Region != b.Region || rec.KindOrDefault() != "instance" || rec.Role != "" || fleet {
+ // A TCP-backed instance (Addr or Addrs) has no derived socket, so
+ // RegionalTarget could never serve it there.
+ tcp := len(rec.AddrsOrDefault()) > 0
+ if !ok || rec.Region != b.Region || rec.KindOrDefault() != "instance" || rec.Role != "" || fleet || tcp {
return nil, &doorRefusal{http.StatusBadRequest, placementsNotInstanceMsg(b.Host, named[i])}
}
}
diff --git a/internal/console/apiplacements_put_test.go b/internal/console/apiplacements_put_test.go
index d1cf66216..f79e15bca 100644
--- a/internal/console/apiplacements_put_test.go
+++ b/internal/console/apiplacements_put_test.go
@@ -318,12 +318,18 @@ func TestPlacementsPutTargetRefusals(t *testing.T) {
w.putRecord(t, w.fx.sqid, "shop", "shop-f.example.net", "fleet/home", nil)
w.putRecord(t, w.fx.sqid, "shop", "shop-s.example.net", "uk", func(r *provision.Record) { r.Kind = "static" })
w.putRecord(t, w.fx.sqid, "shop", "shop-v.example.net", "uk", func(r *provision.Record) { r.Kind = "service" })
+ // TCP-backed instances (a legacy Addr, and Addrs): no derived socket, so
+ // RegionalTarget could never serve them (T7+T8 R1 P2-1).
+ w.putRecord(t, w.fx.sqid, "shop", "shop-a.example.net", "uk", func(r *provision.Record) { r.Addr = "127.0.0.1:8080" })
+ w.putRecord(t, w.fx.sqid, "shop", "shop-m.example.net", "uk", func(r *provision.Record) { r.Addrs = []string{"127.0.0.1:8080", "127.0.0.1:8081"} })
for _, c := range []struct{ what, region, host string }{
{"a region mismatch", "uk", rdIE},
{"a replica", "uk", "shop-r.example.net"},
{"a fleet-placed instance", "fleet/home", "shop-f.example.net"},
{"a static site", "uk", "shop-s.example.net"},
{"a service", "uk", "shop-v.example.net"},
+ {"a legacy Addr upstream", "uk", "shop-a.example.net"},
+ {"an Addrs upstream set", "uk", "shop-m.example.net"},
{"a sidecar", "uk", "bot.sidecar.internal"},
{"not a hostname", "uk", "not a host"},
} {
diff --git a/internal/console/regional_reverse_test.go b/internal/console/regional_reverse_test.go
index 346a3ede6..63d9cbc75 100644
--- a/internal/console/regional_reverse_test.go
+++ b/internal/console/regional_reverse_test.go
@@ -10,6 +10,7 @@ package console
import (
"context"
+ "encoding/json"
"errors"
"fmt"
"io"
@@ -537,6 +538,39 @@ func TestRegionalClaimCapabilitiesAreFixed(t *testing.T) {
}
unchanged(c.host, was, "(c) "+what)
}
+
+ // A body naming one capability: the other is the stored one (T7+T8 R1
+ // P2-2). On the claim with both, an unchanged catchall:true alone, and
+ // wildcard:true alone, are the same values: 200 from the PUT and the
+ // attach door, no write, no audit row, no serial bump. On the claim
+ // with neither, catchall:true alone is a change: RD-26, not the
+ // creation-time 422.
+ for _, c := range []struct {
+ host, flags string
+ body placementsPutBody
+ changed bool
+ }{
+ {both, `"catchall":true`, placementsPutBody{Placements: rdBoth().Placements, Catchall: boolp(true)}, false},
+ {both, `"wildcard":true`, placementsPutBody{Placements: rdBoth().Placements, Wildcard: boolp(true)}, false},
+ {neither, `"catchall":true`, placementsPutBody{Placements: rdBoth().Placements, Catchall: boolp(true)}, true},
+ } {
+ what := c.host + " " + c.flags + " alone"
+ was := snapshot(c.host)
+ code, out := w.put(t, c.host, c.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)
+ code, out = w.capsReq(t, c.host, c.flags)
+ 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)
+ }
if n := lookups.Load(); n != 0 {
t.Fatalf("CNAME lookups = %d, want 0", n)
}
@@ -604,3 +638,150 @@ func TestDetachThenRecreateChangesCapabilities(t *testing.T) {
t.Fatalf("recreated claim bytes equal the old claim's: %s", raw)
}
}
+
+// parkCapability sets capabilityDoorHook to hold the first capability
+// request on host at stage until resume is closed; held closes when it gets
+// there. Later requests pass straight through.
+func parkCapability(t *testing.T, stage, host string) (held, resume chan struct{}) {
+ t.Helper()
+ held, resume = make(chan struct{}), make(chan struct{})
+ // Not a sync.Once: Once.Do blocks every concurrent caller until the
+ // first returns, which would park request B behind A.
+ var taken atomic.Bool
+ h := func(s, h string) {
+ if s != stage || h != host || !taken.CompareAndSwap(false, true) {
+ return
+ }
+ close(held)
+ <-resume
+ }
+ capabilityDoorHook.Store(&h)
+ t.Cleanup(func() {
+ capabilityDoorHook.Store(nil)
+ select { // a failed test never leaves the request parked
+ case <-resume:
+ default:
+ close(resume)
+ }
+ })
+ return held, resume
+}
+
+// TestStaleCapabilityRequestCannotRestoreACatchall (ruling 8, the T7+T8 R1
+// P1): request A re-sends wildcard and catchall true for example.com, whose
+// catch-all is on, and is parked after every read its door made before the
+// capability decision. Request B turns the catch-all off, and a placements
+// PUT then makes shop.example.com regional under it. A resumes. A is
+// refused (RD-28, or the door's retry answer), the parent's catch-all stays
+// off and the regional claim is untouched: the decision is made on a read
+// taken under regionalMu, never on one taken before it.
+func TestStaleCapabilityRequestCannotRestoreACatchall(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdrev-stalecaps")
+ w.delegatedCounting()
+ const parent = "example.com"
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", parent, rdIE)
+ if _, err := domains.SetClaimCapabilities(context.Background(), w.fx.rel, parent, w.fx.sqid, "shop", true, true); err != nil {
+ t.Fatal(err)
+ }
+
+ held, resume := parkCapability(t, capabilityBeforeDecision, parent)
+ a := make(chan rdAnswer, 1)
+ go func() {
+ a <- rdDo(http.MethodPost, domainsURL(w.fx, w.fx.sqid, "shop"), w.token,
+ `{"host":"`+parent+`","route":"`+rdIE+`","wildcard":true,"catchall":true}`)
+ }()
+ await(t, held, "request A at "+capabilityBeforeDecision)
+
+ // B: the catch-all off.
+ if code, out := w.capsReq(t, parent, `"catchall":false`); code != http.StatusOK {
+ t.Fatalf("B catchall off = %d %s, want 200", code, out)
+ }
+ if c := w.claim(t, parent); !c.Wildcard || c.Catchall {
+ t.Fatalf("after B, claim %s = %+v, want wildcard on and catchall off", parent, c)
+ }
+ // The PUT: shop.example.com regional under the parent.
+ w.mustPut(t, rdHost, rdBoth())
+ regional, regionalETag := regionalClaimBytes(t, w.fx.rel, rdHost)
+ parentRaw, parentETag := regionalClaimBytes(t, w.fx.rel, parent)
+ before := serial(t, w.fx)
+ rows := eventsOf(t, w.fx.st, "shop", "domain-capabilities")
+
+ close(resume)
+ got := await(t, a, "request A's answer")
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ t.Logf("request A answered %d %s", got.code, strings.TrimSpace(got.out))
+ var e struct {
+ Error string `json:"error"`
+ }
+ _ = json.Unmarshal([]byte(got.out), &e)
+ refused := (got.code == http.StatusConflict && e.Error == rdCatchallMsg(parent)) ||
+ (got.code == http.StatusBadGateway && e.Error == capabilitiesRetryMsg)
+ if !refused {
+ t.Fatalf("request A = %d %s, want 409 %q or 502 %q", got.code, got.out, rdCatchallMsg(parent), capabilitiesRetryMsg)
+ }
+ if c := w.claim(t, parent); c.Catchall {
+ t.Fatalf("claim %s = %+v: a stale request restored the catch-all over regional %s", parent, c, rdHost)
+ }
+ requireClaimUnchanged(t, w.fx.rel, parent, parentRaw, parentETag, "request A")
+ requireClaimUnchanged(t, w.fx.rel, rdHost, regional, regionalETag, "request A")
+ if c := w.claim(t, rdHost); !c.Regional() {
+ t.Fatalf("claim %s = %+v, want it regional", rdHost, c)
+ }
+ 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 != rows {
+ t.Fatalf("%d domain-capabilities rows, was %d", n, rows)
+ }
+}
+
+// TestCapabilityWriteIsBoundToItsRead (ruling 8): the capability door writes
+// against the ETag of the read its decisions used. A claim changed between
+// that read and the write (here a writer outside regionalMu, injected just
+// before the door's Put) answers the door's retry, and nothing of the
+// request is written over the change.
+func TestCapabilityWriteIsBoundToItsRead(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdrev-capcas")
+ w.delegatedCounting()
+ ctx := context.Background()
+ const host = "cat.example.net"
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", host, rdIE)
+ if _, err := domains.SetClaimCapabilities(ctx, w.fx.rel, host, w.fx.sqid, "shop", true, false); err != nil {
+ t.Fatal(err)
+ }
+ st := w.wrap()
+ var injected atomic.Bool
+ st.beforePut = func(key string) {
+ if key != domains.ClaimKey(host) || !injected.CompareAndSwap(false, true) {
+ return
+ }
+ c := w.claim(t, host)
+ c.CreatedBy = "someone@example.com"
+ body, err := json.Marshal(c)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ _, etag := regionalClaimBytes(t, w.fx.rel, host)
+ if _, err := w.fx.rel.Put(ctx, domains.ClaimKey(host), body, etag); err != nil {
+ t.Error(err)
+ }
+ }
+ before := serial(t, w.fx)
+ code, out := w.capsReq(t, host, `"catchall":true`)
+ requireRefusal(t, "catchall on with the claim changed under it", code, out, http.StatusBadGateway, capabilitiesRetryMsg)
+ if !injected.Load() {
+ t.Fatal("the door never wrote the claim: the injection did not run")
+ }
+ if c := w.claim(t, host); c.Catchall || c.CreatedBy != "someone@example.com" {
+ t.Fatalf("claim %s = %+v, want the injected change and catchall off", host, c)
+ }
+ 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)
+ }
+}
diff --git a/internal/domains/claims.go b/internal/domains/claims.go
index 656688bc2..e1d14654d 100644
--- a/internal/domains/claims.go
+++ b/internal/domains/claims.go
@@ -981,16 +981,21 @@ func HostDenied(host string, deny []string) bool {
// is a config error, not a state — refused at the write path, never stored.
var ErrCatchallNeedsWildcard = errors.New("catchall requires wildcard (no cert could serve the catch-all)")
-// SetClaimCapabilities is the ONLY writer of a claim's Wildcard/Catchall
-// fields on an existing claim (SetClaimPlacements sets them once, when it
-// creates a regional claim, and this refuses to change them on one after:
-// ErrRegionalClaim, with the claim's own values accepted as a no-op).
-// AttachClaim's converge deliberately repoints Route and nothing
-// else — it can preserve these fields but never set them (#151's ruling) —
-// so capability changes go through this CAS read-modify-write, which
-// preserves every other field. Owner-gated: a caller who does not hold the
-// claim gets the same neutral ErrHostUnavailable the attach door uses, and
-// a missing claim answers identically (no existence oracle).
+// SetClaimCapabilities and SetClaimCapabilitiesAt are the ONLY writers of
+// a claim's Wildcard/Catchall fields on an existing claim
+// (SetClaimPlacements sets them once, when it creates a regional claim, and
+// these refuse to change them on one after: ErrRegionalClaim, with the
+// claim's own values accepted as a no-op). AttachClaim's converge
+// deliberately repoints Route and nothing else — it can preserve these
+// fields but never set them (#151's ruling) — so capability changes go
+// through this CAS read-modify-write, which preserves every other field.
+// Owner-gated: a caller who does not hold the claim gets the same neutral
+// ErrHostUnavailable the attach door uses, and a missing claim answers
+// identically (no existence oracle).
+//
+// SetClaimCapabilities rereads and retries a lost CAS itself. The console's
+// capability door does not use it: it decides under regionalMu from its own
+// read and writes with SetClaimCapabilitiesAt against that read (#447).
func claimRawSetClaimCapabilities(ctx context.Context, s release.Store, host, account, app string, wildcard, catchall bool) (changed bool, err error) {
if catchall && !wildcard {
return false, ErrCatchallNeedsWildcard
@@ -1002,37 +1007,63 @@ func claimRawSetClaimCapabilities(ctx context.Context, s release.Store, host, ac
} else if err != nil {
return false, err
}
- // An instance catch-all has no capabilities to set: it answers as a
- // claim the caller does not hold. No door reaches this with a "*"
- // host; the check keeps it true for any caller that ever does.
- if cur.Account != account || cur.App != app || cur.Instances {
- return false, ErrHostUnavailable
- }
- if cur.Wildcard == wildcard && cur.Catchall == catchall {
- return false, nil
- }
- // A regional claim's capabilities are fixed when the placements door
- // creates it (#447 ruling 6); the same values are accepted above.
- if cur.Regional() {
- return false, ErrRegionalClaim
- }
- next := *cur
- next.Wildcard = wildcard
- next.Catchall = catchall
- body, err := json.Marshal(next)
- if err != nil {
- return false, err
- }
- if _, err := s.Put(ctx, ClaimKey(host), body, etag); err == nil {
- return true, nil
- } else if errors.Is(err, release.ErrCASConflict) && attempt < 3 {
+ changed, err := setClaimCapabilitiesAt(ctx, s, host, cur, etag, account, app, wildcard, catchall)
+ if errors.Is(err, release.ErrCASConflict) && attempt < 3 {
continue
- } else {
- return false, err
}
+ return changed, err
}
}
+// claimRawSetClaimCapabilitiesAt writes wildcard and catchall onto cur, the
+// claim at host as the caller read it, with a CAS on etag, the ETag of that read.
+// It never rereads: the caller judged cur (for the console, the regional
+// checks under regionalMu), so a claim that changed since is
+// release.ErrCASConflict, returned as it is with nothing written, for the
+// caller to answer. The rules are SetClaimCapabilities': catchall needs
+// wildcard, the owner gate, the same values are a no-op, and a regional
+// claim's capabilities are fixed.
+func claimRawSetClaimCapabilitiesAt(ctx context.Context, s release.Store, host string, cur *Claim, etag, account, app string, wildcard, catchall bool) (changed bool, err error) {
+ if catchall && !wildcard {
+ return false, ErrCatchallNeedsWildcard
+ }
+ return setClaimCapabilitiesAt(ctx, s, host, cur, etag, account, app, wildcard, catchall)
+}
+
+func setClaimCapabilitiesAt(ctx context.Context, s release.Store, host string, cur *Claim, etag, account, app string, wildcard, catchall bool) (changed bool, err error) {
+ // An instance catch-all has no capabilities to set: it answers as a
+ // claim the caller does not hold. No door reaches this with a "*"
+ // host; the check keeps it true for any caller that ever does.
+ if cur == nil || cur.Account != account || cur.App != app || cur.Instances {
+ return false, ErrHostUnavailable
+ }
+ if cur.Wildcard == wildcard && cur.Catchall == catchall {
+ return false, nil
+ }
+ // A regional claim's capabilities are fixed when the placements door
+ // creates it (#447 ruling 6); the same values are accepted above.
+ if cur.Regional() {
+ return false, ErrRegionalClaim
+ }
+ // An empty etag would be a create-only Put, which an existing claim
+ // always fails; refused here so the answer is the CAS's, not a 412
+ // dressed as something else.
+ if etag == "" {
+ return false, release.ErrCASConflict
+ }
+ next := *cur
+ next.Wildcard = wildcard
+ next.Catchall = catchall
+ body, err := json.Marshal(next)
+ if err != nil {
+ return false, err
+ }
+ if _, err := s.Put(ctx, ClaimKey(host), body, etag); err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
// MaxPathsPerClaim bounds a claim's prefix map. Unlike maxWildcardDomains
// this defends no external budget — there is no ACME equivalent for a path
// row — it bounds the claim object's size and the per-box fold that reads it
@@ -1194,6 +1225,13 @@ func SetClaimCapabilities(ctx context.Context, s release.Store, host, account, a
})
return
}
+func SetClaimCapabilitiesAt(ctx context.Context, s release.Store, host string, cur *Claim, etag, account, app string, wildcard, catchall bool) (claimResult0 bool, claimResult1 error) {
+ claimResult1 = release.WithAppMutation(ctx, s, account, app, "domains.SetClaimCapabilitiesAt", func(claimContext context.Context) error {
+ claimResult0, claimResult1 = claimRawSetClaimCapabilitiesAt(claimContext, s, host, cur, etag, account, app, wildcard, catchall)
+ return claimResult1
+ })
+ return
+}
func SetClaimPaths(ctx context.Context, s release.Store, host, account, app string, paths map[string]string) (claimResult0 bool, claimResult1 error) {
claimResult1 = release.WithAppMutation(ctx, s, account, app, "domains.SetClaimPaths", func(claimContext context.Context) error {
claimResult0, claimResult1 = claimRawSetClaimPaths(claimContext, s, host, account, app, paths)