carlos / platform Public

Regional domains (#447) Task 7: the placements PUT door

PUT /api/cli/apps/{account}/{app}/domains/{host}/placements (person only,
svcrole.Set{}) creates a regional claim or replaces the set on the caller's
own, in spec §6.2's order: gates (RD-25 on a host-claim console), hostname,
bindings (RD-17..RD-20), then under lockAppHost and the new regionalMu the
claim rule (RD-21, RD-26 on a capability change, neutral 409), one
snapshot with the incomplete-evidence check run once, the declared-
ownership walk (provision.RecordHostDeclared, keys only, strict) and
PendingForHost (both fail closed), the never-served/collision/overlap
tests and the descendant scan on create with catchall (neutral 409), the
barrier (RD-23/RD-41 then aliases_read 503), proof (409 with verify) and
the extracted wildcardEnablingRefusal, SetClaimPlacements (RD-24 on CAS),
audit + serial only on change, and the GET body.

The plan-cap check runs before the claim rule (except on a claim the
caller already holds, verified) so a capped caller cannot tell a held
name from a free one. Draft copy rows RD-40 and RD-41 added.

Mutation checks (each guard removed, named test failed, restored):
- pending > 0: TestPlacementsPutEvidenceRefusals/a_pending_operation:
  "a pending allocation = 200"
- declared: TestPlacementsPutDeclaredOwnership: "another account's
  record = 200", "the caller's own record = 200"
- heartbeat rows: .../alias_rows: "a heartbeat listing shop.example.com = 200"
- *.host published: .../a_real_route: "betty publishing *.shop.example.com = 200"
- GET of *.X: TestPlacementsPutTwoLabelApex "want domains/*.example.com.json
  read"; TestPlacementsPutOverlapRefusals "an instance catch-all on the host = 200"
- floor before aliases_read: TestPlacementsRefusesWithABoxBelowTheFloor
  "betty at v0.30.2 = 503"
- capabilities fixed: TestPlacementsPutCapabilitiesAtCreation "a capability change = 200"
- proof: TestPlacementsPutClaimStates "unproven create = 200"
- own verified RD-21: TestPlacementsPutClaimStates "own verified alias.example.com = 409 hostname unavailable"
- enabling gate: TestPlacementsPutCapabilitiesAtCreation "no delegation zone = 200"
- descendant scan: TestPlacementsPutCapabilitiesAtCreation "a regional claim under it = 200"
- parent Catchall: TestPlacementsPutOverlapRefusals "a parent claim with catchall = 200"
- EvidenceComplete: TestPlacementsPutEvidenceRefusals "an edges file that does not read = 200" (and two more)
- CAS mapping: TestPlacementsPutUnchangedWritesNothing "a racing write = 502"
- fleet placement: TestPlacementsPutTargetRefusals "a fleet-placed instance = 200"
- cap ordering: TestPlacementsPutPlanCapComesFirst "another owner's name = 409 hostname unavailable"
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 63f904b2a4305b9e24f31c1859e9ea770712a0bb parent 782a301
12 files changed, +1,809 −39
  • docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md +2 −0
  • internal/console/apidomains.go +42 −33
  • internal/console/apiplacements.go +615 −4
  • internal/console/apiplacements_put_test.go +958 −0
  • internal/console/authcli.go +5 −0
  • internal/console/claim_invariant_fixtures_test.go +9 −0
  • internal/console/claim_invariant_test.go +2 −0
  • internal/console/server.go +6 −0
  • internal/console/svcroutes_test.go +7 −2
  • internal/console/testdata/claim-routes.txt +1 −0
  • internal/provision/recordhost.go +45 −0
  • internal/provision/recordhost_test.go +117 −0
diff --git a/docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md b/docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md
index fe35e73c6..8e4c149b0 100644
--- a/docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md
+++ b/docs/superpowers/plans/2026-10-28-regional-domains-447-copy.md
@@ -81,6 +81,8 @@ count.
| RD-27 | internal/console/apex.go | <host> is a regional domain, so it cannot also be an instance's hostname. choose another name. | draft |
| RD-28 | internal/console/apidomains.go | a catch-all on <host> would cover a regional domain under it, so it cannot be turned on. | draft |
| RD-29 | internal/console/domaincatchall.go | an instance catch-all cannot cover a regional domain. | draft |
+| RD-40 | internal/console/apiplacements.go | given a regional domain | draft |
+| RD-41 | internal/console/apiplacements.go | <box> does not say which release it runs. try again when every server runs <floor> or later. | draft |
## Release floor (operators: internal/release, internal/console, system.go)
diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index 180c63cfd..b184ad229 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -716,39 +716,8 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
// 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-
- // wildcards spec's ACME story (§4): this deployment's own zone
- // issues the wildcard cert, so it must control the challenge record.
- if s.delegationZone == "" {
- jsonError(w, http.StatusUnprocessableEntity, "deployment has no delegation zone configured")
- return false
- }
- // PEEKED before the DNS round trip (C33 review): once a principal
- // has already tripped wildFail, running the lookup again buys the
- // caller nothing but costs the console another live, sequential
- // outbound DNS call. A caller who has never failed never trips
- // this — wildFailTripped only ever reads TRUE from a count that
- // CONSUMED (below) put there — so this can never turn away a
- // legitimate, exempt caller.
- if s.wildFailTripped(p, time.Now()) {
- jsonError(w, http.StatusTooManyRequests, wildFailMsg)
- return false
- }
- if !s.delegationCNAMEDelegated(ctx, host) {
- // CONSUMED only here, on an ACTUAL failure (spec §4a). A
- // succeeding enable is once-per-domain and exempt (domainsGate
- // carries only the convergence ceiling, not a workload budget);
- // a failure is what the peek above exists to eventually stop
- // paying for. Counted AFTER the lookup, so the bound is on
- // FAILURES rather than on attempts — a caller whose CNAME is
- // correct never meets it at all.
- if !s.allowWildFail(p, time.Now()) {
- jsonError(w, http.StatusTooManyRequests, wildFailMsg)
- return false
- }
- jsonError(w, http.StatusUnprocessableEntity,
- "create CNAME _acme-challenge."+host+" -> _acme-challenge."+host+"."+s.delegationZone+", then retry")
+ if ref := s.wildcardEnablingRefusal(ctx, p, host); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
return false
}
}
@@ -785,6 +754,46 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
return true
}
+// wildcardEnablingRefusal is the gate a claim's Wildcard passes on its way
+// from false to true: setDomainCapabilities runs it on that transition, and
+// the placements door (apiplacements.go, #447) runs it when it creates a
+// regional claim with wildcard, so neither door is a way round the other's
+// CNAME check. nil admits.
+func (s *Server) wildcardEnablingRefusal(ctx context.Context, p Principal, host string) *doorRefusal {
+ // Enabling wildcard requires a configured delegation zone and a live
+ // _acme-challenge CNAME delegating to it — the claim-derived-
+ // wildcards spec's ACME story (§4): this deployment's own zone
+ // issues the wildcard cert, so it must control the challenge record.
+ if s.delegationZone == "" {
+ return &doorRefusal{http.StatusUnprocessableEntity, "deployment has no delegation zone configured"}
+ }
+ // PEEKED before the DNS round trip (C33 review): once a principal
+ // has already tripped wildFail, running the lookup again buys the
+ // caller nothing but costs the console another live, sequential
+ // outbound DNS call. A caller who has never failed never trips
+ // this — wildFailTripped only ever reads TRUE from a count that
+ // CONSUMED (below) put there — so this can never turn away a
+ // legitimate, exempt caller.
+ if s.wildFailTripped(p, time.Now()) {
+ return &doorRefusal{http.StatusTooManyRequests, wildFailMsg}
+ }
+ if !s.delegationCNAMEDelegated(ctx, host) {
+ // CONSUMED only here, on an ACTUAL failure (spec §4a). A
+ // succeeding enable is once-per-domain and exempt (domainsGate
+ // carries only the convergence ceiling, not a workload budget);
+ // a failure is what the peek above exists to eventually stop
+ // paying for. Counted AFTER the lookup, so the bound is on
+ // FAILURES rather than on attempts — a caller whose CNAME is
+ // correct never meets it at all.
+ if !s.allowWildFail(p, time.Now()) {
+ return &doorRefusal{http.StatusTooManyRequests, wildFailMsg}
+ }
+ return &doorRefusal{http.StatusUnprocessableEntity,
+ "create CNAME _acme-challenge." + host + " -> _acme-challenge." + host + "." + s.delegationZone + ", then retry"}
+ }
+ return nil
+}
+
// delegationCNAMEDelegated reports whether host's _acme-challenge CNAME
// already points at this deployment's delegation zone — the same check the
// attach gate and the list stamp both use, so a claim's delegation_status
diff --git a/internal/console/apiplacements.go b/internal/console/apiplacements.go
index a3b02c8e7..acf973e65 100644
--- a/internal/console/apiplacements.go
+++ b/internal/console/apiplacements.go
@@ -1,22 +1,28 @@
package console
-// The placements door (#447, spec §6.5): for one alias claim, which boxes
-// serve its target in each region, the addresses they answer on and whether
-// the region is ready for DNS. Read only in this task; the PUT that makes a
-// claim regional, and the regional rules of the view, come later.
+// The placements doors (#447). The GET (spec §6.5): for one alias claim,
+// which boxes serve its target in each region, the addresses they answer on
+// and whether the region is ready for DNS. The PUT (spec §6.2): the only way
+// into regional mode, creating a regional claim or replacing the set on the
+// caller's own. The regional rules of the GET's view come later (Task 9).
import (
"context"
"encoding/json"
"errors"
+ "fmt"
"log"
"net/http"
"os"
"sort"
+ "strings"
+ "sync"
"time"
"github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/status"
)
@@ -211,3 +217,608 @@ func boxAtRegionalFloor(b status.Box) bool {
v, ok := release.ParseReleaseVersion(b.Metrics.Release)
return ok && v.Compare(release.RegionalDomainsFloor) >= 0
}
+
+// The PUT door's member-facing refusals (copy deck, draft RD rows). The
+// neutral 409 of every evidence, walk and overlap refusal is the attach
+// door's hostUnavailableMsg, so this door says nothing an attach does not.
+const (
+ // RD-17: the body names no placement, or more than eight.
+ placementsCountMsg = "give between one and eight placements, one per region."
+ // RD-24: the claim changed between this request's read and its write.
+ placementsChangedMsg = "the placements changed while this request ran. try again."
+ // RD-25: a console with the shelved host-claim mode on.
+ placementsHostClaimMsg = "regional domains are not available on this console yet."
+)
+
+// RD-18.
+func placementsRegionTwiceMsg(region string) string {
+ return fmt.Sprintf("%s is named twice. give one instance per region.", region)
+}
+
+// RD-19.
+func placementsHostTwiceMsg(host string) string {
+ return fmt.Sprintf("%s is named for two regions. give a different instance in each region.", host)
+}
+
+// RD-20. The same bytes for a host nobody holds, another app's or another
+// account's, and one of this app's in another region.
+func placementsNotInstanceMsg(host, region string) string {
+ return fmt.Sprintf("%s is not an instance of this app in %s.", host, region)
+}
+
+// RD-21.
+func placementsOrdinaryMsg(host string) string {
+ return fmt.Sprintf("%s is already attached to this app as an ordinary domain. detach it first, then set placements to attach it again as a regional domain.", host)
+}
+
+// RD-23.
+func placementsBelowFloorMsg(box, rel, floor string) string {
+ return fmt.Sprintf("%s runs %s, which cannot serve regional domains. try again when every server runs %s or later.", box, rel, floor)
+}
+
+// RD-41: RD-23 for a box whose heartbeat names no release.
+func placementsNoReleaseMsg(box, floor string) string {
+ return fmt.Sprintf("%s does not say which release it runs. try again when every server runs %s or later.", box, floor)
+}
+
+// placementsControlPlaneVerb (RD-40) completes controlPlaneRefusal's
+// sentence: "<app> is marked as the control plane, so it cannot be ...".
+const placementsControlPlaneVerb = "given a regional domain"
+
+// placementIn is one binding of the PUT body: a region as the member names
+// it and the instance hostname that serves the claim there.
+type placementIn struct {
+ Region string `json:"region"`
+ Host string `json:"host"`
+}
+
+// placementsPutBody is the PUT body: the whole set, and the two
+// capabilities, which take effect only when the PUT creates the claim.
+type placementsPutBody struct {
+ Placements []placementIn `json:"placements"`
+ Wildcard *bool `json:"wildcard,omitempty"`
+ Catchall *bool `json:"catchall,omitempty"`
+}
+
+// handleAPIDomainPlacementsPut answers PUT .../domains/{host}/placements
+// (spec §6.2): it creates a regional claim on host, or replaces the set on
+// the caller's own. The steps run in the spec's order, and each step's
+// refusals come before the next step reads anything:
+//
+// 1. gates: domainsGate, a person, not temporary, not the control plane,
+// not a host-claim console;
+// 2. the hostname;
+// 3. the body, each binding an instance record of this app in its region;
+// 4. under the app lock, the hostname exclusion and regionalMu, the claim
+// rule (never-served half one: the claim's own state);
+// 5. one snapshot (edges files and heartbeats), the declared-ownership
+// walk and the pending-operation read, each failing closed;
+// 6. the never-served evidence, the collision and overlap tests, and on a
+// create with catchall the descendant scan, all the neutral 409;
+// 7. the activation barrier (§10.3) on the heartbeats step 5 loaded;
+// 8. proof and, with wildcard, the enabling gate, when the write creates;
+// 9. the write, audited and announced only when bytes changed;
+// 10. the GET body, built from the step-5 snapshot. No further reads.
+//
+// The locks are released on every return.
+func (s *Server) handleAPIDomainPlacementsPut(w http.ResponseWriter, r *http.Request) {
+ // Step 1.
+ p, acct, app, ok := s.domainsGate(w, r)
+ if !ok {
+ return
+ }
+ if !s.apiPerson(w, r) {
+ return
+ }
+ if s.refuseTemporary(w, acct, app, "attach a domain to it") {
+ return
+ }
+ if s.refuseControlPlane(w, acct, app, placementsControlPlaneVerb) {
+ return
+ }
+ // The shelved host-claim mode writes claims through another authority
+ // that knows nothing of placements (plan, "spec against the code" 9).
+ if s.cfg.HostClaim {
+ jsonError(w, http.StatusConflict, placementsHostClaimMsg)
+ return
+ }
+
+ // Step 2. The hostname becomes a bucket key segment and, on every box,
+ // a routing key: nothing below runs until it is well formed.
+ host, ok := domains.NormalizeAliasHost(r.PathValue("host"))
+ if !ok {
+ jsonError(w, http.StatusBadRequest,
+ "invalid hostname — attach a full hostname like tickets.example.com")
+ return
+ }
+ if s.domainHostPolicy(host, acct.Sqid) != hostOpen || s.directAppsDomainHost(host) {
+ jsonError(w, http.StatusBadRequest, "that hostname is platform-managed")
+ return
+ }
+
+ // Step 3. Strict decoding: the capabilities are fixed for the claim's
+ // life, so a misspelt key must not create a claim without them.
+ var in placementsPutBody
+ if !readJSONStrictLimit(w, r, &in, 8<<10) {
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ defer cancel()
+ set, ref := s.placementsBindings(ctx, acct, app, in.Placements)
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ 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
+ // do every create, retirement, migration and recovery of the host, so
+ // step 5's PendingForHost read cannot be overtaken. Then regionalMu,
+ // held from the evidence to the write.
+ defer s.lockAppHost(acct.Sqid, app, host)()
+ s.regionalMu.Lock()
+ defer s.regionalMu.Unlock()
+ now := time.Now()
+ prove := onceProver(s.domainProver(ctx, host, acct.Sqid))
+ cur, etag, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
+ if errors.Is(err, os.ErrNotExist) {
+ cur, etag, err = nil, "", nil
+ }
+ if err != nil {
+ log.Printf("console: api domain placements put %s/%s %s: read claim: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, "could not read the hostname")
+ return
+ }
+ // The plan cap on custom domains (customDomainRefusal: the console's own
+ // database, no bucket request) comes before any answer about another
+ // owner's claim, as attach puts it before its ownership check: judged
+ // after, a capped caller would read "someone holds this" from the
+ // neutral 409 against the cap sentence for a free name. Only a claim
+ // the caller already holds, verified, skips it: that is no new domain.
+ own := cur != nil && cur.Account == acct.Sqid && cur.App == app
+ if !own || cur.Pending {
+ if ref := s.customDomainRefusal(acct, host); ref != nil {
+ writeJSON(w, ref.Status, capOrError(ref))
+ return
+ }
+ }
+ // create: the write makes a new claim, from nothing or over a pending
+ // one, and nothing of a replaced pending claim survives it.
+ create := true
+ switch {
+ case cur == nil:
+ case own && cur.Regional():
+ create = false
+ 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.
+ jsonError(w, http.StatusConflict, domains.ErrRegionalClaim.Error())
+ return
+ }
+ case own && cur.Pending:
+ // A pending claim never derived a row on any binary since #215,
+ // so replacing it is not a conversion.
+ case own:
+ // A verified ordinary claim may have served as an alias or a first
+ // route, and nothing can show that it did not (ruling 4).
+ jsonError(w, http.StatusConflict, placementsOrdinaryMsg(host))
+ return
+ case cur.Pending && (!cur.PendingLive(now) || prove()):
+ // Another owner's reservation, which AttachClaimProven's rule
+ // lets this caller take: run out, or proven now.
+ default:
+ jsonError(w, http.StatusConflict, hostUnavailableMsg)
+ return
+ }
+
+ // Step 5. One snapshot, shared by every check below and the answer.
+ var (
+ snap edgesfile.Snapshot
+ snapErr error
+ boxes []status.Box
+ complete bool
+ boxesErr error
+ )
+ runConcurrently(
+ func() { snap, snapErr = readEdgesSnapshotConcurrently(ctx, s.cfg.Releases) },
+ func() { boxes, complete, boxesErr = s.loadBoxes(ctx, s.cfg.Releases, "") },
+ )
+ if err := errors.Join(snapErr, boxesErr); err != nil {
+ log.Printf("console: api domain placements put %s/%s %s: snapshot: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ return
+ }
+ snap = edgesfile.JoinLive(snap, boxes, complete, nil, now)
+ // The incomplete-evidence check, run once (controller ruling): the
+ // barrier at step 7 judges the same heartbeats and does not repeat it.
+ if regionalEvidenceMissing(boxes, snap.EvidenceComplete(), now) {
+ log.Printf("console: api domain placements put %s/%s %s: evidence incomplete (edges complete %v, heartbeats complete %v)",
+ acct.Sqid, app, host, snap.Complete, snap.BoxesComplete)
+ jsonError(w, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ return
+ }
+
+ // Step 6 (with step 5's walk and pending read, which fail closed first).
+ if ref := s.regionalEvidenceRefusal(ctx, host, snap, boxes, now); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ if ref := s.regionalOverlapRefusal(ctx, host, snap, boxes, now); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ if create && wantCatchall {
+ if ref := s.regionalDescendantRefusal(ctx, host); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ }
+
+ // Step 7.
+ if ref := regionalReadyRefusal(boxes, now); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+
+ // Steps 8 and 9.
+ next := domains.Claim{Host: host, Account: acct.Sqid, App: app, Placements: set}
+ if create {
+ next.Route = set[0].Host // the first binding in body order
+ next.CreatedAt = now.UTC().Format(time.RFC3339)
+ next.CreatedBy = auditActor(p, acct)
+ next.Wildcard, next.Catchall = wantWildcard, wantCatchall
+ // The PUT never writes a pending claim.
+ if !prove() {
+ writeJSON(w, http.StatusConflict, attachAnswer(host, next.Route, false, true, s.domainChallenge(host, acct.Sqid)))
+ return
+ }
+ if wantWildcard {
+ if ref := s.wildcardEnablingRefusal(ctx, p, host); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ }
+ } else {
+ next.Route = domains.RegionalRoute(set, cur.Route)
+ next.CreatedAt, next.CreatedBy = cur.CreatedAt, cur.CreatedBy
+ next.Wildcard, next.Catchall = cur.Wildcard, cur.Catchall
+ }
+ changed, err := domains.SetClaimPlacements(ctx, s.cfg.Releases, next, cur, etag)
+ if errors.Is(err, release.ErrCASConflict) {
+ jsonError(w, http.StatusConflict, placementsChangedMsg)
+ return
+ } else if err != nil {
+ log.Printf("console: api domain placements put %s/%s %s: write: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, "could not attach the hostname — try again")
+ return
+ }
+ if changed {
+ pairs := make([]string, 0, len(set))
+ for _, b := range set {
+ pairs = append(pairs, s.homeRegionOut(b.Region)+"="+b.Host)
+ }
+ sort.Strings(pairs)
+ s.auditActivity(acct, app, auditActor(p, acct), Activity{
+ Action: "domain-placements", TargetType: "instance", Target: next.Route,
+ Detail: "set placements of " + host + ": " + strings.Join(pairs, ", ") + " (cli)",
+ })
+ s.bumpSerial(ctx)
+ }
+
+ // Step 10. The claim as written (SetClaimPlacements stores the set in
+ // region order) and the step-5 snapshot.
+ written := next
+ written.Schema = 2
+ written.Placements = append([]domains.Placement(nil), set...)
+ sort.SliceStable(written.Placements, func(i, j int) bool { return written.Placements[i].Region < written.Placements[j].Region })
+ writeJSON(w, http.StatusOK, s.placementsView(written, snap, boxes, now))
+}
+
+// onceProver asks prove at most once: the claim rule (another owner's live
+// reservation) and the proof step (any create) share one TXT lookup.
+func onceProver(prove func() bool) func() bool {
+ var (
+ once sync.Once
+ proven bool
+ )
+ return func() bool {
+ once.Do(func() { proven = prove() })
+ return proven
+ }
+}
+
+// placementsBindings is step 3 for the body's placements: 1 to 8; each
+// 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.
+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}
+ }
+ set := make([]domains.Placement, 0, len(in))
+ named := make([]string, 0, len(in)) // each region as the member named it
+ regions, hosts := map[string]bool{}, map[string]bool{}
+ for _, b := range in {
+ given := strings.TrimSpace(b.Region)
+ if given == "" {
+ return nil, &doorRefusal{http.StatusBadRequest, placementsNotInstanceMsg(b.Host, given)}
+ }
+ code := s.homeRegionIn(strings.ToLower(given))
+ if regions[code] {
+ return nil, &doorRefusal{http.StatusBadRequest, placementsRegionTwiceMsg(given)}
+ }
+ regions[code] = true
+ host, ok := domains.NormalizeAliasHost(strings.TrimSpace(b.Host))
+ if !ok || strings.HasSuffix(host, provision.SidecarSuffix) {
+ return nil, &doorRefusal{http.StatusBadRequest, placementsNotInstanceMsg(b.Host, given)}
+ }
+ if hosts[host] {
+ return nil, &doorRefusal{http.StatusBadRequest, placementsHostTwiceMsg(host)}
+ }
+ hosts[host] = true
+ set = append(set, domains.Placement{Region: code, Host: host})
+ named = append(named, given)
+ }
+ recs, _, err := s.listRecords(ctx, acct.Sqid, app, instanceListMax)
+ if err != nil {
+ log.Printf("console: api domain placements put %s/%s: list records: %v", acct.Sqid, app, err)
+ return nil, &doorRefusal{http.StatusBadGateway, "could not read this app's instances"}
+ }
+ byHost := make(map[string]provision.Record, len(recs))
+ for _, rec := range recs {
+ byHost[rec.Host] = rec
+ }
+ 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 {
+ return nil, &doorRefusal{http.StatusBadRequest, placementsNotInstanceMsg(b.Host, named[i])}
+ }
+ }
+ return set, nil
+}
+
+// regionalEvidenceMissing is the PUT's incomplete-evidence rule (spec §6.2
+// step 5): the snapshot is not complete (an edges file or heartbeat that
+// did not read, a fresh box with no edges file, a file with no heartbeat),
+// no box is fresh, or a fresh box's heartbeat carries no metrics. Short of
+// that, "no box holds the name" cannot be concluded.
+func regionalEvidenceMissing(boxes []status.Box, complete bool, now time.Time) bool {
+ if !complete {
+ return true
+ }
+ fresh := freshHeartbeats(boxes, now)
+ if len(fresh) == 0 {
+ return true
+ }
+ for _, b := range fresh {
+ if b.Metrics == nil {
+ return true
+ }
+ }
+ return false
+}
+
+// regionalEvidenceRefusal is spec §6.2 step 6's never-served and collision
+// tests, with step 5's two reads that feed it. The reads come first and fail
+// closed (503 RD-22); then, with no owner exemption, any of these refuses
+// with the neutral 409:
+//
+// - an instance record declared at host, under any account and app, the
+// caller's own included (the walk, provision.RecordHostDeclared);
+// - a pending allocation, retirement or migration of host
+// (PendingForHost, read under the hostname exclusion the caller holds);
+// - a fresh edges file publishing host or "*."+host under role home,
+// alias or not;
+// - a fresh heartbeat listing host, "*."+host or "*."+parent among its
+// alias rows.
+func (s *Server) regionalEvidenceRefusal(ctx context.Context, host string, snap edgesfile.Snapshot, boxes []status.Box, now time.Time) *doorRefusal {
+ unreadable := &doorRefusal{http.StatusServiceUnavailable, placementsUnreadableMsg}
+ declared, err := provision.RecordHostDeclared(ctx, s.cfg.Releases, host)
+ if err != nil {
+ log.Printf("console: api domain placements %s: record walk: %v", host, err)
+ return unreadable
+ }
+ pending, err := s.store.PendingForHost(host, "")
+ if err != nil {
+ log.Printf("console: api domain placements %s: pending operations: %v", host, err)
+ return unreadable
+ }
+ taken := &doorRefusal{http.StatusConflict, hostUnavailableMsg}
+ if declared || pending > 0 {
+ return taken
+ }
+ if publishedHome(snap, host) || publishedHome(snap, "*."+host) {
+ return taken
+ }
+ keys := []string{host, "*." + host}
+ if parent := parentOf(host); parent != "" {
+ keys = append(keys, "*."+parent)
+ }
+ if heartbeatLists(boxes, now, keys...) {
+ return taken
+ }
+ return nil
+}
+
+// regionalOverlapRefusal is spec §6.7's table for a regional claim on host
+// (X) with parent P: the keys that could cover a regional name are *.P
+// (covers X) and *.X (covers the names under X).
+//
+// - domains/*.X.json, always: any object there, whatever its state or
+// body, refuses;
+// - when P has an interior dot (so a claim can exist there):
+// domains/P.json with Catchall, of any schema (a body that does not
+// parse refuses), and domains/*.P.json, any object;
+// - a fresh edges file publishing *.P under role home;
+// - a fresh heartbeat listing *.P.
+//
+// A not-found GET passes; any other GET error is 503 RD-22. Every refusal
+// is the neutral 409.
+func (s *Server) regionalOverlapRefusal(ctx context.Context, host string, snap edgesfile.Snapshot, boxes []status.Box, now time.Time) *doorRefusal {
+ taken := &doorRefusal{http.StatusConflict, hostUnavailableMsg}
+ unreadable := &doorRefusal{http.StatusServiceUnavailable, placementsUnreadableMsg}
+ parent := parentOf(host)
+ if parent != "" && (publishedHome(snap, "*."+parent) || heartbeatLists(boxes, now, "*."+parent)) {
+ return taken
+ }
+ // get is one claim object's bytes: found false on not-found, ref set on
+ // any other error.
+ get := func(claimHost string) (body []byte, found bool, ref *doorRefusal) {
+ raw, _, err := s.cfg.Releases.Get(ctx, domains.ClaimKey(claimHost))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, false, nil
+ }
+ if err != nil {
+ log.Printf("console: api domain placements %s: overlap read of %s: %v", host, claimHost, err)
+ return nil, false, unreadable
+ }
+ return raw, true, nil
+ }
+ if _, found, ref := get("*." + host); ref != nil {
+ return ref
+ } else if found {
+ return taken
+ }
+ if !strings.Contains(parent, ".") {
+ // No claim can exist at P or *.P (NormalizeAliasHost wants an
+ // interior dot), so neither is read.
+ return nil
+ }
+ if raw, found, ref := get(parent); ref != nil {
+ return ref
+ } else if found {
+ var c struct {
+ Catchall bool `json:"catchall"`
+ }
+ if err := json.Unmarshal(raw, &c); err != nil || c.Catchall {
+ return taken
+ }
+ }
+ if _, found, ref := get("*." + parent); ref != nil {
+ return ref
+ } else if found {
+ return taken
+ }
+ return nil
+}
+
+// regionalDescendantRefusal is the descendant scan (spec §6.7): a claim on
+// any "<label>.<parent>" that is regional, or that the listing shows but
+// could not read, makes a catch-all on parent impossible. A listing error
+// is 503 RD-22. The 409 is the neutral one; a door that names the reason
+// (the capability and instance catch-all doors, Task 8) maps it to its own
+// sentence.
+func (s *Server) regionalDescendantRefusal(ctx context.Context, parent string) *doorRefusal {
+ claims, unread, err := s.claims.ListWithUnread(ctx, s.cfg.Releases)
+ if err != nil {
+ log.Printf("console: regional descendant scan under %s: %v", parent, err)
+ return &doorRefusal{http.StatusServiceUnavailable, placementsUnreadableMsg}
+ }
+ under := func(h string) bool {
+ label, ok := strings.CutSuffix(h, "."+parent)
+ return ok && label != "" && !strings.Contains(label, ".")
+ }
+ for _, c := range claims {
+ if c.Regional() && under(c.Host) {
+ return &doorRefusal{http.StatusConflict, hostUnavailableMsg}
+ }
+ }
+ for _, u := range unread {
+ if under(u.Host) {
+ return &doorRefusal{http.StatusConflict, hostUnavailableMsg}
+ }
+ }
+ return nil
+}
+
+// regionalReadyRefusal is the activation barrier (spec §10.3) on the
+// heartbeats the PUT already loaded, after step 5 has judged them complete
+// (regionalEvidenceMissing, the one incomplete-evidence check). A fresh box
+// below release.RegionalDomainsFloor, a missing or unparseable release
+// included, is a 409 naming the first by label with its release. Then a
+// fresh box whose heartbeat does not say its alias read succeeded is
+// incomplete evidence, 503 RD-22. The floor test runs first so that a box
+// on a binary that predates aliases_read, which never sends it, is the one
+// the 409 names. Every platform box counts: every edge must hold the
+// regional entry.
+func regionalReadyRefusal(boxes []status.Box, now time.Time) *doorRefusal {
+ fresh := freshHeartbeats(boxes, now)
+ labels := make([]string, 0, len(fresh))
+ for label := range fresh {
+ labels = append(labels, label)
+ }
+ sort.Strings(labels)
+ floor := "v" + release.RegionalDomainsFloor.String()
+ for _, label := range labels {
+ b := fresh[label]
+ if boxAtRegionalFloor(b) {
+ continue
+ }
+ if b.Metrics == nil || b.Metrics.Release == "" {
+ return &doorRefusal{http.StatusConflict, placementsNoReleaseMsg(label, floor)}
+ }
+ return &doorRefusal{http.StatusConflict, placementsBelowFloorMsg(label, b.Metrics.Release, floor)}
+ }
+ for _, label := range labels {
+ if b := fresh[label]; b.Metrics == nil || !b.Metrics.AliasesRead {
+ return &doorRefusal{http.StatusServiceUnavailable, placementsUnreadableMsg}
+ }
+ }
+ return nil
+}
+
+// parentOf is host without its first label ("" for a one-label host).
+func parentOf(host string) string {
+ _, parent, ok := strings.Cut(host, ".")
+ if !ok {
+ return ""
+ }
+ return parent
+}
+
+// publishedHome reports whether any fresh edges file publishes key under
+// role home, alias or not. An entry that does not decode counts: the door
+// cannot vouch for it.
+func publishedHome(snap edgesfile.Snapshot, key string) bool {
+ for _, f := range snap.Files {
+ if !f.Fresh {
+ continue
+ }
+ raw, ok := f.Hosts[key]
+ if !ok {
+ continue
+ }
+ var h edgesfile.Host
+ if err := json.Unmarshal(raw, &h); err != nil || h.Role == edgesfile.RoleHome {
+ return true
+ }
+ }
+ return false
+}
+
+// heartbeatLists reports whether any fresh heartbeat lists one of keys among
+// its alias rows (Metrics.Aliases: every route_aliases row on the box,
+// published or not, plus its stamped routes).
+func heartbeatLists(boxes []status.Box, now time.Time, keys ...string) bool {
+ for _, b := range freshHeartbeats(boxes, now) {
+ if b.Metrics == nil {
+ continue
+ }
+ for _, k := range keys {
+ if _, ok := b.Metrics.Aliases[k]; ok {
+ return true
+ }
+ }
+ }
+ return false
+}
diff --git a/internal/console/apiplacements_put_test.go b/internal/console/apiplacements_put_test.go
new file mode 100644
index 000000000..d1cf66216
--- /dev/null
+++ b/internal/console/apiplacements_put_test.go
@@ -0,0 +1,958 @@
+package console
+
+// The placements PUT (apiplacements.go, #447 Task 7, spec §6.2): the only
+// way into regional mode. Every test goes through the real console server,
+// the real claim writer, real heartbeats (status.WriteBox), real instance
+// records (provision.CreateRecord) and edges files in the shape a box
+// publishes them.
+//
+// newRegionalWorld is the shared world (Tasks 8 and 9 reuse it): see its
+// comment for what it holds.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "os"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// The world's two bound instances (the same names Task 3's helpers use).
+const (
+ rdIE = rdHomeHost // shop-ie.example.net, the home region, named "ie"
+ rdUK = rdUKHost // shop-uk.example.net, uk
+ rdHost = "shop.example.com"
+)
+
+// regionalWorld is the placements PUT's test world: a console whose ops
+// account (fx.sqid) holds app shop, the home region named "ie", two
+// instance records of shop (rdIE at home, rdUK in uk), and two fresh boxes
+// at the regional floor, each with a heartbeat that says aliases_read and
+// an edges file carrying its eip, placement and hosts: annie (home) serving
+// rdIE and betty (uk) serving rdUK. Tests change a box with putBox.
+type regionalWorld struct {
+ fx *consoleFixture
+ token string
+ reg *registry.Registry
+}
+
+// regionalBox is one box of the world: its heartbeat and its edges file.
+type regionalBox struct {
+ Label, Placement, EIP string
+ // Hosts is the edges file's hosts block.
+ Hosts map[string]edgesfile.Host
+ // Release is the heartbeat's metrics.release; At its generated_at.
+ Release string
+ At time.Time
+ // AliasesRead and Aliases are the heartbeat's alias read and rows.
+ AliasesRead bool
+ Aliases map[string]status.AliasReading
+ // NoMetrics writes a heartbeat with no metrics object; NoEdges writes
+ // no edges file.
+ NoMetrics, NoEdges bool
+}
+
+// rdBox is a fresh box at the floor whose alias read succeeded, publishing
+// each of serves under home.
+func rdBox(label, placement, eip string, serves ...string) regionalBox {
+ hosts := map[string]edgesfile.Host{}
+ for _, h := range serves {
+ hosts[h] = edgesfile.Host{Role: edgesfile.RoleHome}
+ }
+ return regionalBox{Label: label, Placement: placement, EIP: eip, Hosts: hosts,
+ Release: rdFloor(), At: time.Now(), AliasesRead: true}
+}
+
+// rdFloor is the regional floor as a release tag.
+func rdFloor() string { return "v" + release.RegionalDomainsFloor.String() }
+
+func newRegionalWorld(t *testing.T, code string) *regionalWorld {
+ t.Helper()
+ fx, token, reg := rootfsDoorWorldToken(t, code)
+ fx.srv.cfg.HomeRegion = "ie"
+ w := &regionalWorld{fx: fx, token: token, reg: reg}
+ w.putRecord(t, fx.sqid, "shop", rdIE, "", nil)
+ w.putRecord(t, fx.sqid, "shop", rdUK, "uk", nil)
+ w.putBox(t, rdBox("annie", "", "203.0.113.10", rdIE))
+ w.putBox(t, rdBox("betty", "uk", "203.0.113.20", rdUK))
+ return w
+}
+
+// putBox writes b's heartbeat and, unless NoEdges, its edges file.
+func (w *regionalWorld) putBox(t *testing.T, b regionalBox) {
+ t.Helper()
+ hb := status.Box{GeneratedAt: b.At, Label: b.Label, Region: "eu-west-1"}
+ if !b.NoMetrics {
+ hb.Metrics = &status.BoxMetrics{Release: b.Release, AliasesRead: b.AliasesRead, Aliases: b.Aliases}
+ }
+ if err := status.WriteBox(context.Background(), w.fx.rel, hb); err != nil {
+ t.Fatal(err)
+ }
+ if b.NoEdges {
+ return
+ }
+ body, err := json.Marshal(map[string]any{"v": 1, "box": b.Label, "eip": b.EIP, "region": "eu-west-1",
+ "placement": b.Placement, "hosts": b.Hosts})
+ if err != nil {
+ t.Fatal(err)
+ }
+ putFixtureObject(t, w.fx.rel, edgesfile.Key(b.Label), body)
+}
+
+// putRecord writes an instance record of acct/app at host in region, after
+// mod edits it.
+func (w *regionalWorld) putRecord(t *testing.T, acct, app, host, region string, mod func(*provision.Record)) {
+ t.Helper()
+ rec := provision.Record{Schema: 1, Host: host, Slug: strings.SplitN(host, ".", 2)[0], App: app, Account: acct,
+ Region: region, Channel: "stable", CreatedAt: time.Now().UTC(), CreatedBy: "paul@keymail.dev"}
+ if mod != nil {
+ mod(&rec)
+ }
+ if err := provision.CreateRecord(context.Background(), w.fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// putAccount writes another account's manifest, so the record walk knows
+// it, and returns its sqid.
+func (w *regionalWorld) putAccount(t *testing.T, id int64) string {
+ t.Helper()
+ sqid := domains.Sqid(id)
+ body, err := json.Marshal(domains.AccountManifest{ID: id, Sqid: sqid, Name: "other", CreatedAt: time.Now().UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ putFixtureObject(t, w.fx.rel, domains.AccountManifestKey(sqid), body)
+ return sqid
+}
+
+// rdSet is a PUT body binding each "region=host" pair, in order.
+func rdSet(pairs ...string) placementsPutBody {
+ var b placementsPutBody
+ for _, p := range pairs {
+ region, host, _ := strings.Cut(p, "=")
+ b.Placements = append(b.Placements, placementIn{Region: region, Host: host})
+ }
+ return b
+}
+
+// rdBoth is the world's whole set: ie and uk.
+func rdBoth() placementsPutBody { return rdSet("ie="+rdIE, "uk="+rdUK) }
+
+// put sends the placements PUT for host with body as the world's owner.
+func (w *regionalWorld) put(t *testing.T, host string, body placementsPutBody) (int, string) {
+ t.Helper()
+ raw, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ code, _, out := rawReq(t, http.MethodPut, placementsURL(w.fx, "shop", host), w.token, string(raw))
+ return code, out
+}
+
+// mustPut is put, failing unless the answer is 200.
+func (w *regionalWorld) mustPut(t *testing.T, host string, body placementsPutBody) {
+ t.Helper()
+ if code, out := w.put(t, host, body); code != http.StatusOK {
+ t.Fatalf("PUT %s = %d %s, want 200", host, code, out)
+ }
+}
+
+// claim is host's stored claim, failing if there is none.
+func (w *regionalWorld) claim(t *testing.T, host string) *domains.Claim {
+ t.Helper()
+ c, err := domains.GetClaim(context.Background(), w.fx.rel, host)
+ if err != nil {
+ t.Fatalf("claim %s: %v", host, err)
+ }
+ return c
+}
+
+// requireNoClaim fails unless host has no claim object at all.
+func (w *regionalWorld) requireNoClaim(t *testing.T, host, what string) {
+ t.Helper()
+ if _, _, err := w.fx.rel.Get(context.Background(), domains.ClaimKey(host)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("%s: claim %s: %v, want none written", what, host, err)
+ }
+}
+
+// requireRefusal fails unless code and out are status and the JSON error msg.
+func requireRefusal(t *testing.T, what string, code int, out string, status int, msg string) {
+ t.Helper()
+ var e struct {
+ Error string `json:"error"`
+ }
+ _ = json.Unmarshal([]byte(out), &e)
+ if code != status || e.Error != msg {
+ t.Fatalf("%s = %d %s, want %d %q", what, code, out, status, msg)
+ }
+}
+
+// rdStore wraps the console's store: it records Gets and Puts, and can fail
+// a Get or a List by key, or run a hook before a Put.
+type rdStore struct {
+ release.Store
+ mu sync.Mutex
+ gets []string
+ puts []string
+ failGet map[string]bool
+ failList map[string]bool
+ beforePut func(key string)
+}
+
+func newRDStore(s release.Store) *rdStore {
+ return &rdStore{Store: s, failGet: map[string]bool{}, failList: map[string]bool{}}
+}
+
+func (s *rdStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.mu.Lock()
+ s.gets = append(s.gets, key)
+ fail := s.failGet[key]
+ s.mu.Unlock()
+ if fail {
+ return nil, "", errors.New("rdStore: get refused")
+ }
+ return s.Store.Get(ctx, key)
+}
+
+func (s *rdStore) List(ctx context.Context, prefix string) ([]string, error) {
+ s.mu.Lock()
+ fail := s.failList[prefix]
+ s.mu.Unlock()
+ if fail {
+ return nil, errors.New("rdStore: list refused")
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func (s *rdStore) Put(ctx context.Context, key string, body []byte, etag string) (string, error) {
+ s.mu.Lock()
+ s.puts = append(s.puts, key)
+ hook := s.beforePut
+ s.mu.Unlock()
+ if hook != nil {
+ hook(key)
+ }
+ return s.Store.Put(ctx, key, body, etag)
+}
+
+func (s *rdStore) got(key string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return slices.Contains(s.gets, key)
+}
+
+func (s *rdStore) put(key string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return slices.Contains(s.puts, key)
+}
+
+// wrap puts an rdStore in front of the world's console.
+func (w *regionalWorld) wrap() *rdStore {
+ st := newRDStore(w.fx.rel)
+ w.fx.srv.cfg.Releases = st
+ return st
+}
+
+// The happy path the other tests depart from: a PUT creates a schema-2
+// claim, Route the first binding in body order, and answers the GET body.
+func TestPlacementsPutCreates(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-create")
+ code, out := w.put(t, rdHost, rdSet("uk="+rdUK, "ie="+rdIE))
+ if code != http.StatusOK {
+ t.Fatalf("PUT = %d %s, want 200", code, out)
+ }
+ var got placementsResp
+ if err := json.Unmarshal([]byte(out), &got); err != nil || got.Host != rdHost || got.Route != rdUK {
+ t.Fatalf("answer = %s (%v), want the GET body for %s, route %s", out, err, rdHost, rdUK)
+ }
+ c := w.claim(t, rdHost)
+ want := []domains.Placement{{Region: "", Host: rdIE}, {Region: "uk", Host: rdUK}}
+ if c.Schema != 2 || !c.Regional() || !slices.Equal(c.Placements, want) || c.Route != rdUK ||
+ c.Account != w.fx.sqid || c.App != "shop" || c.CreatedBy == "" || c.CreatedAt == "" ||
+ c.Wildcard || c.Catchall || c.Pending {
+ t.Fatalf("claim = %+v, want schema 2, %v, route %s, no capabilities", c, want, rdUK)
+ }
+ if got := serial(t, w.fx); got != 1 {
+ t.Fatalf("serial = %d, want 1", got)
+ }
+ if got := eventsOf(t, w.fx.st, "shop", "domain-placements"); got != 1 {
+ t.Fatalf("domain-placements rows = %d, want 1", got)
+ }
+}
+
+// TestPlacementsPutTargetRefusals (W5): a binding must name an instance
+// record of this app in that region that can carry a regional name. Every
+// way it does not answers RD-20, and a host nobody holds answers the same
+// bytes as another account's or another app's instance.
+func TestPlacementsPutTargetRefusals(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-targets")
+ const de = "shop-de.example.net"
+ unknownCode, unknown := w.put(t, rdHost, rdSet("ie="+rdIE, "de="+de))
+ requireRefusal(t, "an unknown host", unknownCode, unknown, http.StatusBadRequest, placementsNotInstanceMsg(de, "de"))
+ other := w.putAccount(t, 77)
+ w.putRecord(t, other, "blog", de, "de", nil)
+ if code, out := w.put(t, rdHost, rdSet("ie="+rdIE, "de="+de)); code != unknownCode || out != unknown {
+ t.Fatalf("another account's instance = %d %s, want the unknown host's %d %s", code, out, unknownCode, unknown)
+ }
+ w.putRecord(t, w.fx.sqid, "blog", de, "de", nil)
+ if code, out := w.put(t, rdHost, rdSet("ie="+rdIE, "de="+de)); code != unknownCode || out != unknown {
+ t.Fatalf("another app's instance = %d %s, want the unknown host's %d %s", code, out, unknownCode, unknown)
+ }
+
+ w.putRecord(t, w.fx.sqid, "shop", "shop-r.example.net", "uk", func(r *provision.Record) { r.Role = "replica" })
+ 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" })
+ 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 sidecar", "uk", "bot.sidecar.internal"},
+ {"not a hostname", "uk", "not a host"},
+ } {
+ code, out := w.put(t, rdHost, rdSet(c.region+"="+c.host))
+ requireRefusal(t, c.what, code, out, http.StatusBadRequest, placementsNotInstanceMsg(c.host, c.region))
+ }
+
+ w.fx.srv.cfg.DenyDomains = []string{"denied.test"}
+ code, out := w.put(t, "shop.denied.test", rdBoth())
+ requireRefusal(t, "a platform hostname", code, out, http.StatusBadRequest, "that hostname is platform-managed")
+ w.requireNoClaim(t, "shop.denied.test", "a platform hostname")
+
+ // A service credential never reaches the handler: the door is closed to
+ // every role (cliRoute's gate, before apiPerson's inner wall).
+ svc := serviceToken(t, w.fx.st, OpsAccountID, "ci", "shop", svcrole.Publish)
+ raw, _ := json.Marshal(rdBoth())
+ code, _, out = rawReq(t, http.MethodPut, placementsURL(w.fx, "shop", rdHost), svc, string(raw))
+ if code != http.StatusForbidden || !strings.Contains(out, "closed to service credentials") {
+ t.Fatalf("a service credential = %d %s, want the closed-door 403", code, out)
+ }
+
+ // The shelved host-claim mode: RD-25.
+ w.fx.srv.cfg.HostClaim = true
+ code, out = w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "a host-claim console", code, out, http.StatusConflict, placementsHostClaimMsg)
+ w.fx.srv.cfg.HostClaim = false
+
+ w.requireNoClaim(t, rdHost, "every refusal")
+ if got := serial(t, w.fx); got != 0 {
+ t.Fatalf("serial = %d after refusals only, want 0", got)
+ }
+}
+
+// TestPlacementsPutClaimStates (W5): the claim rule. No claim, the caller's
+// own pending claim and another owner's reservation this caller may take
+// are created fresh; the caller's own verified ordinary claim is RD-21;
+// another owner's verified claim is the neutral 409; and with proof on and
+// no TXT record nothing is written and the answer carries the record.
+func TestPlacementsPutClaimStates(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-states")
+ ctx := context.Background()
+
+ w.mustPut(t, rdHost, rdBoth())
+ if raw, _, err := w.fx.rel.Get(ctx, domains.ClaimKey(rdHost)); err != nil || strings.Contains(string(raw), "pending") {
+ t.Fatalf("created claim %s (%v): want no pending field", raw, err)
+ }
+
+ // The caller's own pending claim, carrying every field a claim can.
+ const pend = "pend.example.com"
+ pendBody, _ := json.Marshal(domains.Claim{Schema: 1, Host: pend, Account: w.fx.sqid, App: "shop",
+ Route: "elsewhere.example.net", CreatedAt: "2026-01-01T00:00:00Z", CreatedBy: "old@example.com",
+ Wildcard: true, Catchall: true, Paths: map[string]string{"blog": "blog.example.net"},
+ Pending: true, PendingUntil: time.Now().Add(time.Hour).UTC().Format(time.RFC3339)})
+ putFixtureObject(t, w.fx.rel, domains.ClaimKey(pend), pendBody)
+ w.mustPut(t, pend, rdBoth())
+ c := w.claim(t, pend)
+ if c.Pending || c.PendingUntil != "" || c.Route != rdIE || c.CreatedAt == "2026-01-01T00:00:00Z" ||
+ c.CreatedBy == "old@example.com" || c.Wildcard || c.Catchall || len(c.Paths) != 0 || !c.Regional() {
+ t.Fatalf("replaced pending claim = %+v, want a fresh regional body", c)
+ }
+
+ // The caller's own verified ordinary claims: an alias and a first route.
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", "alias.example.com", rdIE)
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", "first.example.com", "")
+ for _, h := range []string{"alias.example.com", "first.example.com"} {
+ raw, etag := regionalClaimBytes(t, w.fx.rel, h)
+ code, out := w.put(t, h, rdBoth())
+ requireRefusal(t, "own verified "+h, code, out, http.StatusConflict, placementsOrdinaryMsg(h))
+ requireClaimUnchanged(t, w.fx.rel, h, raw, etag, "own verified "+h)
+ }
+
+ // Another owner's verified claim.
+ attachShopClaim(t, w.fx, "zzz", "blog", "theirs.example.com", "theirs.example.net")
+ raw, etag := regionalClaimBytes(t, w.fx.rel, "theirs.example.com")
+ code, out := w.put(t, "theirs.example.com", rdBoth())
+ requireRefusal(t, "another owner's verified claim", code, out, http.StatusConflict, hostUnavailableMsg)
+ requireClaimUnchanged(t, w.fx.rel, "theirs.example.com", raw, etag, "another owner's verified claim")
+
+ // Proof on, no TXT: 409 with the verify record, nothing written.
+ w.fx.srv.cfg.DomainProof = true
+ lookups := 0
+ w.fx.srv.lookupTXT = noTXT(&lookups)
+ const proof = "proof.example.com"
+ code, out = w.put(t, proof, rdBoth())
+ var ans proofAttachResp
+ if err := json.Unmarshal([]byte(out), &ans); err != nil || code != http.StatusConflict ||
+ ans.Verified == nil || *ans.Verified || ans.Verify.Type != "TXT" || ans.Verify.Name != domains.ChallengeName(proof) ||
+ ans.Verify.Value != domains.ChallengeToken(w.fx.srv.challengeDeployment(), w.fx.sqid, proof) {
+ t.Fatalf("unproven create = %d %s, want 409 carrying the verify record", code, out)
+ }
+ w.requireNoClaim(t, proof, "an unproven create")
+
+ // Another owner's live reservation: unproven, the neutral 409 (one TXT
+ // lookup); proven, taken.
+ const theirsPending = "reserved.example.com"
+ if _, _, _, err := domains.AttachClaimProven(ctx, w.fx.rel, domains.Claim{Host: theirsPending, Account: "zzz",
+ App: "blog", Route: "theirs.example.net"}, time.Now(), func() bool { return false }); err != nil {
+ t.Fatal(err)
+ }
+ raw, etag = regionalClaimBytes(t, w.fx.rel, theirsPending)
+ lookups = 0
+ code, out = w.put(t, theirsPending, rdBoth())
+ requireRefusal(t, "another owner's live reservation, unproven", code, out, http.StatusConflict, hostUnavailableMsg)
+ requireClaimUnchanged(t, w.fx.rel, theirsPending, raw, etag, "another owner's live reservation")
+ if lookups != 1 {
+ t.Fatalf("TXT lookups = %d, want 1", lookups)
+ }
+ w.fx.srv.lookupTXT = txtFor(w.fx.srv, w.fx.sqid, theirsPending)
+ w.mustPut(t, theirsPending, rdBoth())
+ if c := w.claim(t, theirsPending); c.Account != w.fx.sqid || !c.Regional() {
+ t.Fatalf("taken reservation = %+v, want the caller's regional claim", c)
+ }
+}
+
+// TestPlacementsPutEvidenceRefusals (W5): the never-served and collision
+// evidence, with no owner exemption, and the incomplete-evidence 503s.
+func TestPlacementsPutEvidenceRefusals(t *testing.T) {
+ t.Run("a real route at the host or its star, on an update", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-ev-route")
+ w.mustPut(t, rdHost, rdBoth())
+ raw, etag := regionalClaimBytes(t, w.fx.rel, rdHost)
+ for _, key := range []string{rdHost, "*." + rdHost} {
+ w.putBox(t, rdBox("betty", "uk", "203.0.113.20", rdUK, key))
+ code, out := w.put(t, rdHost, rdSet("ie="+rdIE))
+ requireRefusal(t, "betty publishing "+key, code, out, http.StatusConflict, hostUnavailableMsg)
+ requireClaimUnchanged(t, w.fx.rel, rdHost, raw, etag, "betty publishing "+key)
+ }
+ // An alias entry under home refuses too: the name has served.
+ b := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ b.Hosts[rdHost] = edgesfile.Host{Role: edgesfile.RoleHome, Alias: true}
+ w.putBox(t, b)
+ code, out := w.put(t, rdHost, rdSet("ie="+rdIE))
+ requireRefusal(t, "an alias entry", code, out, http.StatusConflict, hostUnavailableMsg)
+ requireClaimUnchanged(t, w.fx.rel, rdHost, raw, etag, "an alias entry")
+ })
+ t.Run("alias rows in a heartbeat", func(t *testing.T) {
+ for _, key := range []string{rdHost, "*." + rdHost, "*.example.com"} {
+ w := newRegionalWorld(t, "code-rdput-ev-rows")
+ b := rdBox("annie", "", "203.0.113.10", rdIE)
+ b.Aliases = map[string]status.AliasReading{key: {Route: rdIE}}
+ w.putBox(t, b)
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "a heartbeat listing "+key, code, out, http.StatusConflict, hostUnavailableMsg)
+ w.requireNoClaim(t, rdHost, "a heartbeat listing "+key)
+ }
+ })
+ t.Run("a pending operation on the host", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-ev-pending")
+ if err := w.fx.st.BeginAllocation(Allocation{OpID: "op-a", Account: w.fx.sqid, App: "shop", Host: rdHost,
+ Incarnation: 1, Body: []byte(`{"app":"shop"}`), PredecessorETag: `"p"`, StaleETag: `"s"`,
+ AppLifetime: "00112233aabbccdd"}); err != nil {
+ t.Fatal(err)
+ }
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "a pending allocation", code, out, http.StatusConflict, hostUnavailableMsg)
+ w.requireNoClaim(t, rdHost, "a pending allocation")
+ })
+ t.Run("a pending-operation read that fails", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-ev-pendread")
+ if _, err := w.fx.st.db.Exec(`ALTER TABLE record_migrations RENAME TO record_migrations_gone`); err != nil {
+ t.Fatal(err)
+ }
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "a failed pending read", code, out, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ w.requireNoClaim(t, rdHost, "a failed pending read")
+ })
+ for _, c := range []struct {
+ what string
+ spoil func(t *testing.T, w *regionalWorld)
+ }{
+ {"an edges file that does not read", func(t *testing.T, w *regionalWorld) {
+ w.wrap().failGet[edgesfile.Key("betty")] = true
+ }},
+ {"a heartbeat that does not read", func(t *testing.T, w *regionalWorld) {
+ w.wrap().failGet["status/boxes/betty.json"] = true
+ }},
+ {"a fresh heartbeat with no edges file", func(t *testing.T, w *regionalWorld) {
+ b := rdBox("carol", "uk", "203.0.113.30")
+ b.NoEdges = true
+ w.putBox(t, b)
+ }},
+ {"a fresh heartbeat with no metrics", func(t *testing.T, w *regionalWorld) {
+ b := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ b.NoMetrics = true
+ w.putBox(t, b)
+ }},
+ {"no fresh box", func(t *testing.T, w *regionalWorld) {
+ for _, label := range []string{"annie", "betty"} {
+ b := rdBox(label, "", "203.0.113.10")
+ b.At = time.Now().Add(-time.Hour)
+ w.putBox(t, b)
+ }
+ }},
+ } {
+ t.Run(c.what, func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-ev-503")
+ c.spoil(t, w)
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, c.what, code, out, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ w.requireNoClaim(t, rdHost, c.what)
+ })
+ }
+}
+
+// TestPlacementsPutOverlapRefusals (W5): spec §6.7's table for
+// shop.example.com, whose parent example.com can hold a claim.
+func TestPlacementsPutOverlapRefusals(t *testing.T) {
+ putRaw := func(t *testing.T, w *regionalWorld, host string, c domains.Claim) {
+ body, err := json.Marshal(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ putFixtureObject(t, w.fx.rel, domains.ClaimKey(host), body)
+ }
+ for _, c := range []struct {
+ what string
+ status int
+ setup func(t *testing.T, w *regionalWorld)
+ }{
+ {"a parent claim with catchall", http.StatusConflict, func(t *testing.T, w *regionalWorld) {
+ attachShopClaim(t, w.fx, "zzz", "blog", "example.com", "theirs.example.net")
+ if _, err := domains.SetClaimCapabilities(context.Background(), w.fx.rel, "example.com", "zzz", "blog", true, true); err != nil {
+ t.Fatal(err)
+ }
+ }},
+ {"a parent claim that does not parse", http.StatusConflict, func(t *testing.T, w *regionalWorld) {
+ putFixtureObject(t, w.fx.rel, domains.ClaimKey("example.com"), []byte("not json"))
+ }},
+ {"an instance catch-all on the parent", http.StatusConflict, func(t *testing.T, w *regionalWorld) {
+ putRaw(t, w, "*.example.com", domains.Claim{Schema: 1, Host: "*.example.com", Account: "zzz", App: "blog", Instances: true})
+ }},
+ {"an instance catch-all on the host", http.StatusConflict, func(t *testing.T, w *regionalWorld) {
+ putRaw(t, w, "*."+rdHost, domains.Claim{Schema: 1, Host: "*." + rdHost, Account: w.fx.sqid, App: "shop", Instances: true})
+ }},
+ {"a file publishing *.<parent> as home", http.StatusConflict, func(t *testing.T, w *regionalWorld) {
+ w.putBox(t, rdBox("betty", "uk", "203.0.113.20", rdUK, "*.example.com"))
+ }},
+ {"a heartbeat listing *.<parent>", http.StatusConflict, func(t *testing.T, w *regionalWorld) {
+ b := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ b.Aliases = map[string]status.AliasReading{"*.example.com": {Route: "x.example.net"}}
+ w.putBox(t, b)
+ }},
+ {"an unreadable parent claim", http.StatusServiceUnavailable, func(t *testing.T, w *regionalWorld) {
+ attachShopClaim(t, w.fx, "zzz", "blog", "example.com", "theirs.example.net")
+ w.wrap().failGet[domains.ClaimKey("example.com")] = true
+ }},
+ } {
+ t.Run(c.what, func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-overlap")
+ c.setup(t, w)
+ msg := hostUnavailableMsg
+ if c.status == http.StatusServiceUnavailable {
+ msg = placementsUnreadableMsg
+ }
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, c.what, code, out, c.status, msg)
+ w.requireNoClaim(t, rdHost, c.what)
+ })
+ }
+ // A parent claim without catchall is no overlap.
+ w := newRegionalWorld(t, "code-rdput-overlap-ok")
+ attachShopClaim(t, w.fx, "zzz", "blog", "example.com", "theirs.example.net")
+ w.mustPut(t, rdHost, rdBoth())
+}
+
+// TestPlacementsPutDeclaredOwnership (W5): a committed, unprovisioned record
+// at the host (no route, nothing in any file) refuses, whoever holds it,
+// and a walk that cannot read an account manifest refuses with 503.
+func TestPlacementsPutDeclaredOwnership(t *testing.T) {
+ t.Run("another account's record", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-decl-other")
+ other := w.putAccount(t, 77)
+ w.putRecord(t, other, "blog", rdHost, "", nil)
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "another account's record", code, out, http.StatusConflict, hostUnavailableMsg)
+ w.requireNoClaim(t, rdHost, "another account's record")
+ })
+ t.Run("the caller's own record", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-decl-own")
+ w.putRecord(t, w.fx.sqid, "shop", rdHost, "", nil)
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "the caller's own record", code, out, http.StatusConflict, hostUnavailableMsg)
+ w.requireNoClaim(t, rdHost, "the caller's own record")
+ })
+ t.Run("a manifest that does not read", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-decl-503")
+ other := w.putAccount(t, 77)
+ w.wrap().failGet[domains.AccountManifestKey(other)] = true
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "an unreadable manifest", code, out, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ w.requireNoClaim(t, rdHost, "an unreadable manifest")
+ })
+}
+
+// TestPlacementsPutTwoLabelApex (W5): example.com's parent com can hold no
+// claim, so neither GET at com is made; the GET of *.example.com is, and
+// anything there refuses.
+func TestPlacementsPutTwoLabelApex(t *testing.T) {
+ const apex = "example.com"
+ w := newRegionalWorld(t, "code-rdput-apex")
+ st := w.wrap()
+ w.mustPut(t, apex, rdBoth())
+ if !st.got(domains.ClaimKey("*." + apex)) {
+ t.Fatalf("gets = %v, want domains/*.%s.json read", st.gets, apex)
+ }
+ for _, k := range []string{domains.ClaimKey("com"), domains.ClaimKey("*.com")} {
+ if st.got(k) {
+ t.Fatalf("gets = %v, want no read of %s", st.gets, k)
+ }
+ }
+
+ pending := domains.Claim{Schema: 1, Host: "*." + apex, Account: "zzz", App: "blog", Instances: true,
+ Pending: true, PendingUntil: time.Now().Add(time.Hour).UTC().Format(time.RFC3339)}
+ pendingBody, _ := json.Marshal(pending)
+ verified := pending
+ verified.Pending, verified.PendingUntil = false, ""
+ verifiedBody, _ := json.Marshal(verified)
+ for _, c := range []struct {
+ what string
+ body []byte
+ }{{"a verified catch-all", verifiedBody}, {"a pending catch-all", pendingBody}, {"an object that does not parse", []byte("{")}} {
+ w := newRegionalWorld(t, "code-rdput-apex-409")
+ putFixtureObject(t, w.fx.rel, domains.ClaimKey("*."+apex), c.body)
+ code, out := w.put(t, apex, rdBoth())
+ requireRefusal(t, c.what, code, out, http.StatusConflict, hostUnavailableMsg)
+ w.requireNoClaim(t, apex, c.what)
+ }
+ w = newRegionalWorld(t, "code-rdput-apex-503")
+ w.wrap().failGet[domains.ClaimKey("*."+apex)] = true
+ code, out := w.put(t, apex, rdBoth())
+ requireRefusal(t, "a failed GET at *."+apex, code, out, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ w.requireNoClaim(t, apex, "a failed GET")
+}
+
+// TestPlacementsPutCapabilitiesAtCreation (W5, ruling 6): the body's
+// wildcard and catchall are written on create, through the attach door's
+// enabling gate, and any later change is refused.
+func TestPlacementsPutCapabilitiesAtCreation(t *testing.T) {
+ const zone = "acme.example.org"
+ delegated := func(w *regionalWorld) {
+ w.fx.srv.delegationZone = zone
+ w.fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
+ return name + "." + zone + ".", nil
+ }
+ }
+ both := rdBoth()
+ both.Wildcard, both.Catchall = boolp(true), boolp(true)
+
+ w := newRegionalWorld(t, "code-rdput-caps")
+ delegated(w)
+ w.mustPut(t, rdHost, both)
+ if c := w.claim(t, rdHost); !c.Wildcard || !c.Catchall {
+ t.Fatalf("claim = %+v, want both capabilities", c)
+ }
+ w.mustPut(t, "plain.example.com", rdBoth())
+ if c := w.claim(t, "plain.example.com"); c.Wildcard || c.Catchall {
+ t.Fatalf("claim = %+v, want neither capability", c)
+ }
+
+ // Fixed after creation: a different value is RD-26, the same is a no-op.
+ raw, etag := regionalClaimBytes(t, w.fx.rel, "plain.example.com")
+ for _, body := range []placementsPutBody{
+ {Placements: rdBoth().Placements, Wildcard: boolp(true)},
+ {Placements: rdBoth().Placements, Wildcard: boolp(true), Catchall: boolp(true)},
+ } {
+ code, out := w.put(t, "plain.example.com", body)
+ requireRefusal(t, "a capability change", code, out, http.StatusConflict, domains.ErrRegionalClaim.Error())
+ requireClaimUnchanged(t, w.fx.rel, "plain.example.com", raw, etag, "a capability change")
+ }
+ same := rdBoth()
+ same.Wildcard, same.Catchall = boolp(false), boolp(false)
+ w.mustPut(t, "plain.example.com", same)
+ requireClaimUnchanged(t, w.fx.rel, "plain.example.com", raw, etag, "the same capabilities")
+ off := rdBoth()
+ off.Wildcard = boolp(false)
+ code, out := w.put(t, rdHost, off)
+ requireRefusal(t, "turning wildcard off", code, out, http.StatusConflict, domains.ErrRegionalClaim.Error())
+
+ // catchall alone.
+ alone := rdBoth()
+ alone.Catchall = boolp(true)
+ code, out = w.put(t, "alone.example.com", alone)
+ requireRefusal(t, "catchall alone", code, out, http.StatusUnprocessableEntity, domains.ErrCatchallNeedsWildcard.Error())
+ w.requireNoClaim(t, "alone.example.com", "catchall alone")
+
+ // The enabling gate: no zone, then no delegating CNAME.
+ wild := rdBoth()
+ wild.Wildcard = boolp(true)
+ w.fx.srv.delegationZone = ""
+ code, out = w.put(t, "wild.example.com", wild)
+ requireRefusal(t, "no delegation zone", code, out, http.StatusUnprocessableEntity, "deployment has no delegation zone configured")
+ w.fx.srv.delegationZone = zone
+ w.fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("not found") }
+ code, out = w.put(t, "wild.example.com", wild)
+ requireRefusal(t, "no delegating CNAME", code, out, http.StatusUnprocessableEntity,
+ "create CNAME _acme-challenge.wild.example.com -> _acme-challenge.wild.example.com."+zone+", then retry")
+ w.requireNoClaim(t, "wild.example.com", "the enabling gate")
+ delegated(w)
+
+ // The descendant scan on create with catchall.
+ const parent = "cat.example.com"
+ if err := writeRegionalClaim(w.fx.rel, "alice."+parent, "zzz", "blog", "alice-ie.example.net", false, false); err != nil {
+ t.Fatal(err)
+ }
+ code, out = w.put(t, parent, both)
+ requireRefusal(t, "a regional claim under it", code, out, http.StatusConflict, hostUnavailableMsg)
+ w.requireNoClaim(t, parent, "a regional claim under it")
+ // Without catchall the scan is not run.
+ w.mustPut(t, parent, rdBoth())
+
+ const parent2 = "dog.example.com"
+ putFixtureObject(t, w.fx.rel, domains.ClaimKey("bob."+parent2), []byte("not json"))
+ code, out = w.put(t, parent2, both)
+ requireRefusal(t, "an unread claim under it", code, out, http.StatusConflict, hostUnavailableMsg)
+ w.requireNoClaim(t, parent2, "an unread claim under it")
+
+ w.wrap().failList[domains.ClaimsPrefix] = true
+ code, out = w.put(t, "eel.example.com", both)
+ requireRefusal(t, "a failed claim listing", code, out, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ w.requireNoClaim(t, "eel.example.com", "a failed claim listing")
+}
+
+// TestPlacementsPutUnchangedWritesNothing (W5): the same set again writes
+// nothing, announces nothing and audits nothing; an update keeps Route
+// while it is still bound; and a claim that changes between the read and
+// the write is RD-24.
+func TestPlacementsPutUnchangedWritesNothing(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-same")
+ w.mustPut(t, rdHost, rdBoth())
+ st := w.wrap()
+ w.mustPut(t, rdHost, rdBoth())
+ w.mustPut(t, rdHost, rdSet("uk="+rdUK, "ie="+rdIE))
+ if st.put(domains.ClaimKey(rdHost)) {
+ t.Fatalf("puts = %v, want no write of the claim", st.puts)
+ }
+ if got := serial(t, w.fx); got != 1 {
+ t.Fatalf("serial = %d, want 1", got)
+ }
+ if got := eventsOf(t, w.fx.st, "shop", "domain-placements"); got != 1 {
+ t.Fatalf("domain-placements rows = %d, want 1", got)
+ }
+
+ // Route: kept while bound, otherwise the first region in code order.
+ w.mustPut(t, rdHost, rdSet("uk="+rdUK))
+ if c := w.claim(t, rdHost); c.Route != rdUK {
+ t.Fatalf("route = %s, want %s once %s is unbound", c.Route, rdUK, rdIE)
+ }
+ w.mustPut(t, rdHost, rdBoth())
+ if c := w.claim(t, rdHost); c.Route != rdUK || len(c.Placements) != 2 {
+ t.Fatalf("claim = %+v, want route %s kept", c, rdUK)
+ }
+ if got := serial(t, w.fx); got != 3 {
+ t.Fatalf("serial = %d, want 3", got)
+ }
+
+ // A write racing in between this request's read and its write.
+ st.beforePut = func(key string) {
+ if key != domains.ClaimKey(rdHost) {
+ return
+ }
+ st.beforePut = nil
+ cur, etag, err := domains.GetClaimETag(context.Background(), w.fx.rel, rdHost)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ next := *cur
+ next.CreatedBy = "racer@example.com"
+ if _, err := domains.SetClaimPlacements(context.Background(), w.fx.rel, next, cur, etag); err != nil {
+ t.Error(err)
+ }
+ }
+ code, out := w.put(t, rdHost, rdSet("ie="+rdIE))
+ requireRefusal(t, "a racing write", code, out, http.StatusConflict, placementsChangedMsg)
+ if c := w.claim(t, rdHost); c.CreatedBy != "racer@example.com" || len(c.Placements) != 2 {
+ t.Fatalf("claim = %+v, want the racing write standing", c)
+ }
+}
+
+// TestPlacementsRefusesWithABoxBelowTheFloor (W7 barrier).
+func TestPlacementsRefusesWithABoxBelowTheFloor(t *testing.T) {
+ floor := rdFloor()
+ t.Run("a fresh box below the floor", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-floor-old")
+ b := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ b.Release, b.AliasesRead = "v0.30.2", false // an old binary never sends aliases_read
+ w.putBox(t, b)
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "betty at v0.30.2", code, out, http.StatusConflict, placementsBelowFloorMsg("betty", "v0.30.2", floor))
+ w.requireNoClaim(t, rdHost, "a box below the floor")
+ })
+ t.Run("the first by label", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-floor-first")
+ for _, label := range []string{"betty", "annie"} {
+ b := rdBox(label, "", "203.0.113.10", rdIE)
+ b.Release = "v0.29." + label[:1]
+ w.putBox(t, b)
+ }
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "two old boxes", code, out, http.StatusConflict, placementsBelowFloorMsg("annie", "v0.29.a", floor))
+ })
+ t.Run("a missing release", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-floor-missing")
+ b := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ b.Release = ""
+ w.putBox(t, b)
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "a missing release", code, out, http.StatusConflict, placementsNoReleaseMsg("betty", floor))
+ w.requireNoClaim(t, rdHost, "a missing release")
+ })
+ t.Run("incomplete heartbeats", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-floor-incomplete")
+ w.wrap().failGet["status/boxes/annie.json"] = true
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "incomplete heartbeats", code, out, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ })
+ t.Run("aliases_read absent at the floor", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-floor-aliases")
+ b := rdBox("betty", "uk", "203.0.113.20", rdUK)
+ b.AliasesRead = false
+ w.putBox(t, b)
+ code, out := w.put(t, rdHost, rdBoth())
+ requireRefusal(t, "aliases_read absent", code, out, http.StatusServiceUnavailable, placementsUnreadableMsg)
+ w.requireNoClaim(t, rdHost, "aliases_read absent")
+ })
+ t.Run("a stale old box is ignored", func(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-floor-stale")
+ b := rdBox("carol", "uk", "203.0.113.30", rdUK)
+ b.Release, b.AliasesRead, b.At = "v0.30.2", false, time.Now().Add(-time.Hour)
+ w.putBox(t, b)
+ w.mustPut(t, rdHost, rdBoth())
+ })
+}
+
+// TestPlacementsPutNormalisesInput (Review Focus 2): hosts and regions are
+// lower-cased and trimmed, the home region's name is stored as "", and an
+// empty or unknown region is RD-20.
+func TestPlacementsPutNormalisesInput(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-norm")
+ w.mustPut(t, "Shop.Example.COM", rdSet(" UK =SHOP-UK.Example.NET", "ie=Shop-IE.example.net."))
+ c := w.claim(t, rdHost)
+ want := []domains.Placement{{Region: "", Host: rdIE}, {Region: "uk", Host: rdUK}}
+ if !slices.Equal(c.Placements, want) || c.Host != rdHost || c.Route != rdUK {
+ t.Fatalf("claim = %+v, want %v on %s", c, want, rdHost)
+ }
+ code, out := w.put(t, "other.example.com", rdSet("="+rdIE))
+ requireRefusal(t, "an empty region", code, out, http.StatusBadRequest, placementsNotInstanceMsg(rdIE, ""))
+ code, out = w.put(t, "other.example.com", rdSet("de="+rdIE))
+ requireRefusal(t, "an unknown region", code, out, http.StatusBadRequest, placementsNotInstanceMsg(rdIE, "de"))
+ w.requireNoClaim(t, "other.example.com", "a refused region")
+}
+
+// TestPlacementsPutRefusesDuplicates (Review Focus 3): a region or an
+// instance named twice, and a set of none or more than eight, write nothing.
+func TestPlacementsPutRefusesDuplicates(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-dup")
+ nine := make([]string, 9)
+ for i := range nine {
+ nine[i] = "r" + string(rune('a'+i)) + "=" + rdIE
+ }
+ for _, c := range []struct {
+ what string
+ body placementsPutBody
+ msg string
+ }{
+ {"a region twice", rdSet("uk="+rdUK, "UK="+rdIE), placementsRegionTwiceMsg("UK")},
+ {"the home twice", rdSet("ie="+rdIE, "ie="+rdUK), placementsRegionTwiceMsg("ie")},
+ {"an instance twice", rdSet("ie="+rdIE, "uk=SHOP-IE.example.net"), placementsHostTwiceMsg(rdIE)},
+ {"no placements", rdSet(), placementsCountMsg},
+ {"nine placements", rdSet(nine...), placementsCountMsg},
+ } {
+ code, out := w.put(t, rdHost, c.body)
+ requireRefusal(t, c.what, code, out, http.StatusBadRequest, c.msg)
+ }
+ w.requireNoClaim(t, rdHost, "duplicates")
+}
+
+// The PUT holds the app lock, then the hostname exclusion, for the host it
+// writes: instance create's regional recheck runs under that exclusion.
+func TestPlacementsPutHoldsTheHostExclusion(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-locks")
+ var (
+ mu sync.Mutex
+ events []string
+ )
+ hook := func(kind, key, event string) {
+ if event == lockHeld && (key == rdHost || key == w.fx.sqid+"/shop") {
+ mu.Lock()
+ events = append(events, kind+" "+key)
+ mu.Unlock()
+ }
+ }
+ lifetimeLockHook.Store(&hook)
+ t.Cleanup(func() { lifetimeLockHook.Store(nil) })
+ w.mustPut(t, rdHost, rdBoth())
+ mu.Lock()
+ got := slices.Clone(events)
+ mu.Unlock()
+ want := []string{"app " + w.fx.sqid + "/shop", "host " + rdHost}
+ if !slices.Equal(got, want) {
+ t.Fatalf("locks held = %v, want %v", got, want)
+ }
+ // regionalMu was released: a second PUT does not wait forever.
+ w.mustPut(t, rdHost, rdBoth())
+}
+
+// On a plan without custom domains the cap sentence comes before any
+// answer about another owner's claim, as on the attach door: a free name
+// and a name someone else holds get the same bytes. A claim the caller
+// already holds, verified, is no new domain and meets no cap.
+func TestPlacementsPutPlanCapComesFirst(t *testing.T) {
+ w := newRegionalWorld(t, "code-rdput-cap")
+ w.mustPut(t, rdHost, rdBoth())
+ attachShopClaim(t, w.fx, w.fx.sqid, "shop", "alias.example.com", rdIE)
+ attachShopClaim(t, w.fx, "zzz", "blog", "theirs.example.com", "theirs.example.net")
+ w.fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ if _, err := w.fx.st.SetAccountPlan(OpsAccountID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ freeCode, free := w.put(t, "free.example.com", rdBoth())
+ if freeCode != http.StatusConflict || !strings.Contains(free, `"code":"cap"`) {
+ t.Fatalf("a free name on a capped plan = %d %s, want the cap 409", freeCode, free)
+ }
+ if code, out := w.put(t, "theirs.example.com", rdBoth()); code != freeCode ||
+ strings.ReplaceAll(out, "theirs", "free") != free {
+ t.Fatalf("another owner's name = %d %s, want the free name's %d %s", code, out, freeCode, free)
+ }
+ code, out := w.put(t, "alias.example.com", rdBoth())
+ requireRefusal(t, "own verified claim on a capped plan", code, out, http.StatusConflict, placementsOrdinaryMsg("alias.example.com"))
+ w.mustPut(t, rdHost, rdSet("uk="+rdUK))
+ w.requireNoClaim(t, "free.example.com", "a capped create")
+}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 82aa50d94..c6e6102bb 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -868,6 +868,11 @@ func (s *Server) registerCLIRoutes() {
// claim's target, where, and whether it is ready. The per-host read's
// roles and team scope exactly; it discloses no more about the claim.
s.cliScopedRoute("GET /api/cli/apps/{account}/{app}/domains/{host}/placements", svcrole.Allow(svcrole.Publish, svcrole.Instance), scopeDomainHost, s.handleAPIDomainPlacementsGet)
+ // The placements write (#447, spec §6.2): the only way into regional
+ // mode. A person's act and no service role's: it fixes where a name is
+ // served in every region and its capabilities for the claim's life, and
+ // a team credential (no team set here) cannot reach it either.
+ s.cliRoute("PUT /api/cli/apps/{account}/{app}/domains/{host}/placements", svcrole.Set{}, s.handleAPIDomainPlacementsPut)
s.cliScopedRoute("POST /api/cli/apps/{account}/{app}/domains", svcrole.Allow(svcrole.Publish, svcrole.Instance), scopeDomainBody, s.handleAPIDomainAttach)
s.cliScopedRoute("DELETE /api/cli/apps/{account}/{app}/domains/{host}", svcrole.Allow(svcrole.Publish, svcrole.Instance), scopeDomainHost, s.handleAPIDomainDetach)
// The prefix-map publish (path-based routing): replace the WHOLE map of
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index a41f844a2..f98320c99 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -2080,6 +2080,15 @@ var claimFixtures = map[string]claimFixture{
setup: func(t *testing.T, cx *claimCase) { cx.claimedAlias(t, "ti.to") },
do: claimAPI(http.MethodPut, "/api/cli/apps/bab/titogo/domains/ti.to/paths", `{"paths":{"paulca":"`+claimAliasRoute+`"}}`),
}},
+ // The placements write (#447): a host-claim console refuses it (RD-25)
+ // after its caller gates and before it reads or writes anything.
+ "route PUT /api/cli/apps/{account}/{app}/domains/{host}/placements": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"),
+ setup: claimWorldInstance,
+ do: claimRefusedAPI(http.MethodPut, "/api/cli/apps/bab/titogo/domains/shop.example.com/placements", `{"placements":[{"region":"ie","host":"acme.go.tito.io"}]}`),
+ status: http.StatusConflict,
+ msg: placementsHostClaimMsg,
+ }},
"route PUT /api/cli/apps/{account}/{app}/email/events/push": {door: &claimDoor{
apps: claimRefs("bab/titogo"),
do: claimAPI(http.MethodPut, "/api/cli/apps/bab/titogo/email/events/push", `{"path":"/mail/events"}`),
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index f4921d5e1..cb7beb8a6 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -121,6 +121,8 @@ var claimUnsupported = map[string]string{
"(db region forward spec §6): the reads route reads the record and answers main's residency sentence, writing nothing",
appRegionSetCopy.ClaimOff: "changing an app's stored region writes its SQL row, and no claim operation gates that write; " +
"both doors refuse after their caller gates and before they read or write anything",
+ placementsHostClaimMsg: "a regional claim is written by SetClaimPlacements, which no host-claim operation gates (#447 plan note 9); " +
+ "the placements PUT refuses after its caller gates and before it reads or writes anything",
seedClaimConsoleRefusal().Msg: "seeded instances need nested boxes, and the claim-armed path waits for #250 (seeded-instances spec §3.4); " +
"every import door refuses before it reads the record, and the legacy route assignment before it reads anything",
}
diff --git a/internal/console/server.go b/internal/console/server.go
index cb240d491..81fb8231b 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1372,6 +1372,12 @@ type Server struct {
// log line was written, pruned past two hours. Zero values are ready.
hostLocks keyedLocks
lifetimeLogged sync.Map
+ // regionalMu is the regional-domains mutex (#447, spec §6.7): the
+ // placements PUT holds it from its evidence reads to its claim write,
+ // and every door that could create a covering catch-all takes it too,
+ // so neither can slip in between the other's check and write. Acquired
+ // after any app or host lock, never before. The zero value is ready.
+ regionalMu sync.Mutex
// The trash sweep's clock (lifetimes_purge.go) and the box floor
// watch's memory (lifetimes_floor.go).
trashSweepState
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 5f2c843e8..b9dfed689 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -271,6 +271,11 @@ var closedDoors = []string{
// instance role, which is the point of the family: an app process mints
// a bot per member, inside bounds a person set.
"PUT /api/cli/apps/{account}/{app}/sidecars-manifest",
+ // The placements write (#447, spec §6.2): the only way into regional
+ // mode, fixing where a hostname is served in every region and its
+ // capabilities for the claim's life. A person's act: no credential the
+ // app holds, and no team credential, may make a name regional.
+ "PUT /api/cli/apps/{account}/{app}/domains/{host}/placements",
// `carlos system` (apisystem.go): what the whole deployment RUNS. The
// same cut as the mint and fleet doors, taken over the substrate every
// tenant sits inside rather than over one account's credentials, so it
@@ -1126,8 +1131,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 71 {
- t.Errorf("walked %d closed doors, want all %d (and 71 today: three environment ownership doors, instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
+ if seen != len(closedDoors) || seen != 72 {
+ t.Errorf("walked %d closed doors, want all %d (and 72 today: three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
seen, len(closedDoors))
}
}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 90c592ebb..7ca7b91d5 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -312,6 +312,7 @@ route POST /fleet/store/{account}/{decision}
route POST /invite/{token}
route PUT /api/cli/apps/{account}/{app}/config
route PUT /api/cli/apps/{account}/{app}/domains/{host}/paths
+route PUT /api/cli/apps/{account}/{app}/domains/{host}/placements
route PUT /api/cli/apps/{account}/{app}/email/events/push
route PUT /api/cli/apps/{account}/{app}/instances-manifest
route PUT /api/cli/apps/{account}/{app}/instances/{host}/import
diff --git a/internal/provision/recordhost.go b/internal/provision/recordhost.go
new file mode 100644
index 000000000..c3c204073
--- /dev/null
+++ b/internal/provision/recordhost.go
@@ -0,0 +1,45 @@
+package provision
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// RecordHostDeclared reports whether any instance record in the deployment
+// sits at host, under any known account and app (#447, spec §6.2 step 5:
+// the placements door's declared-ownership walk). A key at the host is
+// ownership whatever its body says, provisioned or not, so no record body is
+// read: it lists record keys as readAllRecords does (knownAccounts, then
+// listAppSubtree(..., "instances/")) and matches each key's host with
+// ParseRecordKey.
+//
+// Strict: a failed listing, an account manifest that does not read cleanly
+// or a partial app listing is an error, never "not declared". Records under
+// an account with no live manifest are invisible, as they are to the
+// provisioning pass that would mint their routes (ListAllRecordsStrict's
+// stated blind spot), so they never become a route.
+func RecordHostDeclared(ctx context.Context, s release.Store, host string) (bool, error) {
+ known, readFailed, err := knownAccounts(ctx, s)
+ if err != nil {
+ return false, err
+ }
+ if readFailed {
+ return false, errors.New("provision: an account manifest could not be read cleanly, so the record walk is incomplete")
+ }
+ keys, partial, err := listAppSubtree(ctx, s, known, "instances/")
+ if err != nil {
+ return false, fmt.Errorf("provision: list apps: %w", err)
+ }
+ if partial {
+ return false, errors.New("provision: an app's records could not be listed, so the record walk is incomplete")
+ }
+ for _, key := range keys {
+ if _, _, h, ok := ParseRecordKey(key, known); ok && h == host {
+ return true, nil
+ }
+ }
+ return false, nil
+}
diff --git a/internal/provision/recordhost_test.go b/internal/provision/recordhost_test.go
new file mode 100644
index 000000000..621fdce58
--- /dev/null
+++ b/internal/provision/recordhost_test.go
@@ -0,0 +1,117 @@
+package provision
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// recordHostStore is a bucket-shaped store (so the walk takes the per-app
+// listings production takes) that records every Get and can fail one Get
+// or one List.
+type recordHostStore struct {
+ *bucketShaped
+ mu sync.Mutex
+ gets []string
+ failGet string
+ failList string
+}
+
+func (s *recordHostStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.mu.Lock()
+ s.gets = append(s.gets, key)
+ s.mu.Unlock()
+ if key == s.failGet {
+ return nil, "", errors.New("get refused")
+ }
+ return s.bucketShaped.Get(ctx, key)
+}
+
+func (s *recordHostStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if prefix == s.failList {
+ return nil, errors.New("list refused")
+ }
+ return s.bucketShaped.List(ctx, prefix)
+}
+
+// TestRecordHostDeclared: the walk finds a record key at the host under any
+// known account, reading keys only (never a record body), and is strict:
+// an account manifest that does not read and an app listing that fails are
+// errors, never "not declared".
+func TestRecordHostDeclared(t *testing.T) {
+ d := dirStore(t)
+ mine := writeAccountManifest(t, d, acctID, "Mine")
+ theirs := writeAccountManifest(t, d, acctID+1, "Theirs")
+ for _, k := range []string{
+ "apps/" + mine + "/shop/instances/shop-ie.example.net.json",
+ "apps/" + theirs + "/blog/instances/taken.example.com.json",
+ "apps/" + theirs + "/blog/instances.json",
+ "apps/" + theirs + "/blog/logs/2026/10/29/taken.example.com.json",
+ // An account with no manifest: invisible, as to every reader.
+ "apps/zzzz/ghost/instances/ghost.example.com.json",
+ } {
+ if _, err := d.Put(ctx, k, []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ s := &recordHostStore{bucketShaped: &bucketShaped{Store: d}}
+
+ for host, want := range map[string]bool{
+ "taken.example.com": true, // another account's record
+ "shop-ie.example.net": true, // the caller's own
+ "free.example.com": false,
+ "ghost.example.com": false,
+ "blog": false, // the manifest is not a record
+ } {
+ got, err := RecordHostDeclared(ctx, s, host)
+ if err != nil || got != want {
+ t.Errorf("RecordHostDeclared(%s) = %v, %v; want %v, nil", host, got, err, want)
+ }
+ }
+ for _, k := range s.gets {
+ if strings.Contains(k, "/instances/") {
+ t.Errorf("the walk read %s; it reads keys only", k)
+ }
+ }
+ if s.listedAllOfApps() {
+ t.Error("the walk listed all of apps/ on a bucket-shaped store")
+ }
+
+ // An account manifest that does not read.
+ s.failGet = "accounts/" + theirs + "/account.json"
+ if got, err := RecordHostDeclared(ctx, s, "free.example.com"); err == nil {
+ t.Errorf("a manifest that does not read = %v, nil; want an error", got)
+ }
+ s.failGet = ""
+
+ // One app's listing fails: a partial walk is an error.
+ s.failList = "apps/" + theirs + "/blog/instances/"
+ if got, err := RecordHostDeclared(ctx, s, "free.example.com"); err == nil {
+ t.Errorf("a failed app listing = %v, nil; want an error", got)
+ }
+ s.failList = ""
+
+ // One account's app directories fail to list.
+ s.bucketShaped.failDirs = "apps/" + theirs + "/"
+ if got, err := RecordHostDeclared(ctx, s, "free.example.com"); err == nil {
+ t.Errorf("a failed account listing = %v, nil; want an error", got)
+ }
+ s.bucketShaped.failDirs = ""
+
+ // The accounts listing itself fails.
+ s.failList = "accounts/"
+ if got, err := RecordHostDeclared(ctx, s, "free.example.com"); err == nil {
+ t.Errorf("a failed accounts listing = %v, nil; want an error", got)
+ }
+ s.failList = ""
+
+ // A store that is not bucket-shaped is walked through the apps/
+ // listing, with the same answers.
+ if got, err := RecordHostDeclared(ctx, release.Store(d), "taken.example.com"); err != nil || !got {
+ t.Errorf("on a plain store = %v, %v; want true, nil", got, err)
+ }
+}