Regional domains (#447) Task 3: console writer rules, team scope and instance create
- apex.go: apexHold.Regional; hostClaimHolder answers this account's regional claim as Regional whatever the asking app; regionalClaimHold (one claim read, neutral OtherAccount for another account's); claimHeldSentence gives RD-27 for Regional. - lifetimes.go: regionalHostError and regionalRecheck; lifetimeCreateRefusal maps it to 409 claimHeldSentence, so the create, seed, import and first-route doors answer it alike. Lock table note. - lifetimes_create.go: the recheck under both locks, before step 1's admit and so before BeginAllocation (spec 6.3 rev 5). - hostsused.go: createRecordMarked takes the hostname lock after the app lock and rechecks before firstKindRecheck. - teamdoors.go: inScopeClaim puts a regional claim out of scope (get, placements GET, detach, attach); the team list skips it too. - apidomains.go: setDomainCapabilities decides the final values (cascade included) and refuses a regional change 409 RD-26 before any DNS work; attach and paths doors map ErrRegionalClaim to 409 RD-26; domainItem carries "mode":"regional". - domainattach.go: claimRefusal maps ErrRegionalClaim to 409 RD-26. - claim_first_route.go: the host-claim first-route attach reads the claim first and refuses this app's regional claim. Tests: internal/console/regional_writers_test.go.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+594
−17
internal/console/apex.go+39 −3internal/console/apidomains.go+39 −9internal/console/claim_first_route.go+13 −0internal/console/domainattach.go+7 −0internal/console/hostsused.go+9 −1internal/console/lifetimes.go+33 −1internal/console/lifetimes_create.go+11 −2internal/console/regional_writers_test.go+440 −0internal/console/teamdoors.go+3 −1
diff --git a/internal/console/apex.go b/internal/console/apex.go| index c35156769..8101e8a20 100644 |
| --- a/internal/console/apex.go |
| +++ b/internal/console/apex.go |
| @@ -39,11 +39,14 @@ func (s *Server) apexHost(sqid, app string) string { |
| // apexHold is who already holds an apex: the app a route or an instance |
| // record belongs to — "" for a route that names no app (a status page, a bare |
| // proxy, anything hand-added) — whether that app is in the trash, and the |
| -// account a route says it serves when that is not the apex's own. |
| +// account a route says it serves when that is not the apex's own. Regional |
| +// is set for a regional claim (#447) of the asking account, whichever app |
| +// holds it: a regional name is never an instance's hostname. |
| type apexHold struct { |
| Holder string |
| Trashed bool |
| OtherAccount string |
| + Regional bool |
| } |
| // apexErr says which store an apexHolder failure came from, so a door can |
| @@ -189,7 +192,10 @@ func (s *Server) hostHolder(ctx context.Context, acct *Account, host, own string |
| // there is no claim or it is own's. A claim of another account comes back |
| // with only OtherAccount set and no Holder: domains.ErrHostUnavailable is |
| // deliberately neutral about who owns a hostname, and this door must not be a |
| -// way round that. Anything but "no such claim" is an error: it fails closed. |
| +// way round that. A regional claim of acct (#447, spec §6.3) comes back as |
| +// Regional whatever own is, the claim's own app included: no real route of |
| +// a regional name is minted. Anything but "no such claim" is an error: it |
| +// fails closed. |
| func (s *Server) hostClaimHolder(ctx context.Context, acct *Account, host, own string) (*apexHold, error) { |
| if s.cfg.Releases == nil { |
| return nil, nil |
| @@ -204,17 +210,47 @@ func (s *Server) hostClaimHolder(ctx context.Context, acct *Account, host, own s |
| switch { |
| case c.Account != acct.Sqid: |
| return &apexHold{OtherAccount: c.Account}, nil |
| + case c.Regional(): |
| + return &apexHold{Regional: true}, nil |
| case c.App != own: |
| return &apexHold{Holder: c.App}, nil |
| } |
| return nil, nil |
| } |
| +// regionalClaimHold is the instance create's recheck under the hostname |
| +// exclusion (#447, spec §6.3): host's claim, read once. It is nil when there |
| +// is no claim or the claim is not regional; &apexHold{OtherAccount} for |
| +// another account's regional claim, so the refusal is as neutral as |
| +// hostClaimHolder's; &apexHold{Regional: true} for this account's. A read |
| +// error is returned: the caller fails closed. |
| +func (s *Server) regionalClaimHold(ctx context.Context, acct, host string) (*apexHold, error) { |
| + if s.cfg.Releases == nil { |
| + return nil, nil |
| + } |
| + c, err := domains.GetClaim(ctx, s.cfg.Releases, host) |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| + return nil, nil |
| + case err != nil: |
| + return nil, err |
| + case !c.Regional(): |
| + return nil, nil |
| + case c.Account != acct: |
| + return &apexHold{OtherAccount: c.Account}, nil |
| + } |
| + return &apexHold{Regional: true}, nil |
| +} |
| + |
| // claimHeldSentence is hostHeldSentence for a hostname claim. A claim of |
| // another account is refused without saying whose or that it is a claim. |
| +// A regional claim of this account is RD-27 (draft). |
| func claimHeldSentence(host string, hold *apexHold) string { |
| - if hold.OtherAccount != "" { |
| + switch { |
| + case hold.OtherAccount != "": |
| return hostHeldSentence(host, nil) |
| + case hold.Regional: |
| + return host + " is a regional domain, so it cannot also be an instance's hostname. choose another name." |
| } |
| return hostHeldSentence(host, hold) |
| } |
diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go| index 97c4bc594..cc6d21059 100644 |
| --- a/internal/console/apidomains.go |
| +++ b/internal/console/apidomains.go |
| @@ -586,6 +586,12 @@ func (s *Server) handleAPIDomainAttach(w http.ResponseWriter, r *http.Request) { |
| // stranger" — would make this door a hostname-ownership oracle. |
| jsonError(w, http.StatusConflict, hostUnavailableMsg) |
| return |
| + } else if errors.Is(err, domains.ErrRegionalClaim) { |
| + // The caller's own regional claim (AttachClaimProven answers it |
| + // only after the owner match), named by a route that is not one of |
| + // its bound hosts: RD-26. |
| + jsonError(w, http.StatusConflict, domains.ErrRegionalClaim.Error()) |
| + return |
| } else if msg, ok := claimAliasRefusal(err); ok { |
| jsonError(w, http.StatusConflict, msg) |
| return |
| @@ -679,6 +685,20 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c |
| if wantCatchall != nil { |
| catchall = *wantCatchall |
| } |
| + if wantWildcard != nil && !*wantWildcard { |
| + // Disabling wildcard cascades catchall off in the SAME call (the |
| + // switch below says why), decided here so the regional rule judges |
| + // the values that would be written. |
| + catchall = false |
| + } |
| + // 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. |
| + if cur.Regional() && (wildcard != cur.Wildcard || catchall != cur.Catchall) { |
| + jsonError(w, http.StatusConflict, domains.ErrRegionalClaim.Error()) |
| + 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 |
| @@ -689,13 +709,12 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c |
| enabling := wantWildcard != nil && *wantWildcard && !cur.Wildcard |
| switch { |
| case wantWildcard != nil && !*wantWildcard: |
| - // Disabling wildcard cascades catchall off in the SAME call — |
| - // turning off never requires DNS, and a caller disabling wildcard is |
| - // not asking for a 422. The door normalizes here rather than calling |
| - // SetClaimCapabilities with catchall still true and letting its own |
| - // ErrCatchallNeedsWildcard refuse a request that was never asking to |
| - // enable anything. |
| - catchall = false |
| + // Disabling wildcard cascades catchall off in the SAME call (set |
| + // above) — turning off never requires DNS, and a caller disabling |
| + // wildcard is not asking for a 422. The door normalizes rather than |
| + // calling SetClaimCapabilities with catchall still true and letting |
| + // its own ErrCatchallNeedsWildcard refuse a request that was never |
| + // asking to enable anything. |
| case enabling: |
| // Enabling wildcard requires a configured delegation zone and a live |
| // _acme-challenge CNAME delegating to it — the claim-derived- |
| @@ -886,6 +905,11 @@ func (s *Server) handleAPIDomainPaths(w http.ResponseWriter, r *http.Request) { |
| // makes a 10,000-entry map fixable. |
| jsonError(w, http.StatusUnprocessableEntity, err.Error()) |
| return |
| + } else if errors.Is(err, domains.ErrRegionalClaim) { |
| + // The caller's own regional claim (#447): SetClaimPaths refuses it |
| + // after its owner gate, so this names no one else's hostname. |
| + jsonError(w, http.StatusConflict, domains.ErrRegionalClaim.Error()) |
| + return |
| } else if errors.Is(err, domains.ErrHostUnavailable) { |
| // The family's byte-identical 404 discipline, copied verbatim from |
| // setDomainCapabilities (not jsonError — a distinct shape here would |
| @@ -1105,6 +1129,9 @@ type domainListItem struct { |
| // omitted the way an unstamped reading is). |
| Wildcard bool `json:"wildcard"` |
| Catchall bool `json:"catchall"` |
| + // Mode is "regional" for a regional claim (#447, spec §6.4), whose |
| + // readiness lives in the placements GET; omitted for single mode. |
| + Mode string `json:"mode,omitempty"` |
| // DelegationStatus stamps "delegated"/"missing" from the SAME CNAME |
| // check the attach gate uses, live on every list call — never cached |
| // from whenever wildcard was enabled. Omitted (not "unknown") when the |
| @@ -1198,9 +1225,9 @@ func (s *Server) handleAPIDomainList(w http.ResponseWriter, r *http.Request) { |
| } |
| // A team sees the claims whose route is an instance in scope and |
| // nothing else (§4): no first-route or static claim (Route ""), |
| - // no catch-all. |
| + // no catch-all, no regional claim (#447, inScopeClaim's rule). |
| if team { |
| - if c.Route == "" || c.Instances { |
| + if c.Route == "" || c.Instances || c.Regional() { |
| continue |
| } |
| _, ok, err := tv.inScopeHost(ctx, s, c.Route) |
| @@ -1261,6 +1288,9 @@ func (s *Server) handleAPIDomainList(w http.ResponseWriter, r *http.Request) { |
| func (s *Server) domainItem(ctx context.Context, c domains.Claim, readings map[string]status.AliasReading, warm *certwarm.Record, targets DNSTargets, now time.Time, delegation bool) domainListItem { |
| item := domainListItem{Host: c.Host, Route: c.Route, Status: "pending", |
| Wildcard: c.Wildcard, Catchall: c.Catchall} |
| + if c.Regional() { |
| + item.Mode = "regional" |
| + } |
| reading, seen := readings[c.Host] |
| if seen { |
| item.Status = "live" |
diff --git a/internal/console/claim_first_route.go b/internal/console/claim_first_route.go| index 7dabf8794..85a2c5ed5 100644 |
| --- a/internal/console/claim_first_route.go |
| +++ b/internal/console/claim_first_route.go |
| @@ -2,7 +2,9 @@ package console |
| import ( |
| "context" |
| + "errors" |
| "net/http" |
| + "os" |
| "time" |
| "github.com/carlosframework/platform/internal/domains" |
| @@ -12,6 +14,17 @@ import ( |
| ) |
| func (s *Server) attachClaimFirstRoute(ctx context.Context, acct *Account, app, host, channel, principal string) (attachResult, *doorRefusal) { |
| + // A regional claim of this app (#447, spec §6.3) never gains a |
| + // first-route record: read the claim before anything else, as the |
| + // claims-off paths do through AttachClaimProven. Only the caller's own |
| + // claim is answered here, so the refusal names no one else's hostname. |
| + switch c, err := domains.GetClaim(ctx, s.cfg.Releases, host); { |
| + case errors.Is(err, os.ErrNotExist): |
| + case err != nil: |
| + return attachResult{}, claimRefusal(host, err) |
| + case c.Account == acct.Sqid && c.App == app && c.Regional(): |
| + return attachResult{}, claimRefusal(host, domains.ErrRegionalClaim) |
| + } |
| if !s.domainProver(ctx, host, acct.Sqid)() { |
| return attachResult{}, &doorRefusal{http.StatusConflict, verifyGuidance(s.domainChallenge(host, acct.Sqid))} |
| } |
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go| index bb45e48f5..2f715e7b2 100644 |
| --- a/internal/console/domainattach.go |
| +++ b/internal/console/domainattach.go |
| @@ -764,6 +764,13 @@ func claimRefusal(host string, err error) *doorRefusal { |
| if errors.Is(err, domains.ErrHostUnavailable) { |
| return &doorRefusal{http.StatusConflict, hostUnavailableMsg} |
| } |
| + // The caller's own regional claim (#447): every writer answers it only |
| + // after its owner match, so this names nobody else's hostname. RD-26 |
| + // here; a door with its own words for it (the catch-all door) answers |
| + // it before calling this. |
| + if errors.Is(err, domains.ErrRegionalClaim) { |
| + return &doorRefusal{http.StatusConflict, domains.ErrRegionalClaim.Error()} |
| + } |
| log.Printf("console: attach %s: claim write: %v", host, err) |
| return &doorRefusal{http.StatusInternalServerError, |
| "could not claim this domain — try again in a moment"} |
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go| index 1279eed1f..945722445 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -556,9 +556,17 @@ func recordUse(rec provision.Record) provision.HostUse { |
| // (gateDataCreate) and its mark, then provision.CreateRecord. Exempt kinds |
| // write as before. It holds the app lock, as the lifetime create does, so |
| // carlos apps place's check of the app's records holds through its writes |
| -// (placeAppTarget). |
| +// (placeAppTarget), and then the hostname exclusion (the lock table's order, |
| +// lifetimes.go), so the regional recheck (#447) and the write are one hold |
| +// against a placements PUT. |
| func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) error { |
| defer s.lockApp(rec.Account, rec.App)() // record writes hold the app lock (recordlock.go) |
| + defer s.lockHostname(rec.Host)() |
| + // The regional recheck (spec §6.3): a regional claim written since the |
| + // door's first check refuses the create before anything is marked. |
| + if err := s.regionalRecheck(ctx, rec); err != nil { |
| + return err |
| + } |
| // The first-kind boundary (rootfs.go): under the lock, before the mark. |
| if err := s.firstKindRecheck(ctx, rec); err != nil { |
| return err |
diff --git a/internal/console/lifetimes.go b/internal/console/lifetimes.go| index 0eb8b4f04..08d62a173 100644 |
| --- a/internal/console/lifetimes.go |
| +++ b/internal/console/lifetimes.go |
| @@ -25,7 +25,8 @@ import ( |
| // |
| // - createRecordWithLifetime (the create, seed and import doors) takes |
| // s.lockApp then withHostname; createRecordWithLifetimeLocked assumes |
| -// both. |
| +// both. Their lifetimes-off twin, createRecordMarked, takes the same |
| +// two in the same order (#447's regional recheck). |
| // - the attach door takes s.lockApp before it enters its hostname |
| // exclusion; attachFirstRouteLocked and rollbackAttachLocked assume |
| // both. A claims-off detach admitted on runs its claim read, record |
| @@ -73,6 +74,34 @@ func (e *hostHeldError) Error() string { |
| return "console: lifetimes: " + hostHeldSentence(e.Host, e.Hold) |
| } |
| +// regionalHostError is an instance create refused by the recheck under the |
| +// hostname exclusion (#447, spec §6.3): host's claim is regional. |
| +// lifetimeCreateRefusal answers it with claimHeldSentence(host, hold), the |
| +// bytes the create door's first check gives, so the create, seed, import |
| +// and first-route doors answer it alike. Nothing is persisted. |
| +type regionalHostError struct { |
| + host string |
| + hold *apexHold |
| +} |
| + |
| +func (e *regionalHostError) Error() string { |
| + return "console: create: " + claimHeldSentence(e.host, e.hold) |
| +} |
| + |
| +// regionalRecheck is that recheck: one claim read, under the hostname |
| +// exclusion the caller holds, before anything is persisted. A read error is |
| +// returned wrapped (fail closed). |
| +func (s *Server) regionalRecheck(ctx context.Context, rec provision.Record) error { |
| + hold, err := s.regionalClaimHold(ctx, rec.Account, rec.Host) |
| + if err != nil { |
| + return fmt.Errorf("console: create %s: read the hostname's claim: %w", rec.Host, err) |
| + } |
| + if hold != nil { |
| + return ®ionalHostError{host: rec.Host, hold: hold} |
| + } |
| + return nil |
| +} |
| + |
| // lifetimeAppError is step 0's refusal: the app this create was admitted for |
| // is unreadable, in the trash, gone, or a different lifetime under the same |
| // name. Nothing is persisted. |
| @@ -102,7 +131,10 @@ func lifetimeCreateRefusal(host string, err error, pendingMsg string) (*doorRefu |
| var held *hostHeldError |
| var app *lifetimeAppError |
| var used *hostsUsedError |
| + var regional *regionalHostError |
| switch { |
| + case errors.As(err, ®ional): |
| + return &doorRefusal{http.StatusConflict, claimHeldSentence(host, regional.hold)}, true |
| case errors.As(err, &used): |
| // The hostname history's refusal (hostsused.go), lifetimes on or off. |
| return &used.ref, true |
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go| index fe2c8a44f..95c009e11 100644 |
| --- a/internal/console/lifetimes_create.go |
| +++ b/internal/console/lifetimes_create.go |
| @@ -55,8 +55,9 @@ func (s *Server) createRecordWithLifetime(ctx context.Context, rec provision.Rec |
| // createRecordWithLifetimeLocked is the protocol under both locks, which the |
| // caller holds (the attach door's form). It returns the record as written, |
| // or: release.ErrCASConflict (a valid record under this key, the slot |
| -// untouched), *hostHeldError, *lifetimeAppError, errLifetimeSettling, |
| -// errLifetimePending, or a read error with nothing persisted. |
| +// untouched), *hostHeldError, *regionalHostError, *lifetimeAppError, |
| +// errLifetimeSettling, errLifetimePending, or a read error with nothing |
| +// persisted. |
| func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provision.Record, lifetime string) (*provision.Record, error) { |
| if len(rec.Maintenance) != 0 { |
| return nil, provision.ErrMaintenanceProjection |
| @@ -77,6 +78,14 @@ func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provisi |
| if err != nil { |
| return nil, err |
| } |
| + // The regional recheck (#447, spec §6.3 rev 5): the door's claim check |
| + // ran before any lock, so a regional claim written since is caught here, |
| + // under the hostname exclusion and before BeginAllocation. A refusal |
| + // after that point would leave a pending allocation that recovery |
| + // completes into the very record this refuses. |
| + if err := s.regionalRecheck(ctx, rec); err != nil { |
| + return nil, err |
| + } |
| // Step 1. |
| if err := s.admit(host, ""); err != nil { |
| return nil, err |
diff --git a/internal/console/regional_writers_test.go b/internal/console/regional_writers_test.go| new file mode 100644 |
| index 000000000..0684df5f0 |
| --- /dev/null |
| +++ b/internal/console/regional_writers_test.go |
| @@ -0,0 +1,440 @@ |
| +package console |
| + |
| +// Regional domains (#447) Task 3: every console door that writes a claim or |
| +// an instance record at a regional name refuses it or answers a no-op (spec |
| +// §6.3), and a regional claim is out of a team credential's scope (§6.4). |
| +// Regional claims are written by domains.SetClaimPlacements, the real writer. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "slices" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The two hosts a test regional claim is bound to: home and uk. |
| +const ( |
| + rdHomeHost = "shop-ie.example.net" |
| + rdUKHost = "shop-uk.example.net" |
| +) |
| + |
| +// putRegionalClaim stores a regional claim on host for acct/app through the |
| +// real writer: home bound to home, uk bound to rdUKHost, Route home. |
| +func putRegionalClaim(t *testing.T, st release.Store, host, acct, app, home string, wildcard, catchall bool) { |
| + t.Helper() |
| + if err := writeRegionalClaim(st, host, acct, app, home, wildcard, catchall); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func writeRegionalClaim(st release.Store, host, acct, app, home string, wildcard, catchall bool) error { |
| + c := domains.Claim{Host: host, Account: acct, App: app, Route: home, |
| + CreatedAt: "2026-10-29T00:00:00Z", CreatedBy: "owner@example.com", |
| + Wildcard: wildcard, Catchall: catchall, |
| + Placements: []domains.Placement{{Region: "", Host: home}, {Region: "uk", Host: rdUKHost}}} |
| + changed, err := domains.SetClaimPlacements(context.Background(), st, c, nil, "") |
| + if err == nil && !changed { |
| + err = errors.New("SetClaimPlacements wrote nothing") |
| + } |
| + return err |
| +} |
| + |
| +// regionalClaimBytes is the stored claim's bytes and ETag. |
| +func regionalClaimBytes(t *testing.T, st release.Store, host string) (string, string) { |
| + t.Helper() |
| + raw, etag, err := st.Get(context.Background(), domains.ClaimKey(host)) |
| + if err != nil { |
| + t.Fatalf("claim %s: %v", host, err) |
| + } |
| + return string(raw), etag |
| +} |
| + |
| +func requireClaimUnchanged(t *testing.T, st release.Store, host, raw, etag, what string) { |
| + t.Helper() |
| + if gotRaw, gotETag := regionalClaimBytes(t, st, host); gotRaw != raw || gotETag != etag { |
| + t.Fatalf("%s: claim %s rewritten:\n%s (%s)\nwas\n%s (%s)", what, host, gotRaw, gotETag, raw, etag) |
| + } |
| +} |
| + |
| +func requireNoRecord(t *testing.T, st release.Store, app, host string) { |
| + t.Helper() |
| + if _, _, err := st.Get(context.Background(), provision.RecordKey("bab", app, host)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("record bab/%s/%s: %v, want none", app, host, err) |
| + } |
| +} |
| + |
| +// rdHeldMsg is RD-27 (draft) for host. |
| +func rdHeldMsg(host string) string { |
| + return host + " is a regional domain, so it cannot also be an instance's hostname. choose another name." |
| +} |
| + |
| +// eventsOf is the activity rows of app in the ops account with action. |
| +func eventsOf(t *testing.T, st *Store, app, action string) int { |
| + t.Helper() |
| + events, err := st.Events(OpsAccountID, app, 200) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + n := 0 |
| + for _, e := range events { |
| + if e.Action == action { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// wildFailHits is every principal's count in the wildcard-failure limiter. |
| +func wildFailHits(s *Server) int { |
| + l := s.cli.wildFail |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + n := 0 |
| + for _, w := range l.hits { |
| + n += w.n |
| + } |
| + return n |
| +} |
| + |
| +// newShopApp adds app shop to the ops account of an instanceFixture. |
| +func newShopApp(t *testing.T, fx *consoleFixture) { |
| + t.Helper() |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestTeamScopeRefusesRegionalClaim (W4): a regional claim bound to the |
| +// team's own instance is still out of its scope. The per-host GET, the |
| +// placements GET and DELETE answer an unknown hostname's not-found bytes, |
| +// attach answers what a claim held for an out-of-scope route answers, the |
| +// list leaves it out, and the claim is untouched. |
| +func TestTeamScopeRefusesRegionalClaim(t *testing.T) { |
| + w := newTeamWorld(t, "code-team-regional") |
| + const host = "shop.example.com" |
| + putRegionalClaim(t, w.fx.rel, host, "bab", "titogo", "mine.go.tito.io", false, false) |
| + raw, etag := regionalClaimBytes(t, w.fx.rel, host) |
| + |
| + unknownStatus, _, unknown := rawReq(t, http.MethodGet, w.url("/domains/nope.example.com"), w.team, "") |
| + if unknownStatus != http.StatusNotFound { |
| + t.Fatalf("GET an unknown hostname = %d %s", unknownStatus, unknown) |
| + } |
| + for _, c := range []struct{ method, path string }{ |
| + {http.MethodGet, "/domains/" + host}, |
| + {http.MethodGet, "/domains/" + host + "/placements"}, |
| + {http.MethodDelete, "/domains/" + host}, |
| + } { |
| + if status, _, out := rawReq(t, c.method, w.url(c.path), w.team, ""); status != unknownStatus || out != unknown { |
| + t.Errorf("%s %s = %d %s, want the unknown hostname's %d %s", c.method, c.path, status, out, unknownStatus, unknown) |
| + } |
| + } |
| + // Attach: a hostname this app holds for a route out of the team's |
| + // scope answers as taken, the same bytes as any other holder's. |
| + attachDomain(t, w.fx, w.member, "theirs.example.com", "theirs.go.tito.io") |
| + wantStatus, _, want := rawReq(t, http.MethodPost, w.url("/domains"), w.team, attachBody("theirs.example.com", "mine.go.tito.io")) |
| + if wantStatus != http.StatusConflict { |
| + t.Fatalf("attach over an out-of-scope claim = %d %s", wantStatus, want) |
| + } |
| + if status, _, out := rawReq(t, http.MethodPost, w.url("/domains"), w.team, attachBody(host, "mine.go.tito.io")); status != wantStatus || out != want { |
| + t.Errorf("attach over the regional claim = %d %s, want the out-of-scope claim's %d %s", status, out, wantStatus, want) |
| + } |
| + status, out := getJSON(t, w.url("/domains"), w.team) |
| + if status != http.StatusOK { |
| + t.Fatalf("list = %d %v", status, out) |
| + } |
| + for _, row := range out["domains"].([]any) { |
| + if row.(map[string]any)["host"] == host { |
| + t.Errorf("the team's list shows the regional claim: %v", row) |
| + } |
| + } |
| + requireClaimUnchanged(t, w.fx.rel, host, raw, etag, "team doors") |
| + |
| + // A person sees it, marked regional; a single-mode row has no mode. |
| + status, got := getJSON(t, w.url("/domains/"+host), w.member) |
| + if row, _ := got["domain"].(map[string]any); status != http.StatusOK || row["mode"] != "regional" { |
| + t.Errorf("member GET %s = %d %v, want mode regional", host, status, got) |
| + } |
| + status, got = getJSON(t, w.url("/domains/theirs.example.com"), w.member) |
| + row, _ := got["domain"].(map[string]any) |
| + if _, has := row["mode"]; status != http.StatusOK || row == nil || has { |
| + t.Errorf("member GET theirs.example.com = %d %v, want no mode", status, got) |
| + } |
| +} |
| + |
| +// TestAttachOnARegionalClaim (W6 console): attach naming a bound host is a |
| +// 200 no-op (created false, no write, no serial bump, no audit); naming any |
| +// other route is 409 with RD-26's text, and writes nothing. The paths door |
| +// answers the same 409. |
| +func TestAttachOnARegionalClaim(t *testing.T) { |
| + fx, member := instanceFixture(t, "code-rd-attach") |
| + newShopApp(t, fx) |
| + const host = "shop.example.com" |
| + putRegionalClaim(t, fx.rel, host, "bab", "shop", rdHomeHost, false, false) |
| + raw, etag := regionalClaimBytes(t, fx.rel, host) |
| + before := serial(t, fx) |
| + url := domainsURL(fx, "bab", "shop") |
| + for _, bound := range []string{rdHomeHost, rdUKHost} { |
| + code, _, out := rawReq(t, http.MethodPost, url, member, attachBody(host, bound)) |
| + if code != http.StatusOK { |
| + t.Fatalf("attach naming bound %s = %d %s, want 200", bound, code, out) |
| + } |
| + var got domainAttachResp |
| + if err := json.Unmarshal([]byte(out), &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got.Created || got.Host != host { |
| + t.Fatalf("attach naming bound %s = %+v, want created false", bound, got) |
| + } |
| + } |
| + code, _, out := rawReq(t, http.MethodPost, url, member, attachBody(host, "other.example.net")) |
| + if code != http.StatusConflict || cutoverErrorOf(out) != domains.ErrRegionalClaim.Error() { |
| + t.Fatalf("attach naming another route = %d %s, want 409 RD-26", code, out) |
| + } |
| + // The paths door on the same claim: SetClaimPaths refuses it, 409 RD-26. |
| + code, _, out = rawReq(t, http.MethodPut, url+"/"+host+"/paths", member, `{"paths":{"docs":"`+rdUKHost+`"}}`) |
| + if code != http.StatusConflict || cutoverErrorOf(out) != domains.ErrRegionalClaim.Error() { |
| + t.Fatalf("paths = %d %s, want 409 RD-26", code, out) |
| + } |
| + requireClaimUnchanged(t, fx.rel, host, raw, etag, "attach and paths") |
| + if got := serial(t, fx); got != before { |
| + t.Fatalf("serial %d after attaches that wrote nothing, was %d", got, before) |
| + } |
| + if n := eventsOf(t, fx.st, "shop", "domain-attach"); n != 0 { |
| + t.Fatalf("%d domain-attach rows, want none", n) |
| + } |
| +} |
| + |
| +// TestFirstRouteAttachOnARegionalHostWritesNoRecord (W6): an app with no |
| +// ready route attaching a regional host it owns is refused 409 RD-26 before |
| +// any record is declared, lifetimes off and on, and on a host-claim console. |
| +func TestFirstRouteAttachOnARegionalHostWritesNoRecord(t *testing.T) { |
| + for _, on := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on], func(t *testing.T) { |
| + var ( |
| + l lifetimesFx |
| + ctx = context.Background() |
| + ) |
| + if on { |
| + lo := newLtOn(t) |
| + l, ctx = lo.lifetimesFx, onCtx(t, lo.fx.srv) |
| + } else { |
| + l = newLifetimesFx(t) |
| + } |
| + putRegionalClaim(t, l.fx.rel, ltDomain, "bab", ltApp, rdHomeHost, false, false) |
| + raw, etag := regionalClaimBytes(t, l.fx.rel, ltDomain) |
| + acct, err := l.fx.st.AccountBySqid("bab") |
| + if err != nil || acct == nil { |
| + t.Fatalf("account bab: %v", err) |
| + } |
| + _, ref := l.fx.srv.attachDomain(ctx, acct, ltApp, ltDomain, "", "stable", "paul@keymail.dev") |
| + if ref == nil || ref.Status != http.StatusConflict || ref.Msg != domains.ErrRegionalClaim.Error() { |
| + t.Fatalf("first-route attach = %+v, want 409 RD-26", ref) |
| + } |
| + requireNoRecord(t, l.fx.rel, ltApp, ltDomain) |
| + if n, err := l.fx.st.PendingForHost(ltDomain, ""); err != nil || n != 0 { |
| + t.Fatalf("PendingForHost = %d, %v, want 0", n, err) |
| + } |
| + requireClaimUnchanged(t, l.fx.rel, ltDomain, raw, etag, "first-route attach") |
| + }) |
| + } |
| + t.Run("host-claim console", func(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.HostClaim = true |
| + putRegionalClaim(t, fx.rel, ltDomain, "bab", ltApp, rdHomeHost, false, false) |
| + raw, etag := regionalClaimBytes(t, fx.rel, ltDomain) |
| + acct, err := fx.st.AccountBySqid("bab") |
| + if err != nil || acct == nil { |
| + t.Fatalf("account bab: %v", err) |
| + } |
| + _, ref := fx.srv.attachClaimFirstRoute(context.Background(), acct, ltApp, ltDomain, "stable", "paul@keymail.dev") |
| + if ref == nil || ref.Status != http.StatusConflict || ref.Msg != domains.ErrRegionalClaim.Error() { |
| + t.Fatalf("host-claim first-route attach = %+v, want 409 RD-26", ref) |
| + } |
| + requireNoRecord(t, fx.rel, ltApp, ltDomain) |
| + requireClaimUnchanged(t, fx.rel, ltDomain, raw, etag, "host-claim first-route attach") |
| + }) |
| +} |
| + |
| +// TestSetDomainCapabilitiesRefusesARegionalChangeBeforeDNS: through the |
| +// attach door on a bound host, a capability change on a regional claim is |
| +// 409 RD-26 before any DNS work (no CNAME lookup, no wildFail count) and |
| +// writes nothing; the same values are a 200 that writes nothing, audits |
| +// nothing and bumps no serial. |
| +func TestSetDomainCapabilitiesRefusesARegionalChangeBeforeDNS(t *testing.T) { |
| + fx, member := instanceFixture(t, "code-rd-caps") |
| + newShopApp(t, fx) |
| + fx.srv.delegationZone = "acme.example.org" |
| + var lookups atomic.Int32 |
| + fx.srv.lookupCNAME = func(context.Context, string) (string, error) { |
| + lookups.Add(1) |
| + return "", errors.New("not found") |
| + } |
| + const plain, both = "shop.example.com", "all.example.com" |
| + putRegionalClaim(t, fx.rel, plain, "bab", "shop", rdHomeHost, false, false) |
| + putRegionalClaim(t, fx.rel, both, "bab", "shop", rdHomeHost, true, true) |
| + url := domainsURL(fx, "bab", "shop") |
| + cases := []struct { |
| + host, flags string |
| + refused bool |
| + }{ |
| + {plain, `"wildcard":true`, true}, |
| + {plain, `"catchall":true`, true}, |
| + {plain, `"wildcard":true,"catchall":true`, true}, |
| + {both, `"wildcard":false`, true}, |
| + {both, `"catchall":false`, true}, |
| + {plain, `"wildcard":false`, false}, |
| + {plain, `"wildcard":false,"catchall":false`, false}, |
| + {plain, `"catchall":false`, false}, |
| + {both, `"wildcard":true`, false}, |
| + {both, `"catchall":true`, false}, |
| + {both, `"wildcard":true,"catchall":true`, false}, |
| + } |
| + for _, c := range cases { |
| + raw, etag := regionalClaimBytes(t, fx.rel, c.host) |
| + before := serial(t, fx) |
| + body := `{"host":"` + c.host + `","route":"` + rdHomeHost + `",` + c.flags + `}` |
| + code, _, out := rawReq(t, http.MethodPost, url, member, body) |
| + switch { |
| + case c.refused && (code != http.StatusConflict || cutoverErrorOf(out) != domains.ErrRegionalClaim.Error()): |
| + t.Errorf("%s = %d %s, want 409 RD-26", body, code, out) |
| + case !c.refused && code != http.StatusOK: |
| + t.Errorf("%s = %d %s, want 200", body, code, out) |
| + } |
| + requireClaimUnchanged(t, fx.rel, c.host, raw, etag, body) |
| + if got := serial(t, fx); got != before { |
| + t.Errorf("%s: serial %d, was %d", body, got, before) |
| + } |
| + } |
| + if n := lookups.Load(); n != 0 { |
| + t.Fatalf("lookupCNAME called %d times, want 0", n) |
| + } |
| + if n := wildFailHits(fx.srv); n != 0 { |
| + t.Fatalf("wildFail counted %d failures, want 0", n) |
| + } |
| + if n := eventsOf(t, fx.st, "shop", "domain-capabilities"); n != 0 { |
| + t.Fatalf("%d domain-capabilities rows, want none", n) |
| + } |
| +} |
| + |
| +// rdCreate posts an instance create of host to app shop as token. |
| +func rdCreate(t *testing.T, fx *consoleFixture, token, host string) (int, string) { |
| + t.Helper() |
| + code, _, body := rawReq(t, http.MethodPost, instancesURL(fx, "bab", ltApp), token, `{"host":"`+host+`"}`) |
| + return code, body |
| +} |
| + |
| +// TestInstanceCreateRefusesARegionalHost (W11): an instance create at a |
| +// regional name is refused, lifetimes off and on: 409 RD-27 when the claim |
| +// is this account's (its own app's or another app's), and today's neutral |
| +// bytes when it is another account's. No record or allocation is written. |
| +func TestInstanceCreateRefusesARegionalHost(t *testing.T) { |
| + cases := []struct { |
| + name, acct, app, want string |
| + }{ |
| + {"the claim's own app", "bab", ltApp, rdHeldMsg(ltOne)}, |
| + {"another app of the account", "bab", "web", rdHeldMsg(ltOne)}, |
| + {"another account", "acme", "web", hostHeldSentence(ltOne, nil)}, |
| + } |
| + for _, on := range []bool{false, true} { |
| + for _, c := range cases { |
| + name := map[bool]string{false: "lifetimes off/", true: "lifetimes on/"}[on] + c.name |
| + t.Run(name, func(t *testing.T) { |
| + var l lifetimesFx |
| + if on { |
| + l = newLtOn(t).lifetimesFx |
| + } else { |
| + l = newLifetimesFx(t) |
| + } |
| + putRegionalClaim(t, l.fx.rel, ltOne, c.acct, c.app, rdHomeHost, false, false) |
| + code, out := rdCreate(t, l.fx, l.member, ltOne) |
| + if code != http.StatusConflict || cutoverErrorOf(out) != c.want { |
| + t.Fatalf("create = %d %s, want 409 %q", code, out, c.want) |
| + } |
| + requireNoRecord(t, l.fx.rel, ltApp, ltOne) |
| + if rows := allocRows(t, l.fx.st, ltOne); len(rows) != 0 { |
| + t.Fatalf("allocations %+v, want none", rows) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// TestRegionalRecheckLeavesNoPendingAllocation (W11, rev 5): the door's |
| +// first claim check passes (no claim yet) and the regional claim lands while |
| +// the create waits for the hostname lock. The recheck under that lock |
| +// refuses it with RD-27 before anything is durable: with lifetimes on no |
| +// allocation is pending and the recovery pass writes no record; with |
| +// lifetimes off the legacy create takes the app lock, then the hostname, |
| +// and writes nothing. |
| +func TestRegionalRecheckLeavesNoPendingAllocation(t *testing.T) { |
| + for _, on := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on], func(t *testing.T) { |
| + var l lifetimesFx |
| + if on { |
| + l = newLtOn(t).lifetimesFx |
| + } else { |
| + l = newLifetimesFx(t) |
| + } |
| + var ( |
| + mu sync.Mutex |
| + held []string |
| + fired atomic.Bool |
| + writeErr error |
| + ) |
| + h := func(kind, key, event string) { |
| + if event != lockHeld { |
| + return |
| + } |
| + mu.Lock() |
| + held = append(held, kind+" "+key) |
| + mu.Unlock() |
| + if kind == "host" && key == ltOne && fired.CompareAndSwap(false, true) { |
| + err := writeRegionalClaim(l.fx.rel, ltOne, "bab", ltApp, rdHomeHost, false, false) |
| + mu.Lock() |
| + writeErr = err |
| + mu.Unlock() |
| + } |
| + } |
| + lifetimeLockHook.Store(&h) |
| + t.Cleanup(func() { lifetimeLockHook.Store(nil) }) |
| + code, out := rdCreate(t, l.fx, l.member, ltOne) |
| + lifetimeLockHook.Store(nil) |
| + mu.Lock() |
| + err := writeErr |
| + mu.Unlock() |
| + if !fired.Load() || err != nil { |
| + t.Fatalf("the claim was not written under the hostname lock (fired %v): %v", fired.Load(), err) |
| + } |
| + if code != http.StatusConflict || cutoverErrorOf(out) != rdHeldMsg(ltOne) { |
| + t.Fatalf("create = %d %s, want 409 RD-27", code, out) |
| + } |
| + requireNoRecord(t, l.fx.rel, ltApp, ltOne) |
| + mu.Lock() |
| + app, host := slices.Index(held, "app bab/"+ltApp), slices.Index(held, "host "+ltOne) |
| + mu.Unlock() |
| + if app < 0 || host < 0 || app > host { |
| + t.Fatalf("locks held %v, want the app lock then the hostname", held) |
| + } |
| + if !on { |
| + return |
| + } |
| + // Errorf, so the recovery leg below still runs and shows what a |
| + // pending allocation would become. |
| + if n, err := l.fx.st.PendingForHost(ltOne, ""); err != nil || n != 0 { |
| + t.Errorf("PendingForHost = %d, %v, want 0", n, err) |
| + } |
| + recoverOn(t, l.fx.srv) |
| + requireNoRecord(t, l.fx.rel, ltApp, ltOne) |
| + }) |
| + } |
| +} |
diff --git a/internal/console/teamdoors.go b/internal/console/teamdoors.go| index 9d0743a75..24bb122a1 100644 |
| --- a/internal/console/teamdoors.go |
| +++ b/internal/console/teamdoors.go |
| @@ -226,12 +226,14 @@ func (tv *teamView) inScopeHost(ctx context.Context, s *Server, host string) (*p |
| // account's and app's, with a non-empty Route that is an instance in |
| // scope. A claim with Route == "" (a first-route or static claim) is out of |
| // scope by definition (§3), so the alias door can never retire a record. |
| +// A regional claim (#447, spec §6.4) is out of scope too, whichever of its |
| +// bound hosts is in scope: it serves the app in every region at once. |
| func (tv *teamView) inScopeClaim(ctx context.Context, s *Server, host string) (*domains.Claim, bool, error) { |
| c, err := domains.GetClaim(ctx, s.cfg.Releases, host) |
| if err != nil && !errors.Is(err, os.ErrNotExist) { |
| return nil, false, err |
| } |
| - if err != nil || c == nil || c.Account != tv.acct.Sqid || c.App != tv.app || c.Route == "" || c.Instances { |
| + if err != nil || c == nil || c.Account != tv.acct.Sqid || c.App != tv.app || c.Route == "" || c.Instances || c.Regional() { |
| return nil, false, nil |
| } |
| _, ok, err := tv.inScopeHost(ctx, s, c.Route) |