carlos / platform Public

Regional domains (#447) Task 2: regional claim shape and domains writer rules

A schema-2 claim with placements (Placement, MaxPlacements, Regional,
PlacementFor, ValidPlacements, RegionalRoute), SetClaimPlacements
(claimRawSetClaimPlacements wrapped by release.WithAppMutation),
GetClaimETag, PendingLive, ErrRegionalClaim (RD-26), ErrBadPlacements.
Readers accept schema 1 without placements and schema 2 only when
Regional and ValidPlacements; everything else is refused and skipped.
Writers: AttachClaimProven no-ops a bound host and refuses any other
route; SetClaimCapabilities refuses a change on a regional claim (same
values accepted, no write); SetClaimPaths and AttachInstanceCatchall
refuse; ReconcileAliasesReport skips a regional claim (Task 4 replaces
the skip with the derivation); the host-claim attach (claim_alias.go)
answers a regional claim as AttachClaimProven does.

Reader audit:
- internal/domains/claims.go: branches here (readers, writers above).
- internal/domains/aliases.go: skip here; derivation and instance
  catch-all regional parent in Task 4.
- internal/domains/claimcache.go: safe, decodes through readClaimDetail.
- internal/console/claim_alias.go: branches here (explicit Regional()
  after the owner check: bound host no-op, else ErrRegionalClaim).
- internal/console/teamdoors.go: Task 3 (inScopeClaim).
- internal/console/apex.go: Task 3 (hostClaimHolder).
- internal/console/apidomains.go: Task 3 (attach, capabilities, paths,
  domainItem).
- internal/console/domainattach.go: Task 3 (claimRefusal).
- internal/console/claim_first_route.go: Task 3.
- internal/console/apiplacements.go: Task 1's GET reads Route as a
  single-mode target; Task 9 adds the regional view.
- internal/console/domaincatchall.go: safe, reads Account/App of the
  caller's own claim and lists instance catch-alls only; the regional
  intercept is Task 8.
- internal/console/appsettings.go: safe, a listing (state from readings
  by Host); never treats Route as an alias.
- internal/console/domainstate.go: safe, claimState reads Pending only.
- internal/console/apiinstancemove_offline.go: safe, reads Acquisition.
- internal/console/server.go: safe, the ClaimCache field only.
- internal/console/claim_pending_views.go: safe, host-claim objects
  under control/hosts/ (hostops.ListClaims).
- internal/console/claim_purge.go: safe, HostClaim mode; a claim with no
  Acquisition (a regional one) holds the purge at ErrPending as any
  legacy claim does; it never routes.
- internal/console/claim_retire.go: safe, HostClaim mode; deletes only a
  claim matching an acquisition, which a regional claim lacks.
- internal/edge/storedoor.go: safe, relays the JSON object whole
  (storedoor.go:757), so placements reach the box.
- internal/host/agent.go, assetauthority.go, changeindex.go,
  edgesfile.go: safe, ClaimCache plumbing and route_aliases only.
- internal/hostops/backfill.go: safe, requires a matching Acquisition.
- internal/hostops/create_effects.go, production_create.go: HostClaim
  create path, left unchanged as spec §6.3 says (beginClaimCreate); the
  Reload deny is the backstop.
- internal/hostops/loads.go, purge_hosts.go, recovery.go: safe,
  control/hosts/ objects only.
- internal/mail/domainclaim.go: safe, mail domain claims (comment only).
- internal/registry/registry.go: safe, comments only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 89a8104b16b2564a9ce788bb124700c9c8393aac parent fb65398
5 files changed, +710 −10
  • internal/console/claim_alias.go +13 −0
  • internal/console/claim_alias_test.go +51 −0
  • internal/domains/aliases.go +5 −0
  • internal/domains/claims.go +215 −10
  • internal/domains/regional_claims_test.go +426 −0

Intent

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/1118974.sock" from-name="platform-01" from-mode="bypass"> Release coordination on carlos/platform: is a release or roll worth cutting now, or should it wait for your work? Main is three console-only commits past v0.30.2: 1c5db50 (Analytics tab overhaul + Overview traffic card, mine, just merged), 0c39af30 and 89491675 (billing UI). I'm asking platform-46, platform-81 and platform-1d. Please reply with: (1) what you are working on; (2) whether you expect to merge to main in the next few hours, and anything that should ride the same release; (3) whether you are mid-release or mid-roll right now, or on a box or console whose roll this would disturb. A one-line answer is fine. If you're the one cutting releases today, say so and I'll leave it to you. </cross-session-message>

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/1118974.sock" from-name="platform-01" from-mode="bypass"> FYI: v0.30.3 is being cut now from main 1c5db50e and rolled dev then flagship by platform-01's release agent (log: ~/.cache/release-v0.30.3/roll-log.md). Flagship goes v0.30.1 to v0.30.3, so it picks up v0.30.2's changes too. Please don't start another release or roll until I say it's done. </cross-session-message>

diff --git a/internal/console/claim_alias.go b/internal/console/claim_alias.go
index 60b11a682..bde52ce1c 100644
--- a/internal/console/claim_alias.go
+++ b/internal/console/claim_alias.go
@@ -94,6 +94,19 @@ func (s *Server) attachDomainClaim(ctx context.Context, acct *Account, app strin
if current.Account != acct.Sqid || current.App != app {
return false, false, false, domains.ErrHostUnavailable
}
+ // A regional claim (#447) is the placements door's alone, and this
+ // decode skips the schema check GetClaim makes, so it is answered
+ // here as AttachClaimProven answers it: a bound host is a no-op,
+ // any other route is refused. The placements door refuses host-claim
+ // mode, so a regional claim here was written before the mode changed.
+ if current.Regional() {
+ for _, p := range current.Placements {
+ if p.Host == incoming.Route {
+ return false, false, false, nil
+ }
+ }
+ return false, false, false, domains.ErrRegionalClaim
+ }
if current.Acquisition == "" || current.Route == "" || current.RecordIncarnation == "" || etag == "" {
return false, false, false, hostops.ErrPending
}
diff --git a/internal/console/claim_alias_test.go b/internal/console/claim_alias_test.go
index 6ed50b025..0b2bc4929 100644
--- a/internal/console/claim_alias_test.go
+++ b/internal/console/claim_alias_test.go
@@ -11,6 +11,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/hostops"
"github.com/carlosframework/platform/internal/release"
)
@@ -100,3 +101,53 @@ func TestFlaggedDomainCapabilitiesRefuseBeforeBucketRead(t *testing.T) {
t.Fatalf("status=%d", w.Code)
}
}
+
+// TestHostClaimAttachOnARegionalClaim: the host-claim attach decodes the
+// claim itself, so it answers a regional claim (#447) as AttachClaimProven
+// does: a bound host is a no-op, any other route is ErrRegionalClaim, and
+// the claim is never rewritten.
+func TestHostClaimAttachOnARegionalClaim(t *testing.T) {
+ ctx := context.Background()
+ cx := newClaimCase(t)
+ cx.claimedRoute(t)
+ acct, err := cx.st.AccountBySqid("bab")
+ if err != nil {
+ t.Fatal(err)
+ }
+ put := func(host, bound string) []byte {
+ t.Helper()
+ c := domains.Claim{Host: host, Account: "bab", App: "titogo", Route: bound, CreatedAt: "t",
+ Placements: []domains.Placement{{Region: "", Host: bound}}}
+ if _, err := domains.SetClaimPlacements(ctx, cx.rel, c, nil, ""); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := cx.rel.Get(ctx, domains.ClaimKey(host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+ }
+ attach := func(host string) error {
+ t.Helper()
+ created, changed, pending, err := cx.srv.attachDomainClaim(ctx, acct, "titogo",
+ domains.Claim{Host: host, Account: "bab", App: "titogo", Route: claimAliasRoute}, time.Now(), nil)
+ if created || changed || pending {
+ t.Fatalf("attach %s: created=%v changed=%v pending=%v", host, created, changed, pending)
+ }
+ return err
+ }
+ for host, bound := range map[string]string{"shop.example.com": claimAliasRoute, "shop-two.example.com": "shop-uk.example.net"} {
+ before := put(host, bound)
+ err := attach(host)
+ switch {
+ case bound == claimAliasRoute && err != nil:
+ t.Fatalf("attach naming a bound host: %v, want a no-op", err)
+ case bound != claimAliasRoute && !errors.Is(err, domains.ErrRegionalClaim):
+ t.Fatalf("attach naming another route: %v, want ErrRegionalClaim", err)
+ }
+ after, _, err := cx.rel.Get(ctx, domains.ClaimKey(host))
+ if err != nil || string(after) != string(before) {
+ t.Fatalf("claim %s rewritten:\n%s\n%s (%v)", host, before, after, err)
+ }
+ }
+}
diff --git a/internal/domains/aliases.go b/internal/domains/aliases.go
index e8c80ad22..6184b3420 100644
--- a/internal/domains/aliases.go
+++ b/internal/domains/aliases.go
@@ -400,6 +400,11 @@ func ReconcileAliasesReport(ctx context.Context, s release.Store, reg *registry.
if c.Pending {
continue
}
+ // A regional claim (#447) is never a plain alias of its Route, a
+ // wildcard parent or a prefix map: it derives nothing here.
+ if c.Regional() {
+ continue
+ }
// Plain alias derivation (#164): a routeless (first-route) claim is
// not an alias — that skip is scoped to THIS half only, so a
// routeless Wildcard claim still falls through to the wildcard
diff --git a/internal/domains/claims.go b/internal/domains/claims.go
index fc23ebad9..dfe213e9b 100644
--- a/internal/domains/claims.go
+++ b/internal/domains/claims.go
@@ -8,6 +8,7 @@
package domains
import (
+ "bytes"
"context"
"crypto/sha256"
"encoding/hex"
@@ -17,6 +18,7 @@ import (
"log"
"os"
"regexp"
+ "sort"
"strings"
"time"
@@ -91,6 +93,14 @@ type Claim struct {
// a hostname (NormalizeAliasHost), so an older console cannot rewrite or
// detach it either. Declared here for the round-trip reason above.
Instances bool `json:"instances,omitempty"`
+ // Placements makes this a regional claim (#447): the hostname is served
+ // in each listed region by that region's bound host, never backhauled.
+ // Only SetClaimPlacements writes it, and only on a schema-2 claim, which
+ // every binary before this field skips (getClaimETag, readClaimDetail),
+ // so an old box derives nothing from a regional claim rather than routing
+ // it as a plain alias of Route. A schema-1 claim never carries it.
+ // Declared here for the round-trip reason above.
+ Placements []Placement `json:"placements,omitempty"`
// Pending marks a claim whose writer has not yet proved control of the
// hostname (#215): no TXT record carrying ChallengeToken was found at
// ChallengeName(Host) when it was written. A pending claim is a
@@ -113,6 +123,152 @@ type Claim struct {
PendingUntil string `json:"pending_until,omitempty"`
}
+// MaxPlacements bounds a regional claim's placement list, which holds at
+// most one entry per region.
+const MaxPlacements = 8
+
+// Placement binds one region of a regional claim to the host that serves the
+// claim's name there.
+type Placement struct {
+ Region string `json:"region"` // a stored region code: "" is the home region
+ Host string `json:"host"`
+}
+
+// Regional reports whether c is a regional claim (#447).
+func (c Claim) Regional() bool { return len(c.Placements) > 0 }
+
+// PlacementFor is the host bound to region, or "" when the claim has none
+// there.
+func (c Claim) PlacementFor(region string) string {
+ for _, p := range c.Placements {
+ if p.Region == region {
+ return p.Host
+ }
+ }
+ return ""
+}
+
+// boundHost reports whether host is one of c's bound hosts.
+func (c Claim) boundHost(host string) bool {
+ for _, p := range c.Placements {
+ if p.Host == host {
+ return true
+ }
+ }
+ return false
+}
+
+// ValidPlacements reports whether c is a well-formed regional claim: schema
+// 2; 1 to MaxPlacements placements with unique regions and unique hosts, each
+// host a normalised hostname outside the reserved sidecar suffix; Route one of
+// those hosts; and none of the shapes a regional claim never takes (a prefix
+// map, an instance catch-all, a pending reservation).
+func (c Claim) ValidPlacements() bool {
+ if c.Schema != 2 || len(c.Placements) == 0 || len(c.Placements) > MaxPlacements {
+ return false
+ }
+ if len(c.Paths) > 0 || c.Instances || c.Pending {
+ return false
+ }
+ regions := make(map[string]bool, len(c.Placements))
+ hosts := make(map[string]bool, len(c.Placements))
+ for _, p := range c.Placements {
+ if regions[p.Region] || hosts[p.Host] {
+ return false
+ }
+ regions[p.Region], hosts[p.Host] = true, true
+ if n, ok := NormalizeAliasHost(p.Host); !ok || n != p.Host || strings.HasSuffix(p.Host, sidecarSuffix) {
+ return false
+ }
+ }
+ return hosts[c.Route]
+}
+
+// RegionalRoute is the Route a regional claim with placements ps carries:
+// keep when it is still one of the bound hosts, otherwise the host bound to
+// the first region in code order, the home region ("") first. The placements
+// door uses it on create (keep "") and on every update.
+func RegionalRoute(ps []Placement, keep string) string {
+ first := -1
+ for i, p := range ps {
+ if p.Host == keep && keep != "" {
+ return keep
+ }
+ if first < 0 || p.Region < ps[first].Region {
+ first = i
+ }
+ }
+ if first < 0 {
+ return ""
+ }
+ return ps[first].Host
+}
+
+// claimSchemaOK is the reader rule for a decoded claim: schema 1 (or an
+// older body with no schema) without placements, or schema 2 with valid
+// placements. Anything else, newer schemas included, is refused and skipped.
+func claimSchemaOK(c Claim) bool {
+ if c.Schema <= 1 {
+ return !c.Regional()
+ }
+ return c.Schema == 2 && c.Regional() && c.ValidPlacements()
+}
+
+// claimSchemaRefusal says why claimSchemaOK refused c.
+func claimSchemaRefusal(c Claim) string {
+ if c.Schema > 2 {
+ return fmt.Sprintf("schema %d is newer than this binary understands", c.Schema)
+ }
+ return fmt.Sprintf("schema %d with invalid placements", c.Schema)
+}
+
+// ErrRegionalClaim is returned by every writer asked to change a regional
+// claim in a way only the placements door may: a route that is not one of
+// its bound hosts, its capabilities, its prefix map, or an instance catch-all
+// under it.
+var ErrRegionalClaim = errors.New("this is a regional domain. carlos domains placements is the only way to change where it is served, and its wildcard and catch-all settings are fixed when it is created. to change those, detach it and create it again.")
+
+// ErrBadPlacements is returned by SetClaimPlacements for a claim that would
+// not pass ValidPlacements once written.
+var ErrBadPlacements = errors.New("domains: invalid placements")
+
+// claimRawSetClaimPlacements writes next as a regional claim: schema 2 and
+// verified are stamped here, the placements are stored in region order, and
+// the rest is written as given. cur nil and etag "" is a create-only Put;
+// otherwise the Put is a CAS on etag. When the bytes equal cur's, nothing is
+// written (changed false). release.ErrCASConflict is returned as it is, with
+// no retry: the caller decided from cur, so a lost race is the caller's to
+// re-read and judge.
+func claimRawSetClaimPlacements(ctx context.Context, s release.Store, next Claim, cur *Claim, etag string) (changed bool, err error) {
+ next.Schema = 2
+ next.Pending, next.PendingUntil = false, ""
+ next.Placements = append([]Placement(nil), next.Placements...)
+ sort.SliceStable(next.Placements, func(i, j int) bool { return next.Placements[i].Region < next.Placements[j].Region })
+ if !next.ValidPlacements() || next.Account == "" || next.App == "" {
+ return false, ErrBadPlacements
+ }
+ if n, ok := NormalizeAliasHost(next.Host); !ok || n != next.Host {
+ return false, ErrBadPlacements
+ }
+ body, err := json.Marshal(next)
+ if err != nil {
+ return false, err
+ }
+ if cur != nil {
+ old, err := json.Marshal(*cur)
+ if err != nil {
+ return false, err
+ }
+ if bytes.Equal(old, body) {
+ return false, nil
+ }
+ }
+ if _, err := s.Put(ctx, ClaimKey(next.Host), body, etag); err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
// InstanceCatchallHost is the claim host of parent's instance catch-all:
// "*.<parent>". Using the star as the key is what makes the catch-all
// globally unique per parent through the same bucket key gate every other
@@ -300,6 +456,12 @@ func claimRawAttachInstanceCatchall(ctx context.Context, s release.Store, parent
// A pending parent (#215) is a reservation, not a holding.
return false, ErrParentNotHeld
}
+ if apex.Regional() {
+ // A regional parent (#447) lends no catch-all its names: a name under
+ // it would be served by one region's instance everywhere. Answered
+ // only to the parent's own account, so it says nothing to anyone else.
+ return false, ErrRegionalClaim
+ }
host := InstanceCatchallHost(parent)
body, err := json.Marshal(Claim{
Schema: 1, Host: host, Account: account, App: app,
@@ -388,11 +550,11 @@ func ForeignInstanceCatchall(ctx context.Context, s release.Store, host, account
// prove control supersedes a pending claim at any time.
const ClaimPendingTTL = 7 * 24 * time.Hour
-// pendingLive reports whether c is pending and still reserving its hostname
+// PendingLive reports whether c is pending and still reserving its hostname
// at now. A pending claim with no readable expiry is hand-written or damaged,
// and is treated as expired: the conservative direction for a reservation
// nobody proved is to let it go.
-func (c Claim) pendingLive(now time.Time) bool {
+func (c Claim) PendingLive(now time.Time) bool {
if !c.Pending {
return false
}
@@ -436,7 +598,8 @@ var ErrHostUnavailable = errors.New("hostname unavailable")
// getClaimETag reads and parses host's claim, carrying the etag it was read
// under. Not-found stays os.ErrNotExist-wrapped. A schema newer than this
// binary understands is refused rather than silently truncated by
-// json.Unmarshal — the GetManifestETag precedent (provision.go).
+// json.Unmarshal — the GetManifestETag precedent (provision.go) — and so is
+// a schema-2 claim whose placements are not valid (claimSchemaOK).
func getClaimETag(ctx context.Context, s release.Store, host string) (*Claim, string, error) {
raw, etag, err := s.Get(ctx, ClaimKey(host))
if err != nil {
@@ -446,12 +609,22 @@ func getClaimETag(ctx context.Context, s release.Store, host string) (*Claim, st
if err := json.Unmarshal(raw, &c); err != nil {
return nil, "", fmt.Errorf("domains: claim %s: %w", host, err)
}
- if c.Schema > 1 {
- return nil, "", fmt.Errorf("domains: claim %s: schema %d is newer than this binary understands — upgrade carlos", host, c.Schema)
+ if !claimSchemaOK(c) {
+ if c.Schema > 2 {
+ return nil, "", fmt.Errorf("domains: claim %s: schema %d is newer than this binary understands — upgrade carlos", host, c.Schema)
+ }
+ return nil, "", fmt.Errorf("domains: claim %s: %s", host, claimSchemaRefusal(c))
}
return &c, etag, nil
}
+// GetClaimETag reads host's claim with the etag it was read under, for a
+// caller that writes it back with a CAS (SetClaimPlacements). Not-found stays
+// os.ErrNotExist-wrapped.
+func GetClaimETag(ctx context.Context, s release.Store, host string) (*Claim, string, error) {
+ return getClaimETag(ctx, s, host)
+}
+
// GetClaim reads host's claim. Not-found stays os.ErrNotExist-wrapped.
func GetClaim(ctx context.Context, s release.Store, host string) (*Claim, error) {
c, _, err := getClaimETag(ctx, s, host)
@@ -502,7 +675,9 @@ func AttachClaim(ctx context.Context, s release.Store, c Claim) (created, change
// time, and by anyone once it has expired; otherwise ErrHostUnavailable,
// byte-identical to the verified case;
// - the caller's own claim: converged — a pending one becomes verified
-// once proven (its expiry is never pushed back) — and Route repointed.
+// once proven (its expiry is never pushed back) — and Route repointed;
+// - the caller's own REGIONAL claim (#447): a no-op when Route is one of
+// its bound hosts, otherwise ErrRegionalClaim. Never written here.
//
// Verification is one-way and sticky: nothing here ever turns a verified
// claim back into a pending one. pending reports the state of the claim as
@@ -554,7 +729,7 @@ func AttachClaimProven(ctx context.Context, s release.Store, c Claim, now time.T
// control, and to anyone once it has run out. Both refusals are
// the same ErrHostUnavailable, so the answer still never says
// whether the name is held, or how firmly.
- if !cur.Pending || (cur.pendingLive(now) && !isProven()) {
+ if !cur.Pending || (cur.PendingLive(now) && !isProven()) {
return false, false, false, ErrHostUnavailable
}
next := fresh()
@@ -573,6 +748,17 @@ func AttachClaimProven(ctx context.Context, s release.Store, c Claim, now time.T
return false, false, false, err
}
}
+ // A regional claim (#447) is changed only by the placements door. A
+ // route that is one of its bound hosts is already served by it, so the
+ // attach is a no-op (`carlos deploy` re-attaches on every run); any
+ // other route would repoint it, and is refused. Nothing here ever
+ // writes schema 2: c.Schema is 1, set above.
+ if cur.Regional() {
+ if c.Route != "" && cur.boundHost(c.Route) {
+ return false, false, false, nil
+ }
+ return false, false, false, ErrRegionalClaim
+ }
// Converge repoints Route and settles the pending state, and nothing
// else: the stored claim keeps its CreatedAt (the claim's age) and
// Wildcard (TLS opt-in state a route repoint has no business
@@ -702,8 +888,8 @@ func readClaimDetail(ctx context.Context, s release.Store, key string) (c Claim,
log.Printf("domains: claim %s: unparseable: %v", key, err)
return Claim{}, false, true, false
}
- if c.Schema > 1 {
- log.Printf("domains: claim %s: schema %d is newer than this binary understands, skipping", key, c.Schema)
+ if !claimSchemaOK(c) {
+ log.Printf("domains: claim %s: %s, skipping", key, claimSchemaRefusal(c))
return Claim{}, false, true, false
}
return c, true, true, false
@@ -767,7 +953,10 @@ func HostDenied(host string, deny []string) bool {
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. AttachClaim's converge deliberately repoints Route and nothing
+// 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
@@ -793,6 +982,11 @@ func claimRawSetClaimCapabilities(ctx context.Context, s release.Store, host, ac
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
@@ -898,6 +1092,10 @@ func claimRawSetClaimPaths(ctx context.Context, s release.Store, host, account,
if cur.Account != account || cur.App != app || cur.Instances {
return false, ErrHostUnavailable
}
+ // A regional claim carries no prefix map (#447 ruling 4).
+ if cur.Regional() {
+ return false, ErrRegionalClaim
+ }
if samePaths(cur.Paths, paths) {
return false, nil
}
@@ -967,3 +1165,10 @@ func SetClaimPaths(ctx context.Context, s release.Store, host, account, app stri
})
return
}
+func SetClaimPlacements(ctx context.Context, s release.Store, next Claim, cur *Claim, etag string) (claimResult0 bool, claimResult1 error) {
+ claimResult1 = release.WithAppMutation(ctx, s, next.Account, next.App, "domains.SetClaimPlacements", func(claimContext context.Context) error {
+ claimResult0, claimResult1 = claimRawSetClaimPlacements(claimContext, s, next, cur, etag)
+ return claimResult1
+ })
+ return
+}
diff --git a/internal/domains/regional_claims_test.go b/internal/domains/regional_claims_test.go
new file mode 100644
index 000000000..536712924
--- /dev/null
+++ b/internal/domains/regional_claims_test.go
@@ -0,0 +1,426 @@
+package domains
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// claimPutCounter counts the Puts that land on a claim key. Only claim keys:
+// a journaled store may write its own objects around the mutation, and the
+// property under test is that the claim itself is not rewritten.
+type claimPutCounter struct {
+ release.Store
+ puts int
+}
+
+func (c *claimPutCounter) Put(ctx context.Context, key string, raw []byte, etag string) (string, error) {
+ if strings.HasPrefix(key, ClaimsPrefix) {
+ c.puts++
+ }
+ return c.Store.Put(ctx, key, raw, etag)
+}
+
+// regionalClaim is a valid two-region claim on shop.example.com: the home
+// region bound to shop-ie.example.net and uk bound to shop-uk.example.net.
+func regionalClaim() Claim {
+ return Claim{
+ Schema: 2, Host: "shop.example.com", Account: "bab", App: "shop",
+ Route: "shop-ie.example.net",
+ CreatedAt: "2026-10-29T00:00:00Z", CreatedBy: "owner@example.com",
+ Placements: []Placement{
+ {Region: "", Host: "shop-ie.example.net"},
+ {Region: "uk", Host: "shop-uk.example.net"},
+ },
+ }
+}
+
+// putRegional stores c through the real writer, create-only.
+func putRegional(t *testing.T, s release.Store, c Claim) {
+ t.Helper()
+ changed, err := SetClaimPlacements(context.Background(), s, c, nil, "")
+ if err != nil || !changed {
+ t.Fatalf("SetClaimPlacements create: changed=%v err=%v", changed, err)
+ }
+}
+
+func putRawClaim(t *testing.T, s release.Store, host, body string) {
+ t.Helper()
+ if _, err := s.Put(context.Background(), ClaimKey(host), []byte(body), ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func rawClaim(t *testing.T, s release.Store, host string) ([]byte, string) {
+ t.Helper()
+ raw, etag, err := s.Get(context.Background(), ClaimKey(host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw, etag
+}
+
+func TestRegionalClaimRoundTrips(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ c := regionalClaim()
+ body, err := json.Marshal(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{
+ `"schema":2`,
+ `"placements":[{"region":"","host":"shop-ie.example.net"},{"region":"uk","host":"shop-uk.example.net"}]`,
+ } {
+ if !bytes.Contains(body, []byte(want)) {
+ t.Fatalf("marshalled claim %s lacks %s", body, want)
+ }
+ }
+ putRegional(t, s, c)
+ got, err := GetClaim(ctx, s, c.Host)
+ if err != nil {
+ t.Fatalf("GetClaim: %v", err)
+ }
+ if !reflect.DeepEqual(*got, c) {
+ t.Fatalf("round trip:\n got %+v\nwant %+v", *got, c)
+ }
+ if !got.Regional() {
+ t.Fatal("Regional() = false on a claim with placements")
+ }
+ if h := got.PlacementFor("uk"); h != "shop-uk.example.net" {
+ t.Fatalf(`PlacementFor("uk") = %q`, h)
+ }
+ if h := got.PlacementFor(""); h != "shop-ie.example.net" {
+ t.Fatalf(`PlacementFor("") = %q`, h)
+ }
+ if h := got.PlacementFor("us"); h != "" {
+ t.Fatalf(`PlacementFor("us") = %q, want ""`, h)
+ }
+ claims, err := ListClaims(ctx, s)
+ if err != nil || len(claims) != 1 || !reflect.DeepEqual(claims[0], c) {
+ t.Fatalf("ListClaims = %+v, %v", claims, err)
+ }
+ cur, etag, err := GetClaimETag(ctx, s, c.Host)
+ if err != nil || etag == "" || !reflect.DeepEqual(*cur, c) {
+ t.Fatalf("GetClaimETag = %+v %q %v", cur, etag, err)
+ }
+}
+
+// TestTodaysReaderRuleSkipsSchema2 reads the bytes SetClaimPlacements stored
+// RAW and applies the rule every binary before this change applies
+// (getClaimETag and readClaimDetail: "schema > 1" is refused). It fails if the
+// writer ever stamps schema 1 on a regional claim, which an old binary would
+// then route as a plain alias of its Route.
+func TestTodaysReaderRuleSkipsSchema2(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ c := regionalClaim()
+ c.Schema = 1 // the writer stamps the schema, whatever the caller passed
+ putRegional(t, s, c)
+ raw, _ := rawClaim(t, s, c.Host)
+ var old struct {
+ Schema int `json:"schema"`
+ }
+ if err := json.Unmarshal(raw, &old); err != nil {
+ t.Fatal(err)
+ }
+ if !(old.Schema > 1) {
+ t.Fatalf("stored schema %d passes the pre-change reader rule (schema > 1 is skipped); body %s", old.Schema, raw)
+ }
+}
+
+func TestSchema2WithoutValidPlacementsIsSkipped(t *testing.T) {
+ ctx := context.Background()
+ nine := make([]string, 9)
+ for i := range nine {
+ nine[i] = fmt.Sprintf(`{"region":"r%d","host":"shop-%d.example.net"}`, i, i)
+ }
+ cases := map[string]string{
+ "no placements": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"t"}`,
+ "nine placements": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"shop-0.example.net","created_at":"t","placements":[` + strings.Join(nine, ",") + `]}`,
+ "duplicate region": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"t","placements":[{"region":"uk","host":"shop-ie.example.net"},{"region":"uk","host":"shop-uk.example.net"}]}`,
+ "duplicate host": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"t","placements":[{"region":"","host":"shop-ie.example.net"},{"region":"uk","host":"shop-ie.example.net"}]}`,
+ "route not bound": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"other.example.net","created_at":"t","placements":[{"region":"","host":"shop-ie.example.net"},{"region":"uk","host":"shop-uk.example.net"}]}`,
+ "with paths": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"t","paths":{"a":"shop-uk.example.net"},"placements":[{"region":"","host":"shop-ie.example.net"},{"region":"uk","host":"shop-uk.example.net"}]}`,
+ "instances": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"t","instances":true,"placements":[{"region":"","host":"shop-ie.example.net"}]}`,
+ "pending": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"t","pending":true,"pending_until":"2099-01-01T00:00:00Z","placements":[{"region":"","host":"shop-ie.example.net"}]}`,
+ "unnormalised": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"Shop-IE.example.net","created_at":"t","placements":[{"region":"","host":"Shop-IE.example.net"}]}`,
+ "sidecar host": `{"schema":2,"host":"%s","account":"bab","app":"shop","route":"db.sidecar.internal","created_at":"t","placements":[{"region":"","host":"db.sidecar.internal"}]}`,
+ "schema 3": `{"schema":3,"host":"%s","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"t","placements":[{"region":"","host":"shop-ie.example.net"},{"region":"uk","host":"shop-uk.example.net"}]}`,
+ "schema 1 placed": `{"schema":1,"host":"%s","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"t","placements":[{"region":"","host":"shop-ie.example.net"}]}`,
+ }
+ for name, tmpl := range cases {
+ t.Run(name, func(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ host := "shop.example.com"
+ putRawClaim(t, s, host, fmt.Sprintf(tmpl, host))
+ // A plain claim beside it proves the listing still works.
+ putClaim(t, s, Claim{Host: "plain.example.com", Account: "bab", App: "shop", Route: "shop-ie.example.net"})
+ if c, err := GetClaim(ctx, s, host); err == nil {
+ t.Fatalf("GetClaim accepted %+v", c)
+ }
+ if _, _, err := GetClaimETag(ctx, s, host); err == nil {
+ t.Fatal("GetClaimETag accepted it")
+ }
+ claims, err := ListClaims(ctx, s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(claims) != 1 || claims[0].Host != "plain.example.com" {
+ t.Fatalf("ListClaims = %+v, want only plain.example.com", claims)
+ }
+ var cache ClaimCache
+ listed, err := cache.List(ctx, s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(listed) != 1 || listed[0].Host != "plain.example.com" {
+ t.Fatalf("ClaimCache.List = %+v, want only plain.example.com", listed)
+ }
+ })
+ }
+}
+
+// TestSchema1ClaimRoundTripsByteStable: a schema-1 body as this binary writes
+// it today, rewritten by SetClaimCapabilities, changes only the capability it
+// was asked to change and gains no placements key.
+func TestSchema1ClaimRoundTripsByteStable(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ const before = `{"schema":1,"host":"shop.example.com","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"2026-10-29T00:00:00Z","created_by":"owner@example.com","wildcard":true,"catchall":true,"paths":{"en":"shop-uk.example.net"}}`
+ const after = `{"schema":1,"host":"shop.example.com","account":"bab","app":"shop","route":"shop-ie.example.net","created_at":"2026-10-29T00:00:00Z","created_by":"owner@example.com","wildcard":true,"paths":{"en":"shop-uk.example.net"}}`
+ putRawClaim(t, s, "shop.example.com", before)
+ changed, err := SetClaimCapabilities(ctx, s, "shop.example.com", "bab", "shop", true, false)
+ if err != nil || !changed {
+ t.Fatalf("SetClaimCapabilities: changed=%v err=%v", changed, err)
+ }
+ raw, _ := rawClaim(t, s, "shop.example.com")
+ if string(raw) != after {
+ t.Fatalf("rewritten body:\n got %s\nwant %s", raw, after)
+ }
+ if bytes.Contains(raw, []byte("placements")) {
+ t.Fatalf("schema-1 rewrite gained a placements key: %s", raw)
+ }
+}
+
+func TestSetClaimCapabilitiesRefusesARegionalClaim(t *testing.T) {
+ ctx := context.Background()
+ for _, tc := range []struct {
+ name string
+ have [2]bool // the claim's wildcard, catchall
+ changes [][2]bool
+ catchallNoWild bool
+ }{
+ {"neither", [2]bool{false, false}, [][2]bool{{true, false}, {true, true}}, true},
+ {"both", [2]bool{true, true}, [][2]bool{{true, false}, {false, false}}, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s := &claimPutCounter{Store: release.NewDirStore(t.TempDir())}
+ c := regionalClaim()
+ c.Wildcard, c.Catchall = tc.have[0], tc.have[1]
+ putRegional(t, s, c)
+ s.puts = 0
+ raw0, etag0 := rawClaim(t, s, c.Host)
+ for _, ch := range tc.changes {
+ changed, err := SetClaimCapabilities(ctx, s, c.Host, c.Account, c.App, ch[0], ch[1])
+ if !errors.Is(err, ErrRegionalClaim) || changed {
+ t.Fatalf("(%v,%v): changed=%v err=%v, want ErrRegionalClaim", ch[0], ch[1], changed, err)
+ }
+ }
+ // catchall without wildcard is refused first, as for any claim.
+ if _, err := SetClaimCapabilities(ctx, s, c.Host, c.Account, c.App, false, true); !errors.Is(err, ErrCatchallNeedsWildcard) {
+ t.Fatalf("(false,true): err=%v, want ErrCatchallNeedsWildcard", err)
+ }
+ // The claim's own values are accepted and write nothing.
+ changed, err := SetClaimCapabilities(ctx, s, c.Host, c.Account, c.App, tc.have[0], tc.have[1])
+ if err != nil || changed {
+ t.Fatalf("same values: changed=%v err=%v, want false nil", changed, err)
+ }
+ if s.puts != 0 {
+ t.Fatalf("%d claim Put(s), want none", s.puts)
+ }
+ raw1, etag1 := rawClaim(t, s, c.Host)
+ if !bytes.Equal(raw0, raw1) || etag0 != etag1 {
+ t.Fatalf("claim changed:\n%s %s\n%s %s", raw0, etag0, raw1, etag1)
+ }
+ })
+ }
+ // Another owner still gets the neutral refusal, not the regional one.
+ s := release.NewDirStore(t.TempDir())
+ putRegional(t, s, regionalClaim())
+ if _, err := SetClaimCapabilities(ctx, s, "shop.example.com", "zzz", "shop", true, false); !errors.Is(err, ErrHostUnavailable) {
+ t.Fatalf("another owner: err=%v, want ErrHostUnavailable", err)
+ }
+}
+
+func TestAttachClaimProvenOnARegionalClaim(t *testing.T) {
+ ctx := context.Background()
+ s := &claimPutCounter{Store: release.NewDirStore(t.TempDir())}
+ c := regionalClaim()
+ putRegional(t, s, c)
+ s.puts = 0
+ raw0, etag0 := rawClaim(t, s, c.Host)
+ now := time.Date(2026, 10, 29, 0, 0, 0, 0, time.UTC)
+ for _, route := range []string{"shop-ie.example.net", "shop-uk.example.net"} {
+ created, changed, pending, err := AttachClaimProven(ctx, s, Claim{Host: c.Host, Account: c.Account, App: c.App, Route: route}, now, nil)
+ if err != nil || created || changed || pending {
+ t.Fatalf("attach %s: created=%v changed=%v pending=%v err=%v, want a no-op", route, created, changed, pending, err)
+ }
+ }
+ for _, route := range []string{"other.example.net", ""} {
+ _, changed, _, err := AttachClaimProven(ctx, s, Claim{Host: c.Host, Account: c.Account, App: c.App, Route: route}, now, nil)
+ if !errors.Is(err, ErrRegionalClaim) || changed {
+ t.Fatalf("attach %q: changed=%v err=%v, want ErrRegionalClaim", route, changed, err)
+ }
+ }
+ // Another owner gets the neutral refusal.
+ if _, _, _, err := AttachClaimProven(ctx, s, Claim{Host: c.Host, Account: "zzz", App: "shop", Route: "shop-ie.example.net"}, now, nil); !errors.Is(err, ErrHostUnavailable) {
+ t.Fatalf("another owner: err=%v, want ErrHostUnavailable", err)
+ }
+ if s.puts != 0 {
+ t.Fatalf("%d claim Put(s), want none", s.puts)
+ }
+ raw1, etag1 := rawClaim(t, s, c.Host)
+ if !bytes.Equal(raw0, raw1) || etag0 != etag1 {
+ t.Fatalf("claim changed:\n%s\n%s", raw0, raw1)
+ }
+ got, err := GetClaim(ctx, s, c.Host)
+ if err != nil || got.Schema != 2 || !got.Regional() {
+ t.Fatalf("stored claim = %+v, %v; want schema 2, regional", got, err)
+ }
+}
+
+func TestSetClaimPathsRefusesARegionalClaim(t *testing.T) {
+ ctx := context.Background()
+ s := &claimPutCounter{Store: release.NewDirStore(t.TempDir())}
+ c := regionalClaim()
+ putRegional(t, s, c)
+ s.puts = 0
+ for _, paths := range []map[string]string{{"en": "shop-uk.example.net"}, nil} {
+ changed, err := SetClaimPaths(ctx, s, c.Host, c.Account, c.App, paths)
+ if !errors.Is(err, ErrRegionalClaim) || changed {
+ t.Fatalf("paths %v: changed=%v err=%v, want ErrRegionalClaim", paths, changed, err)
+ }
+ }
+ if _, err := SetClaimPaths(ctx, s, c.Host, "zzz", c.App, nil); !errors.Is(err, ErrHostUnavailable) {
+ t.Fatalf("another owner: err=%v, want ErrHostUnavailable", err)
+ }
+ if s.puts != 0 {
+ t.Fatalf("%d claim Put(s), want none", s.puts)
+ }
+}
+
+func TestInstanceCatchallRefusesARegionalParent(t *testing.T) {
+ ctx := context.Background()
+ s := &claimPutCounter{Store: release.NewDirStore(t.TempDir())}
+ putRegional(t, s, regionalClaim())
+ s.puts = 0
+ if _, err := AttachInstanceCatchall(ctx, s, "shop.example.com", "bab", "teams", "t", "j"); !errors.Is(err, ErrRegionalClaim) {
+ t.Fatalf("own regional parent: err=%v, want ErrRegionalClaim", err)
+ }
+ // Another account learns nothing about the parent's mode.
+ if _, err := AttachInstanceCatchall(ctx, s, "shop.example.com", "zzz", "teams", "t", "j"); !errors.Is(err, ErrParentNotHeld) {
+ t.Fatalf("foreign regional parent: err=%v, want ErrParentNotHeld", err)
+ }
+ if s.puts != 0 {
+ t.Fatalf("%d claim Put(s), want none", s.puts)
+ }
+ if _, err := GetClaim(ctx, s, InstanceCatchallHost("shop.example.com")); err == nil {
+ t.Fatal("a catch-all was written under a regional parent")
+ }
+}
+
+func TestSetClaimPlacementsWrites(t *testing.T) {
+ ctx := context.Background()
+ s := &claimPutCounter{Store: release.NewDirStore(t.TempDir())}
+ c := regionalClaim()
+ putRegional(t, s, c)
+ // A second create-only write meets the first.
+ if _, err := SetClaimPlacements(ctx, s, c, nil, ""); !errors.Is(err, release.ErrCASConflict) {
+ t.Fatalf("second create: err=%v, want release.ErrCASConflict", err)
+ }
+ cur, etag, err := GetClaimETag(ctx, s, c.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The same claim again writes nothing, whatever order the set came in.
+ s.puts = 0
+ same := *cur
+ same.Placements = []Placement{cur.Placements[1], cur.Placements[0]}
+ if changed, err := SetClaimPlacements(ctx, s, same, cur, etag); err != nil || changed {
+ t.Fatalf("equal write: changed=%v err=%v, want false nil", changed, err)
+ }
+ if s.puts != 0 {
+ t.Fatalf("equal write: %d claim Put(s), want none", s.puts)
+ }
+ // An update is a CAS on the etag it read.
+ next := *cur
+ next.Placements = append([]Placement{{Region: "us", Host: "shop-us.example.net"}}, cur.Placements...)
+ if changed, err := SetClaimPlacements(ctx, s, next, cur, etag); err != nil || !changed {
+ t.Fatalf("update: changed=%v err=%v", changed, err)
+ }
+ got, err := GetClaim(ctx, s, c.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []Placement{{"", "shop-ie.example.net"}, {"uk", "shop-uk.example.net"}, {"us", "shop-us.example.net"}}
+ if !reflect.DeepEqual(got.Placements, want) {
+ t.Fatalf("stored placements %+v, want %+v (sorted by region)", got.Placements, want)
+ }
+ // The etag is now stale: a write decided from cur meets the update.
+ stale := *cur
+ stale.Placements = []Placement{{Region: "", Host: "shop-ie.example.net"}}
+ if _, err := SetClaimPlacements(ctx, s, stale, cur, etag); !errors.Is(err, release.ErrCASConflict) {
+ t.Fatalf("stale etag: err=%v, want release.ErrCASConflict", err)
+ }
+ // Invalid sets are refused before any write.
+ s.puts = 0
+ bad := map[string]func(*Claim){
+ "none": func(c *Claim) { c.Placements = nil },
+ "route not bound": func(c *Claim) { c.Route = "other.example.net" },
+ "duplicate region": func(c *Claim) { c.Placements[1].Region = "" },
+ "paths": func(c *Claim) { c.Paths = map[string]string{"a": "shop-uk.example.net"} },
+ "instances": func(c *Claim) { c.Instances = true },
+ "too many": func(c *Claim) {
+ c.Placements = nil
+ for i := 0; i <= MaxPlacements; i++ {
+ c.Placements = append(c.Placements, Placement{Region: fmt.Sprintf("r%d", i), Host: fmt.Sprintf("shop-%d.example.net", i)})
+ }
+ c.Route = c.Placements[0].Host
+ },
+ }
+ for name, mutate := range bad {
+ b := regionalClaim()
+ b.Host = "other.example.com"
+ mutate(&b)
+ if _, err := SetClaimPlacements(ctx, s, b, nil, ""); !errors.Is(err, ErrBadPlacements) {
+ t.Fatalf("%s: err=%v, want ErrBadPlacements", name, err)
+ }
+ }
+ if s.puts != 0 {
+ t.Fatalf("invalid sets: %d claim Put(s), want none", s.puts)
+ }
+}
+
+func TestRegionalRoute(t *testing.T) {
+ ps := []Placement{{"uk", "shop-uk.example.net"}, {"", "shop-ie.example.net"}, {"de", "shop-de.example.net"}}
+ if got := RegionalRoute(ps, "shop-uk.example.net"); got != "shop-uk.example.net" {
+ t.Fatalf("bound route kept: got %q", got)
+ }
+ if got := RegionalRoute(ps, "gone.example.net"); got != "shop-ie.example.net" {
+ t.Fatalf("unbound route: got %q, want the home host", got)
+ }
+ if got := RegionalRoute(ps[2:], ""); got != "shop-de.example.net" {
+ t.Fatalf("one placement: got %q", got)
+ }
+ if got := RegionalRoute([]Placement{{"uk", "b.example.net"}, {"de", "a.example.net"}}, ""); got != "a.example.net" {
+ t.Fatalf("no home: got %q, want the first region in code order (de)", got)
+ }
+}