carlos / platform Public

console: the label under the apps domain is platform-owned (T5)

Choice B (spec 2026-11-11 §4.2, §4.5): a new host two or more labels
under the apps domain, or a one-label host whose claim gains a catch-all,
may only be created under the creator's sqid or a subdomain it holds.
Re-attaching or changing a claim the account already holds is not a
create. One namespace view per request (loadNamespaces, one claim
listing); a failed listing or an unread namespace claim refuses,
retryably. A held name is a namespace like a sqid in domainHostPolicy,
otherAccountsNamespace, firstRouteOutsideNamespace and domainProofExempt.

Doors:
- domain attach core, browser and CLI static branch
  (domainattach.go:159-172; first route also domainattach.go:233)
- CLI attach, alias and platform door (apidomains.go:440-456)
- capability change, false-to-true Catchall (apidomains.go:779)
- instance catch-all (domaincatchall.go:101-114)
- regional placements (apiplacements.go:484-538)
- instance create, the host's own label; seed, import and restore
  forms included (apiinstances.go:1739)
Detach, paths and the plan-cap test create nothing and keep the zero view.

Also subdomainRefusal (every §4.2 rule), namespaceOccupants (claims,
records, pending allocations; strict), subdomainInfrastructure,
Store.PendingAllocationsUnder and the approved refusal copy
(subdomain_copy.go). Record-write census re-pins handleAPIDomainAttach
and attachDomainAs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1e7edcefc0ff5a058c52c6c03e0f28c104a79904 parent c08affd
19 files changed, +1,517 −85
  • internal/console/apidomains.go +58 −13
  • internal/console/apiinstances.go +13 −0
  • internal/console/apiplacements.go +22 −2
  • internal/console/claim_alias_test.go +1 −1
  • internal/console/claim_first_route.go +2 −2
  • internal/console/demo_api_origin_test.go +5 −5
  • internal/console/demo_publish_test.go +2 −2
  • internal/console/domainattach.go +35 −7
  • internal/console/domaincatchall.go +23 −3
  • internal/console/domainplatform_test.go +3 −3
  • internal/console/domainpolicy.go +67 −45
  • internal/console/domainproof_test.go +42 −0
  • internal/console/lifetimes_store.go +25 −0
  • internal/console/plancaps.go +5 −1
  • internal/console/regional_writers_test.go +1 −1
  • internal/console/subdomain_copy.go +45 −0
  • internal/console/subdomains.go +464 −0
  • internal/console/subdomains_test.go +702 −0
  • internal/provision/account_subdomains_census_test.go +2 −0

Intent

Attributed to this commit: 6.91 g CO₂e (864,003 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-account-name-hosts, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index 18ef11bff..945a665e2 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -151,13 +151,23 @@ func (s *Server) platformDomains(exemptAppsDomain bool) []string {
// reservedDomains: see platformDomains.
func (s *Server) reservedDomains(exemptAppsDomain bool) []string {
+ return s.reservedDomainsWith(exemptAppsDomain, true)
+}
+
+// reservedDomainsWith is reservedDomains, with ReservePlatformDomains' one
+// synthetic entry (the whole apps domain) left out when withAppsDomain is
+// false. Account subdomains' infrastructure rule (subdomainInfrastructure,
+// spec §4.2 rule 4) asks for that: the entry would refuse every name, and
+// denyEntries' exemption cannot stand in for it because that drops every
+// entry covering the apps domain, an operator's included.
+func (s *Server) reservedDomainsWith(exemptAppsDomain, withAppsDomain bool) []string {
domain := strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))
steeringHost := strings.TrimSuffix(normalizeHost(strings.TrimSpace(s.cfg.SteeringHost)), ".")
if steeringHost == "" && domain != "" {
steeringHost = "edge." + domain
}
entries := []string{strings.TrimSuffix(s.cfg.TunnelHost, ".")}
- if s.cfg.ReservePlatformDomains {
+ if s.cfg.ReservePlatformDomains && withAppsDomain {
entries = append(entries, domain)
}
// The steering host is never exempt: it is edge.<apps-domain>, under
@@ -421,10 +431,32 @@ func (s *Server) handleAPIDomainAttach(w http.ResponseWriter, r *http.Request) {
"invalid hostname — attach a full hostname like tickets.example.com")
return
}
- if policy := s.domainHostPolicy(host, acct.Sqid); policy == hostReserved || (policy == hostPlatform && !in.Platform) || (s.directAppsDomainHost(host) && ((in.Wildcard != nil && *in.Wildcard) || (in.Catchall != nil && *in.Catchall))) {
+ ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ defer cancel()
+ // The namespace view (account subdomains §4.5), read once for this
+ // request and only for a host under the apps domain; the static branch
+ // hands it to the attach core. A listing that fails, or a label whose
+ // namespace claim did not read, refuses here, retryably.
+ v, ref := s.doorNamespaces(ctx, host)
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ if policy := s.domainHostPolicy(v, host, acct.Sqid); policy == hostReserved || (policy == hostPlatform && !in.Platform) || (s.directAppsDomainHost(host) && ((in.Wildcard != nil && *in.Wildcard) || (in.Catchall != nil && *in.Catchall))) {
jsonError(w, http.StatusBadRequest, "that hostname is platform-managed")
return
}
+ // Choice B (account subdomains §4.2): a new host under a label that is
+ // not this account's, or a catch-all that would serve names below
+ // one, is refused, the platform door included. The account's own
+ // claim at host is a re-attach and passes, as does a catch-all it
+ // already has on. setDomainCapabilities asks again under regionalMu,
+ // on the claim it reads there; this earlier answer keeps an attach that
+ // asks for a catch-all from writing its claim first.
+ if ref := s.attachCreateRefusal(ctx, v, host, acct.Sqid, in.Catchall != nil && *in.Catchall); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
if in.Kind != "" && in.Route != "" {
jsonError(w, http.StatusBadRequest,
"route and kind are two different instructions — name a route to alias, or a kind to mint, not both")
@@ -434,8 +466,6 @@ func (s *Server) handleAPIDomainAttach(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusBadRequest, "kind must be \"static\"")
return
}
- ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
- defer cancel()
// The caller's own PENDING first-route claim (#215): a plain re-attach
// is how it gets verified, and only the first-route core knows how —
// look for the proof, and declare the record once it is there. Without
@@ -462,7 +492,7 @@ func (s *Server) handleAPIDomainAttach(w http.ResponseWriter, r *http.Request) {
// from the core's result: on the first-route branch the host IS the
// route the record just declared; on the alias branch it is the
// route the claim names.
- res, ref := s.attachDomainAs(ctx, acct, app, host, in.Kind, in.Channel, principal, in.Platform, message)
+ res, ref := s.attachDomainAs(ctx, &v, acct, app, host, in.Kind, in.Channel, principal, in.Platform, message)
if ref != nil {
setNoCapacityRetryAfter(w, ref)
// The app gone under the lifetime create's lock is the
@@ -502,7 +532,7 @@ func (s *Server) handleAPIDomainAttach(w http.ResponseWriter, r *http.Request) {
if cur, err := domains.GetClaim(ctx, s.cfg.Releases, host); err == nil &&
cur.Account == acct.Sqid && cur.App == app && cur.Route == "" {
if in.Wildcard != nil || in.Catchall != nil {
- if !s.setDomainCapabilities(w, r, ctx, acct, app, p, host, in.Wildcard, in.Catchall) {
+ if !s.setDomainCapabilities(w, r, ctx, v, acct, app, p, host, in.Wildcard, in.Catchall) {
return
}
}
@@ -580,7 +610,7 @@ func (s *Server) handleAPIDomainAttach(w http.ResponseWriter, r *http.Request) {
// below, AFTER this write has already established ownership (a
// review finding on Task 1 — an attach body smuggling
// "wildcard":true alongside host/route must not reach this literal).
- }, time.Now(), s.domainProver(ctx, host, acct.Sqid))
+ }, time.Now(), s.domainProver(ctx, v, host, acct.Sqid))
if errors.Is(err, domains.ErrHostUnavailable) {
// Exactly these bytes, whoever holds it: naming the holder — or even
// distinguishing "held by another app of yours" from "held by a
@@ -632,7 +662,7 @@ func (s *Server) handleAPIDomainAttach(w http.ResponseWriter, r *http.Request) {
// the same "absent means unchanged" contract the CLI's fs.Visit-gated
// flags rely on.
if in.Wildcard != nil || in.Catchall != nil {
- if !s.setDomainCapabilities(w, r, ctx, acct, app, p, host, in.Wildcard, in.Catchall) {
+ if !s.setDomainCapabilities(w, r, ctx, v, acct, app, p, host, in.Wildcard, in.Catchall) {
return
}
}
@@ -687,7 +717,12 @@ const wildFailMsg = "too many wildcard attempts with no _acme-challenge CNAME in
// the answer a lost CAS on such a claim gets. Every
// request takes the mutex, the disabling ones too: one path, and whether a
// request leaves Catchall on can depend on the claim it reads.
-func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, ctx context.Context, acct *Account, app string, p Principal, host string, wantWildcard, wantCatchall *bool) (ok bool) {
+//
+// v is the request's namespace view: a false-to-true Catchall serves new
+// names below host, so it is a create under host's label (account
+// subdomains §4.2, choice B), judged here on the claim read under the
+// mutex.
+func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, ctx context.Context, v namespaceView, acct *Account, app string, p Principal, host string, wantWildcard, wantCatchall *bool) (ok bool) {
if s.cfg.HostClaim {
jsonError(w, http.StatusConflict, claimRefusalText(errClaimAliasCapabilitiesUnsupported))
return false
@@ -739,6 +774,13 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
// name sits under host. A claim whose Catchall is already on needs no
// scan: the PUT refuses a regional name under it while it is on.
if catchall && !cur.Catchall {
+ // New names below host would serve: a create under its label, so
+ // the label must be this account's (account subdomains §4.2).
+ if s.createRefusal(v, host, acct.Sqid, createExpandsCoverage) {
+ ref := s.createDoorRefusal(v, host, acct.Sqid)
+ jsonError(w, ref.Status, ref.Msg)
+ return false
+ }
if ref := s.regionalDescendantRefusal(ctx, host); ref != nil {
if ref.Status == http.StatusConflict {
ref = &doorRefusal{Status: http.StatusConflict, Msg: catchallOverRegionalMsg(host)}
@@ -962,8 +1004,10 @@ func (s *Server) handleAPIDomainPaths(w http.ResponseWriter, r *http.Request) {
}
// A prefix map on a platform hostname routes slices of the operator's
// own site, so it is the operator's to publish (#209). From the name
- // alone, before the body or the claim is read: no neutrality cost.
- if s.domainHostPolicy(host, acct.Sqid) == hostPlatform && !s.principalPlatformOperator(p) {
+ // alone, before the body or the claim is read: no neutrality cost. The
+ // zero namespace view (sqids and config only): a paths change creates
+ // no host, so it keeps the answer it gave before names existed.
+ if s.domainHostPolicy(namespaceView{}, host, acct.Sqid) == hostPlatform && !s.principalPlatformOperator(p) {
jsonError(w, http.StatusForbidden, platformOperatorMsg)
return
}
@@ -1141,8 +1185,9 @@ func (s *Server) handleAPIDomainDetach(w http.ResponseWriter, r *http.Request) {
// detachDomain's rule (#209): a platform hostname's claim is the
// operator's to release. From the name alone, before the claim is read,
// so the door's quiet-in-both-directions answer is untouched for every
- // hostname a member could hold.
- if s.domainHostPolicy(host, acct.Sqid) == hostPlatform && !s.principalPlatformOperator(p) {
+ // hostname a member could hold. The zero namespace view, as in
+ // detachDomain: a detach creates nothing.
+ if s.domainHostPolicy(namespaceView{}, host, acct.Sqid) == hostPlatform && !s.principalPlatformOperator(p) {
jsonError(w, http.StatusForbidden, platformOperatorMsg)
return
}
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 8640219b5..08fab5495 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -1731,6 +1731,19 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
restore, restoreRegion = &ask, v.Region
instanceCreateStage(instanceCreateAfterRestoreProof, host)
}
+ // Choice B (account subdomains §4.2): an instance record is a new host,
+ // so under the apps domain its own label (not the manifest domain's
+ // standing) must be this account's sqid or a name it holds. Every
+ // create through this door asks, the seed, import and restore forms
+ // included; a restore has already had its ownership answer above.
+ if nv, ref := s.doorNamespaces(ctx, host); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ } else if s.createRefusal(nv, host, acct.Sqid, createNewHost) {
+ ref := s.createDoorRefusal(nv, host, acct.Sqid)
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
if err := s.demoRecordReservation(r.Context(), provision.Record{Host: host}); err != nil {
jsonError(w, http.StatusConflict, demoCopy["DEMO-POLICY"])
return
diff --git a/internal/console/apiplacements.go b/internal/console/apiplacements.go
index 8a8ebefc3..0a615715d 100644
--- a/internal/console/apiplacements.go
+++ b/internal/console/apiplacements.go
@@ -477,7 +477,17 @@ func (s *Server) handleAPIDomainPlacementsPut(w http.ResponseWriter, r *http.Req
"invalid hostname — attach a full hostname like tickets.example.com")
return
}
- if s.domainHostPolicy(host, acct.Sqid) != hostOpen || s.directAppsDomainHost(host) {
+ // The namespace view (account subdomains §4.5), read once and only for
+ // a host under the apps domain; a listing that fails, or a label whose
+ // namespace claim did not read, refuses here, retryably.
+ nsCtx, nsCancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ v, ref := s.doorNamespaces(nsCtx, host)
+ nsCancel()
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ if s.domainHostPolicy(v, host, acct.Sqid) != hostOpen || s.directAppsDomainHost(host) {
jsonError(w, http.StatusBadRequest, "that hostname is platform-managed")
return
}
@@ -509,7 +519,7 @@ func (s *Server) handleAPIDomainPlacementsPut(w http.ResponseWriter, r *http.Req
s.regionalMu.Lock()
defer s.regionalMu.Unlock()
now := time.Now()
- prove := onceProver(s.domainProver(ctx, host, acct.Sqid))
+ prove := onceProver(s.domainProver(ctx, v, host, acct.Sqid))
cur, etag, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
if errors.Is(err, os.ErrNotExist) {
cur, etag, err = nil, "", nil
@@ -519,6 +529,16 @@ func (s *Server) handleAPIDomainPlacementsPut(w http.ResponseWriter, r *http.Req
jsonError(w, http.StatusBadGateway, "could not read the hostname")
return
}
+ // Choice B (account subdomains §4.2), on the claim just read under the
+ // locks: a new claim under a label that is not this account's, or a
+ // catch-all that would serve names below one, is refused. A claim the
+ // account already holds at host is not a new host. Decided from the
+ // label and the account's own claim only, so it says nothing about
+ // anyone else's.
+ if ref := s.namespaceCreateRefusal(v, host, acct.Sqid, cur, in.Catchall != nil && *in.Catchall); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ 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
diff --git a/internal/console/claim_alias_test.go b/internal/console/claim_alias_test.go
index 0b2bc4929..426e2e2f1 100644
--- a/internal/console/claim_alias_test.go
+++ b/internal/console/claim_alias_test.go
@@ -94,7 +94,7 @@ func TestFlaggedDomainCapabilitiesRefuseBeforeBucketRead(t *testing.T) {
s := &Server{cfg: Config{HostClaim: true}}
w := httptest.NewRecorder()
yes := true
- if s.setDomainCapabilities(w, httptest.NewRequest("POST", "/", nil), context.Background(), nil, "site", Principal{}, "alias.example.com", &yes, nil) {
+ if s.setDomainCapabilities(w, httptest.NewRequest("POST", "/", nil), context.Background(), namespaceView{}, nil, "site", Principal{}, "alias.example.com", &yes, nil) {
t.Fatal("capability mutation admitted")
}
if w.Code != http.StatusConflict {
diff --git a/internal/console/claim_first_route.go b/internal/console/claim_first_route.go
index d313aa1c9..e6c21478f 100644
--- a/internal/console/claim_first_route.go
+++ b/internal/console/claim_first_route.go
@@ -13,7 +13,7 @@ import (
"github.com/carlosframework/platform/internal/provision"
)
-func (s *Server) attachClaimFirstRoute(ctx context.Context, acct *Account, app, host, channel, principal string) (attachResult, *doorRefusal) {
+func (s *Server) attachClaimFirstRoute(ctx context.Context, v namespaceView, 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
@@ -25,7 +25,7 @@ func (s *Server) attachClaimFirstRoute(ctx context.Context, acct *Account, app,
case c.Account == acct.Sqid && c.App == app && c.Regional():
return attachResult{}, claimRefusal(host, domains.ErrRegionalClaim)
}
- if !s.domainProver(ctx, host, acct.Sqid)() {
+ if !s.domainProver(ctx, v, host, acct.Sqid)() {
return attachResult{}, &doorRefusal{Status: http.StatusConflict, Msg: verifyGuidance(s.domainChallenge(host, acct.Sqid))}
}
request, err := s.beginClaimCreate(ctx, acct, app, host, principal, func(now time.Time, acquisition string) (hostops.Record, error) {
diff --git a/internal/console/demo_api_origin_test.go b/internal/console/demo_api_origin_test.go
index 33b05e2f6..11c716d88 100644
--- a/internal/console/demo_api_origin_test.go
+++ b/internal/console/demo_api_origin_test.go
@@ -225,10 +225,10 @@ func TestDemoAPIProofRequired(t *testing.T) {
func TestDemoAPIHostOwnership(t *testing.T) {
t.Run("catchall parent", func(t *testing.T) {
s := &Server{cfg: Config{Origin: "https://console.example.net", DemoAPIOrigin: "https://www.example.com"}}
- if !s.catchallParentRefused("example.com", "shop") {
+ if !s.catchallParentRefused(namespaceView{}, "example.com", "shop") {
t.Error("catch-all could cover configured public API host")
}
- if s.catchallParentRefused("other.example.net", "shop") {
+ if s.catchallParentRefused(namespaceView{}, "other.example.net", "shop") {
t.Error("configured public API host reserved unrelated catch-all")
}
})
@@ -277,12 +277,12 @@ func TestDemoAPIHostOwnership(t *testing.T) {
s.cfg.Origin = "https://console.example.com"
s.cfg.TunnelHost = "hub.example.com"
s.cfg.DemoAPIOrigin = "https://" + host
- if s.domainHostPolicy(host, "shop") != hostReserved {
+ if s.domainHostPolicy(namespaceView{}, host, "shop") != hostReserved {
t.Error("public origin overrode reserved host")
}
}
s.cfg.DemoAPIOrigin = "https://example.com"
- if s.domainHostPolicy("child.example.com", "shop") != hostOpen {
+ if s.domainHostPolicy(namespaceView{}, "child.example.com", "shop") != hostOpen {
t.Error("public host reserved unrelated child")
}
if code, _, _ := rawReq(t, "POST", base, outsider, platformAttachBody("example.com", "shop.example.net")); code != 404 {
@@ -324,7 +324,7 @@ func TestDemoAPIHostOwnership(t *testing.T) {
}
}
s.cfg.DemoAPIOrigin = ""
- if s.domainHostPolicy("example.com", "shop") != hostOpen {
+ if s.domainHostPolicy(namespaceView{}, "example.com", "shop") != hostOpen {
t.Error("unset retained reservation")
}
}
diff --git a/internal/console/demo_publish_test.go b/internal/console/demo_publish_test.go
index fce57737b..39a3c0a01 100644
--- a/internal/console/demo_publish_test.go
+++ b/internal/console/demo_publish_test.go
@@ -203,11 +203,11 @@ func TestDemoCapabilities(t *testing.T) {
func TestDemoDomainRouting(t *testing.T) {
s, _, _, _ := demoPublishFixture(t)
for _, host := range []string{s.cfg.Demo.Domain, "unknown." + s.cfg.Demo.Domain, "*." + s.cfg.Demo.Domain, "deep.unknown." + s.cfg.Demo.Domain} {
- if s.domainHostPolicy(host, "other") != hostReserved {
+ if s.domainHostPolicy(namespaceView{}, host, "other") != hostReserved {
t.Errorf("reserved demo zone accepted: %s", host)
}
}
- if s.domainHostPolicy("shop.example.com", "other") != hostOpen {
+ if s.domainHostPolicy(namespaceView{}, "shop.example.com", "other") != hostOpen {
t.Error("ordinary domain changed")
}
}
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go
index 764f538ed..fa5212d32 100644
--- a/internal/console/domainattach.go
+++ b/internal/console/domainattach.go
@@ -106,7 +106,7 @@ type attachResult struct {
// a route, static otherwise) and the channel is the one the host's own
// existing route follows, or failing that the app's sole shipped channel.
func (s *Server) attachDomain(ctx context.Context, acct *Account, app, host, kindFlag, channelFlag, principal string, messages ...string) (attachResult, *doorRefusal) {
- return s.attachDomainAs(ctx, acct, app, host, kindFlag, channelFlag, principal, false, messages...)
+ return s.attachDomainAs(ctx, nil, acct, app, host, kindFlag, channelFlag, principal, false, messages...)
}
// attachDomainAs is attachDomain with the platform door (#209) named.
@@ -114,7 +114,12 @@ func (s *Server) attachDomain(ctx context.Context, acct *Account, app, host, kin
// CALLER has already established that principal is a platform operator
// (handleAPIDomainAttach refuses the flag otherwise). The browser form never
// passes it.
-func (s *Server) attachDomainAs(ctx context.Context, acct *Account, app, host, kindFlag, channelFlag, principal string, platform bool, messages ...string) (attachResult, *doorRefusal) {
+//
+// view is the request's namespace view (account subdomains §4.5) when the
+// calling door has already loaded it for this host (the CLI API door, which
+// refused a failed load itself), or nil to load it here, once, after the
+// hostname is normalized.
+func (s *Server) attachDomainAs(ctx context.Context, view *namespaceView, acct *Account, app, host, kindFlag, channelFlag, principal string, platform bool, messages ...string) (attachResult, *doorRefusal) {
message := ""
if len(messages) != 0 {
message = messages[0]
@@ -143,10 +148,30 @@ func (s *Server) attachDomainAs(ctx context.Context, acct *Account, app, host, k
if err := s.demoRecordReservation(ctx, provision.Record{Host: host}); err != nil {
return attachResult{}, &doorRefusal{Status: http.StatusConflict, Msg: demoCopy["DEMO-POLICY"]}
}
- if policy := s.domainHostPolicy(host, acct.Sqid); policy == hostReserved || (policy == hostPlatform && !platform) {
+ // The namespace view (account subdomains §4.5): read once, and only for
+ // a host under the apps domain. A listing that fails, or a label whose
+ // namespace claim did not read, refuses here, retryably.
+ var v namespaceView
+ if view != nil {
+ v = *view
+ } else {
+ var ref *doorRefusal
+ if v, ref = s.doorNamespaces(ctx, host); ref != nil {
+ return attachResult{}, ref
+ }
+ }
+ if policy := s.domainHostPolicy(v, host, acct.Sqid); policy == hostReserved || (policy == hostPlatform && !platform) {
return attachResult{}, &doorRefusal{Status: http.StatusUnprocessableEntity,
Msg: "that hostname is platform-managed"}
}
+ // Choice B (account subdomains §4.2): a new host under a label that is
+ // not this account's sqid or name is refused, the platform door
+ // included. A claim the account already holds at host is a re-attach,
+ // not a create, and passes. Decided from the label and the account's
+ // own claim only, so the answer is the same whoever else holds host.
+ if ref := s.attachCreateRefusal(ctx, v, host, acct.Sqid, false); ref != nil {
+ return attachResult{}, ref
+ }
// Plans 3a: custom domains need a plan that includes them.
if ref := s.customDomainRefusal(acct, host); ref != nil {
return attachResult{}, ref
@@ -176,7 +201,7 @@ func (s *Server) attachDomainAs(ctx context.Context, acct *Account, app, host, k
// lookup, made only when the answer can change what is written (see
// domains.AttachClaimProven), so a re-attach of a verified claim costs no
// DNS round trip.
- prove := s.domainProver(ctx, host, acct.Sqid)
+ prove := s.domainProver(ctx, v, host, acct.Sqid)
verify := s.domainChallenge(host, acct.Sqid)
// --- alias attach: the app already has a route to serve from ---------
@@ -205,7 +230,7 @@ func (s *Server) attachDomainAs(ctx context.Context, acct *Account, app, host, k
if s.directAppsDomainHost(host) {
return attachResult{}, &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: hostUnavailableMsg}
}
- if s.firstRouteOutsideNamespace(host, acct.Sqid) {
+ if s.firstRouteOutsideNamespace(v, host, acct.Sqid) {
return attachResult{}, &doorRefusal{Status: http.StatusUnprocessableEntity,
Msg: "that hostname is platform-managed"}
}
@@ -244,7 +269,7 @@ func (s *Server) attachDomainAs(ctx context.Context, acct *Account, app, host, k
}
}
if s.cfg.HostClaim {
- return s.attachClaimFirstRoute(ctx, acct, app, host, channel, principal)
+ return s.attachClaimFirstRoute(ctx, v, acct, app, host, channel, principal)
}
if lifetimesUnit(ctx) {
return s.attachFirstRouteWithLifetime(ctx, acct, app, host, channel, principal, message, claim, prove, verify)
@@ -372,7 +397,10 @@ func (s *Server) detachDomain(ctx context.Context, acct *Account, app, host, pri
// nothing about who holds it. Reserved names are left alone: nobody can
// claim one now, and a member holding one from before it was reserved
// must still be able to let it go.
- if s.domainHostPolicy(host, acct.Sqid) == hostPlatform && !s.platformOperator(principal) {
+ // The zero namespace view (sqids and config only): detach creates
+ // nothing, and must work whatever the namespace listing does, so it
+ // keeps the answer it gave before names existed.
+ if s.domainHostPolicy(namespaceView{}, host, acct.Sqid) == hostPlatform && !s.platformOperator(principal) {
return &doorRefusal{Status: http.StatusForbidden, Msg: platformOperatorMsg}
}
if lifetimesUnit(ctx) {
diff --git a/internal/console/domaincatchall.go b/internal/console/domaincatchall.go
index de9752f53..06fbe230c 100644
--- a/internal/console/domaincatchall.go
+++ b/internal/console/domaincatchall.go
@@ -56,8 +56,11 @@ const instanceCatchallOverRegionalMsg = "an instance catch-all cannot cover a re
// under its parent to one account at the attach door, and that must
// never cover a registry's whole namespace;
// - the reserved sidecar suffix.
-func (s *Server) catchallParentRefused(parent, account string) bool {
- if s.domainHostPolicy(parent, account) != hostOpen {
+//
+// v is the request's namespace view: a parent under another account's held
+// name is refused as one under its sqid is.
+func (s *Server) catchallParentRefused(v namespaceView, parent, account string) bool {
+ if s.domainHostPolicy(v, parent, account) != hostOpen {
return true
}
if strings.HasSuffix(parent, provision.SidecarSuffix) {
@@ -94,7 +97,24 @@ func (s *Server) attachInstanceCatchall(ctx context.Context, acct *Account, app,
if msg, status := s.temporaryRefusal(acct, app, "attach a domain to it"); msg != "" {
return false, &doorRefusal{Status: status, Msg: msg}
}
- if s.catchallParentRefused(parent, acct.Sqid) {
+ host := domains.InstanceCatchallHost(parent)
+ v, ref := s.doorNamespaces(ctx, host)
+ if ref != nil {
+ return false, ref
+ }
+ // Another account's sqid or name keeps the answer it had (the first
+ // check of catchallParentRefused). Then choice B (account subdomains
+ // §4.2): a catch-all serves every name below parent, so it is a create
+ // under parent's label, refused with the answer naming the fix when
+ // that label is not this account's. The rest of catchallParentRefused
+ // still refuses every parent under the apps domain after that.
+ if s.domainHostPolicy(v, parent, acct.Sqid) != hostOpen {
+ return false, &doorRefusal{Status: http.StatusBadRequest, Msg: "that hostname is platform-managed"}
+ }
+ if s.createRefusal(v, host, acct.Sqid, createNewHost) {
+ return false, s.createDoorRefusal(v, host, acct.Sqid)
+ }
+ if s.catchallParentRefused(v, parent, acct.Sqid) {
return false, &doorRefusal{Status: http.StatusBadRequest, Msg: "that hostname is platform-managed"}
}
// Plans 3a: a catch-all is a custom domain too.
diff --git a/internal/console/domainplatform_test.go b/internal/console/domainplatform_test.go
index 9a31576cc..e5f3a2169 100644
--- a/internal/console/domainplatform_test.go
+++ b/internal/console/domainplatform_test.go
@@ -62,7 +62,7 @@ func TestDomainHostPolicyMatrix(t *testing.T) {
{"web.sidecar.internal", hostReserved},
}
for _, c := range cases {
- if got := s.domainHostPolicy(c.host, "bab"); got != c.want {
+ if got := s.domainHostPolicy(namespaceView{}, c.host, "bab"); got != c.want {
t.Errorf("domainHostPolicy(%q) = %v, want %v", c.host, got, c.want)
}
if got := s.domainHostDenied(c.host, "bab"); got != (c.want != hostOpen) {
@@ -79,7 +79,7 @@ func TestDomainHostPolicyMatrix(t *testing.T) {
"carloku.test": hostPlatform,
"hub.carloku.test": hostReserved,
} {
- if got := s.domainHostPolicy(host, "bab"); got != want {
+ if got := s.domainHostPolicy(namespaceView{}, host, "bab"); got != want {
t.Errorf("without reserve: domainHostPolicy(%q) = %v, want %v", host, got, want)
}
}
@@ -219,7 +219,7 @@ func TestPlatformAttachReservedStaysRefused(t *testing.T) {
t.Fatalf("account: %v", err)
}
for _, host := range []string{"console.carloku.test", "hub.carloku.test", "edge.oncarlos.test", "titogo.bab.oncarlos.test"} {
- if _, ref := fx.srv.attachDomainAs(context.Background(), acct, "titogo", host, "static", "", "paul@keymail.dev", true); ref == nil || ref.Status != http.StatusUnprocessableEntity {
+ if _, ref := fx.srv.attachDomainAs(context.Background(), nil, acct, "titogo", host, "static", "", "paul@keymail.dev", true); ref == nil || ref.Status != http.StatusUnprocessableEntity {
t.Errorf("core attach of reserved %s with the door granted = %+v, want 422", host, ref)
}
claimAbsent(t, fx, host)
diff --git a/internal/console/domainpolicy.go b/internal/console/domainpolicy.go
index b0bf8e69f..55fb123b0 100644
--- a/internal/console/domainpolicy.go
+++ b/internal/console/domainpolicy.go
@@ -63,7 +63,14 @@ func (p hostPolicy) String() string {
// (consoleHosts); reservedDomains and platformDomains cover whole subtrees,
// and reserved wins where the two overlap (a tunnel host under a
// CONSOLE_DENY_DOMAINS entry stays reserved).
-func (s *Server) domainHostPolicy(host, account string) hostPolicy {
+//
+// v is the request's namespace view (account subdomains §4.5): a host under
+// another account's held name is reserved exactly as one under its sqid. A
+// door that creates nothing (detach, paths) passes the zero view, which
+// knows sqids only, and so keeps the answer it gave before names existed
+// whatever the namespace listing does; the plan cap's custom-domain test
+// passes it too, as no host under the apps domain is a custom domain.
+func (s *Server) domainHostPolicy(v namespaceView, host, account string) hostPolicy {
if s.demoDomainReserved(host) || slices.Contains(s.consoleHosts(), host) {
return hostReserved
}
@@ -75,10 +82,11 @@ func (s *Server) domainHostPolicy(host, account string) hostPolicy {
if strings.HasSuffix(host, provision.SidecarSuffix) {
return hostReserved
}
- // Another live account's <sqid>.<apps-domain> namespace (#215): reserved
- // to everyone, the operator's door included, and whatever
+ // Another live account's <sqid>.<apps-domain> namespace (#215), or a
+ // name another account holds (account subdomains §4.5): reserved to
+ // everyone, the operator's door included, and whatever
// ReservePlatformDomains says.
- if s.otherAccountsNamespace(host, account) {
+ if s.otherAccountsNamespace(v, host, account) {
return hostReserved
}
allowed := domains.ValidSqid(account) && slices.Contains(s.cfg.AppsDomainAliasAccounts, account) && s.directAppsDomainHost(host)
@@ -102,9 +110,12 @@ func (s *Server) domainHostPolicy(host, account string) hostPolicy {
}
// domainHostDenied reports whether a MEMBER's attach of host by account is
-// refused as platform-managed.
+// refused as platform-managed. It knows sqids, not held names (the zero
+// namespaceView): its one door, the domain purchase, asks about registrable
+// domains, never names under the apps domain. Every door that creates under
+// the apps domain asks domainHostPolicy with the request's view.
func (s *Server) domainHostDenied(host, account string) bool {
- return s.domainHostPolicy(host, account) != hostOpen
+ return s.domainHostPolicy(namespaceView{}, host, account) != hostOpen
}
// platformOperator reports whether addr may use the platform door (#209):
@@ -142,25 +153,21 @@ func (s *Server) principalPlatformOperator(p Principal) bool {
// door, or writes to a platform hostname's claim, without being an operator.
const platformOperatorMsg = "that hostname is platform-managed. only a platform operator (an ops account owner, or an address on CARLOS_SYSTEM_OPERATORS) can attach or change it"
-// appsNamespace returns the label of the account namespace host falls in —
-// "bes" for bes.<apps-domain> and for anything under it, such as
-// web.bes.<apps-domain> — or "" when host is not under the apps domain or the
-// label could not be an account (domains.ValidSqid). Shape only: whether an
+// appsNamespace returns the account whose namespace host falls in, from the
+// label directly under the apps domain: "bes" for bes.<apps-domain> and for
+// anything under it, such as web.bes.<apps-domain>, and, for a name an
+// account holds (account subdomains §4.5), that account's sqid for
+// harbour.<apps-domain> and web.harbour.<apps-domain>. "" when host is not
+// under the apps domain or the label is neither sqid-shaped nor a held name.
+// known is false when the label's namespace claim did not read: held, by an
+// account nobody can name. For a sqid label this is shape only: whether an
// account with that sqid exists is the caller's question.
-func (s *Server) appsNamespace(host string) string {
- domain := strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))
- if domain == "" {
- return ""
- }
- rest, ok := strings.CutSuffix(host, "."+domain)
- if !ok || rest == "" {
- return ""
+func (s *Server) appsNamespace(v namespaceView, host string) (owner string, known bool) {
+ label, _ := s.appsLabel(host)
+ if label == "" {
+ return "", true
}
- label := rest[strings.LastIndex(rest, ".")+1:]
- if !domains.ValidSqid(label) {
- return ""
- }
- return label
+ return v.labelOwner(label)
}
// otherAccountsNamespace reports whether host is in ANOTHER account's
@@ -183,11 +190,25 @@ func (s *Server) appsNamespace(host string) string {
//
// A lookup failure refuses: the cost of a false refusal is a retry, and the
// cost of a false admission is another tenant's address.
-func (s *Server) otherAccountsNamespace(host, account string) bool {
- label := s.appsNamespace(host)
- if label == "" || label == account {
+//
+// A name another account holds (account subdomains §4.5) is that account's
+// namespace exactly as its sqid is, and needs no lookup: the view says whose
+// it is. A name whose claim did not read is held by an account nobody can
+// name, so it is refused to everyone. A removed name stops protecting at
+// once, on the next request's view.
+func (s *Server) otherAccountsNamespace(v namespaceView, host, account string) bool {
+ owner, known := s.appsNamespace(v, host)
+ if !known {
+ return true
+ }
+ if owner == "" || owner == account {
return false
}
+ label, _ := s.appsLabel(host)
+ if v.byName[label] != "" {
+ return true // another account's held name
+ }
+ // Otherwise owner is the sqid-shaped label itself.
if s.store == nil {
return true // no account table to ask: refuse, as on a lookup failure
}
@@ -215,34 +236,35 @@ func (s *Server) otherAccountsNamespace(host, account string) bool {
//
// Labels that could never be a sqid are left alone here: parentsFor derives
// no parent from them, so a first route under one costs one ordinary
-// per-host certificate, as any custom domain does.
-func (s *Server) firstRouteOutsideNamespace(host, account string) bool {
- domain := strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))
- if domain == "" {
- return false
- }
- rest, ok := strings.CutSuffix(host, "."+domain)
- if !ok || !strings.Contains(rest, ".") {
+// per-host certificate, as any custom domain does. (Under account
+// subdomains' choice B, createRefusal refuses every new host under a label
+// that is not the account's before this is asked; this keeps its own rule.)
+//
+// A held name is a namespace like a sqid (account subdomains §4.5): another
+// account's name refuses, and so does one whose claim did not read.
+func (s *Server) firstRouteOutsideNamespace(v namespaceView, host, account string) bool {
+ if _, depth := s.appsLabel(host); depth < 2 {
return false
}
- label := s.appsNamespace(host)
- return label != "" && label != account
+ owner, known := s.appsNamespace(v, host)
+ return !known || (owner != "" && owner != account)
}
// domainProofExempt reports whether account's claim on host needs no TXT
// proof, because the platform, not a customer zone, answers for the name:
-// the account's own namespace under the apps domain, and the one-label names
-// an operator delegated to it (CONSOLE_APPS_DOMAIN_ALIAS_ACCOUNTS). Neither
-// has a zone the member could publish a record in, and both were already
-// settled as this account's by the deployment's own config.
-func (s *Server) domainProofExempt(host, account string) bool {
- if s.appsNamespace(host) == account && account != "" {
+// the account's own namespace under the apps domain (its sqid, or a name it
+// holds, account subdomains §4.5), and the one-label names an operator
+// delegated to it (CONSOLE_APPS_DOMAIN_ALIAS_ACCOUNTS). None has a zone the
+// member could publish a record in, and all were already settled as this
+// account's by the deployment's own config or its operator.
+func (s *Server) domainProofExempt(v namespaceView, host, account string) bool {
+ if owner, known := s.appsNamespace(v, host); known && owner == account && account != "" {
return true
}
// A platform hostname (#209) is in the deployment's own zones: only a
// platform operator gets past the door to attach one, and its zone is
// the operator's, so the operator's say-so is the proof.
- if s.domainHostPolicy(host, account) == hostPlatform {
+ if s.domainHostPolicy(v, host, account) == hostPlatform {
return true
}
return domains.ValidSqid(account) && slices.Contains(s.cfg.AppsDomainAliasAccounts, account) && s.directAppsDomainHost(host)
@@ -275,9 +297,9 @@ func (s *Server) domainChallenge(host, account string) dnsRecord {
// With DomainProof off (the default) every attach is proven by definition,
// so claims are written verified and the resolver is never asked: the
// behaviour this door had before #215.
-func (s *Server) domainProver(ctx context.Context, host, account string) func() bool {
+func (s *Server) domainProver(ctx context.Context, v namespaceView, host, account string) func() bool {
return func() bool {
- if !s.cfg.DomainProof || s.domainProofExempt(host, account) {
+ if !s.cfg.DomainProof || s.domainProofExempt(v, host, account) {
return true
}
want := domains.ChallengeToken(s.challengeDeployment(), account, host)
diff --git a/internal/console/domainproof_test.go b/internal/console/domainproof_test.go
index 1b6ad7993..e93edb327 100644
--- a/internal/console/domainproof_test.go
+++ b/internal/console/domainproof_test.go
@@ -423,3 +423,45 @@ func TestDeletedAccountsNamespaceStaysReserved(t *testing.T) {
t.Error("a deleted account's namespace is attachable")
}
}
+
+// An account's own subdomain is its namespace as its sqid is (account
+// subdomains §4.5): proof-exempt for it, another account's namespace for
+// everyone else.
+func TestOwnSubdomainNeedsNoProof(t *testing.T) {
+ fx, acct := attachFixture(t)
+ fx.srv.cfg.DomainProof = true
+ shipVersion(t, fx, "story", "v1")
+ seedChannel(t, fx, "story", "canary/live", "v1")
+ lookups := 0
+ fx.srv.lookupTXT = noTXT(&lookups)
+ if _, err := domains.AttachAccountNamespace(context.Background(), fx.rel, "harbour", "oncarlos.com", fx.sqid, "2026-11-11T00:00:00Z", "ops@example.com"); err != nil {
+ t.Fatal(err)
+ }
+ v, err := fx.srv.loadNamespaces(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ host := "blog.harbour.oncarlos.com"
+ if !fx.srv.domainProofExempt(v, host, fx.sqid) {
+ t.Error("the account's own name is not proof-exempt")
+ }
+ if fx.srv.domainProofExempt(v, host, "bdq") {
+ t.Error("another account's name is proof-exempt for bdq")
+ }
+ if !fx.srv.otherAccountsNamespace(v, host, "bdq") || fx.srv.otherAccountsNamespace(v, host, fx.sqid) {
+ t.Error("otherAccountsNamespace does not treat harbour as the fixture account's namespace")
+ }
+ if !fx.srv.firstRouteOutsideNamespace(v, host, "bdq") || fx.srv.firstRouteOutsideNamespace(v, host, fx.sqid) {
+ t.Error("firstRouteOutsideNamespace does not treat harbour as a namespace")
+ }
+ res, ref := fx.srv.attachDomain(context.Background(), acct, "story", host, "", "", "paul@keymail.dev")
+ if ref != nil {
+ t.Fatalf("attach under the account's own name refused %+v", ref)
+ }
+ if res.Pending || !res.FirstRoute {
+ t.Errorf("attach under the account's own name = %+v, want a verified first route", res)
+ }
+ if lookups != 0 {
+ t.Errorf("TXT lookups = %d, want none: the account's own name needs no proof", lookups)
+ }
+}
diff --git a/internal/console/lifetimes_store.go b/internal/console/lifetimes_store.go
index 55b48024c..1832683cd 100644
--- a/internal/console/lifetimes_store.go
+++ b/internal/console/lifetimes_store.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"math"
+ "strings"
"time"
"github.com/carlosframework/platform/internal/provision"
@@ -197,6 +198,30 @@ func (s *Store) PendingAllocations() ([]Allocation, error) {
return s.allocations(`state = ?`, lifetimePending)
}
+// PendingAllocationsUnder lists the pending allocations whose host is
+// suffix or ends in "."+suffix, oldest first (account subdomains §4.2: a
+// console create persists its allocation before its record, and recovery
+// writes the record later without a door, so the walk of what lives under
+// a name must see allocations too). Filtered here rather than with LIKE,
+// whose wildcards a hostname could carry. An empty suffix is refused
+// rather than read as "every host".
+func (s *Store) PendingAllocationsUnder(suffix string) ([]Allocation, error) {
+ if suffix == "" {
+ return nil, errors.New("console: pending allocations under no suffix")
+ }
+ all, err := s.PendingAllocations()
+ if err != nil {
+ return nil, err
+ }
+ var out []Allocation
+ for _, a := range all {
+ if a.Host == suffix || strings.HasSuffix(a.Host, "."+suffix) {
+ out = append(out, a)
+ }
+ }
+ return out, nil
+}
+
// PendingLifetimesForApp lists the pending allocations of one app.
func (s *Store) PendingLifetimesForApp(account, app string) ([]Allocation, error) {
return s.allocations(`state = ? AND account = ? AND app = ?`, lifetimePending, account, app)
diff --git a/internal/console/plancaps.go b/internal/console/plancaps.go
index e00583fd3..351bb39ce 100644
--- a/internal/console/plancaps.go
+++ b/internal/console/plancaps.go
@@ -246,8 +246,12 @@ func (s *Server) planLock(acct *Account) func() {
// free plan may not attach: an open host outside the deployment's apps
// domain. The account's own <sqid>.<apps-domain> addresses and the
// operator's platform zones are not custom domains.
+//
+// The zero namespace view (sqids and config only): every host under the
+// apps domain is not a custom domain whatever its label, so held names
+// cannot change the answer.
func (s *Server) customDomain(host, account string) bool {
- if s.domainHostPolicy(host, account) != hostOpen {
+ if s.domainHostPolicy(namespaceView{}, host, account) != hostOpen {
return false
}
if domain := strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain)); domain != "" && strings.HasSuffix(host, "."+domain) {
diff --git a/internal/console/regional_writers_test.go b/internal/console/regional_writers_test.go
index 9c6e68593..533c8e47b 100644
--- a/internal/console/regional_writers_test.go
+++ b/internal/console/regional_writers_test.go
@@ -256,7 +256,7 @@ func TestFirstRouteAttachOnARegionalHostWritesNoRecord(t *testing.T) {
if err != nil || acct == nil {
t.Fatalf("account bab: %v", err)
}
- _, ref := fx.srv.attachClaimFirstRoute(context.Background(), acct, ltApp, ltDomain, "stable", "paul@keymail.dev")
+ _, ref := fx.srv.attachClaimFirstRoute(context.Background(), namespaceView{}, 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)
}
diff --git a/internal/console/subdomain_copy.go b/internal/console/subdomain_copy.go
new file mode 100644
index 000000000..df29ffd03
--- /dev/null
+++ b/internal/console/subdomain_copy.go
@@ -0,0 +1,45 @@
+package console
+
+// Approved copy for account subdomains (docs/superpowers/plans/
+// 2026-11-11-account-subdomains-copy.json, the entries whose File is this
+// file). Byte for byte the record's Text: change the record and this file
+// together, never one alone. Each constant names its record ID.
+//
+// The refuse.create.* strings are the host-creating doors' answers (spec
+// §4.2, choice B: the label under the apps domain is platform-owned); the
+// rest are the assignment door's (Task 6) and are not wired yet.
+
+const (
+ // refuse.shape
+ subdomainRefuseShapeCopy = "%q cannot be a subdomain. use lowercase letters, digits and hyphens, up to 63 characters, and do not start or end with a hyphen"
+ // refuse.sqid_shaped
+ subdomainRefuseSqidShapedCopy = "%q could be another account's own label later. pick a name with 7 or more letters, or with i, l, o, a digit or a hyphen in it"
+ // refuse.reserved
+ subdomainRefuseReservedCopy = "%q is kept for the platform. pick another name"
+ // refuse.held
+ subdomainRefuseHeldCopy = "%q is taken. pick another name"
+ // refuse.infrastructure
+ subdomainRefuseInfrastructureCopy = "%q would conflict with an address this deployment uses. pick another name"
+ // refuse.occupied
+ subdomainRefuseOccupiedCopy = "other accounts already have hosts under %s:"
+ // refuse.has_one
+ subdomainRefuseHasOneCopy = "account %s already has the subdomain %s. remove it first to change it"
+ // refuse.unreadable
+ subdomainRefuseUnreadableCopy = "could not check which accounts hold names under %s. nothing changed. try again"
+ // refuse.rolled_back
+ subdomainRefuseRolledBackCopy = "something else appeared under %s while it was being set. the subdomain was not set:"
+ // refuse.rollback_failed
+ subdomainRefuseRollbackFailedCopy = "could not undo the change, so %s is still held by account %s. run `carlos accounts subdomain remove --account %s`"
+ // refuse.remove_blocked
+ subdomainRefuseRemoveBlockedCopy = "account %s still has hosts under %s. detach them first:"
+ // refuse.not_operator
+ subdomainRefuseNotOperatorCopy = "only a platform operator can change subdomains"
+ // refuse.host_claims
+ subdomainRefuseHostClaimsCopy = "subdomains cannot be changed while host claims are on"
+ // refuse.create.unassigned
+ subdomainCreateUnassignedCopy = "nothing can be added under %s until an account has that subdomain. ask a platform operator to assign it to this account"
+ // refuse.create.other_account
+ subdomainCreateOtherAccountCopy = "%s belongs to another account"
+ // refuse.create.unreadable
+ subdomainCreateUnreadableCopy = "could not check which account holds %s. try again"
+)
diff --git a/internal/console/subdomains.go b/internal/console/subdomains.go
new file mode 100644
index 000000000..1012b85ca
--- /dev/null
+++ b/internal/console/subdomains.go
@@ -0,0 +1,464 @@
+package console
+
+// Account subdomains in the console (spec docs/superpowers/specs/
+// 2026-11-11-account-subdomains-design.md §4.2, §4.3 and §4.5).
+//
+// Under Paul's choice B (rev 3) the label directly under the apps domain is
+// platform-owned. A new host two or more labels under the apps domain, or a
+// one-label host L.<apps> whose claim gains coverage below it, may only be
+// created when L is the creator's own sqid or a subdomain it holds. Every
+// console door that creates such a host asks createRefusal; the doors that
+// already asked domainHostPolicy keep doing so, and its
+// otherAccountsNamespace now knows held names as well as sqids.
+//
+// The rule only refuses new hosts. Re-attaching or changing a claim an
+// account already holds (without new coverage) is not a create, so hosts
+// made before the rule keep working.
+//
+// namespaceView is read once per request (loadNamespaces, one claim
+// listing through the claim cache). A namespace claim that is listed but
+// does not read counts as held by an unknown account: creating under that
+// label is refused for everyone, and assigning that name is refused, until
+// the read succeeds.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "slices"
+ "sort"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// namespaceView is the account namespaces in force under the apps domain,
+// as one claim listing showed them: byName maps a held name to its
+// account's sqid, byAccount a sqid to its name (domains.AccountNamespaces),
+// and unread holds the names whose namespace claim was listed but could not
+// be trusted this read. The zero value holds no names, which is what a door
+// that decides from sqids alone (detach, paths) passes.
+type namespaceView struct {
+ byName map[string]string
+ byAccount map[string]string
+ unread map[string]bool
+}
+
+// labelOwner is the account whose namespace label, one label directly under
+// the apps domain, is: a name some account holds → that account; a
+// sqid-shaped label → the label itself (whether or not an account holds it,
+// which is otherAccountsNamespace's question); a name whose claim did not
+// read → ("", false), held by an account nobody can name. Anything else is
+// nobody's: ("", true).
+//
+// The held name is asked first: a name may be a 7-letter frozen-alphabet
+// word (§4.2 rule 2 allows it), and while it is held it is that account's.
+func (v namespaceView) labelOwner(label string) (owner string, known bool) {
+ if v.unread[label] {
+ return "", false
+ }
+ if acct, ok := v.byName[label]; ok {
+ return acct, true
+ }
+ if domains.ValidSqid(label) {
+ return label, true
+ }
+ return "", true
+}
+
+// loadNamespaces reads the namespace view: one ListWithUnread through the
+// console's claim cache. A claim at the key of a label that can never be a
+// name (one SubdomainRuleRefusal refuses, a short sqid-shaped label above
+// all) is left out, read or not. Strict where it matters: a claim with
+// AccountNamespace set at a namespace host that AccountNamespaces does not
+// trust (pending, carrying anything but the namespace, an invalid account)
+// counts as unread rather than as no name, and so does any claim at a
+// namespace host whose body did not read (it may be a namespace claim). A
+// listing that fails is an error; the caller decides what that means (a
+// door refuses, a display site shows hosts unchanged).
+func (s *Server) loadNamespaces(ctx context.Context) (namespaceView, error) {
+ domain := s.appsDomain()
+ if domain == "" {
+ return namespaceView{}, nil
+ }
+ if s.cfg.Releases == nil {
+ return namespaceView{}, errors.New("console: namespaces: no deployment bucket")
+ }
+ claims, unread, err := s.claims.ListWithUnread(ctx, s.cfg.Releases)
+ if err != nil {
+ return namespaceView{}, fmt.Errorf("console: namespaces: %w", err)
+ }
+ // Only a label that could ever be a name counts (SubdomainRuleRefusal:
+ // the shape, the reserved labels, the sqid-shaped floor). The door
+ // refuses every other one, so a claim at such a key is a direct bucket
+ // write, and it must never make another account's sqid label, bdq in
+ // *.bdq.<apps>, someone's name: the sqid stays its own account's.
+ nameable := func(name string) bool { return domains.SubdomainRuleRefusal(name) == "" }
+ var kept []domains.Claim
+ for _, c := range claims {
+ if name, ok := domains.ParseNamespaceHost(c.Host, domain); !ok || nameable(name) {
+ kept = append(kept, c)
+ }
+ }
+ v := namespaceView{unread: map[string]bool{}}
+ v.byName, v.byAccount = domains.AccountNamespaces(kept, domain)
+ for _, u := range unread {
+ if name, ok := domains.ParseNamespaceHost(u.Host, domain); ok && nameable(name) {
+ v.unread[name] = true
+ }
+ }
+ for _, c := range kept {
+ if !c.AccountNamespace {
+ continue
+ }
+ if name, ok := domains.ParseNamespaceHost(c.Host, domain); ok {
+ if _, held := v.byName[name]; !held {
+ v.unread[name] = true
+ }
+ }
+ }
+ return v, nil
+}
+
+// appsDomain is the deployment's apps domain, normalized.
+func (s *Server) appsDomain() string {
+ return strings.ToLower(strings.TrimSpace(s.cfg.AppsDomain))
+}
+
+// appsLabel is the label directly under the apps domain that host is at or
+// under, and how many labels host has under the apps domain: ("bdq", 2) for
+// shop.bdq.<apps>, ("bdq", 1) for bdq.<apps>. ("", 0) when host is not
+// under the apps domain (the apps domain itself included), or there is
+// none.
+func (s *Server) appsLabel(host string) (label string, depth int) {
+ domain := s.appsDomain()
+ if domain == "" {
+ return "", 0
+ }
+ rest, ok := strings.CutSuffix(host, "."+domain)
+ if !ok || rest == "" {
+ return "", 0
+ }
+ return rest[strings.LastIndex(rest, ".")+1:], strings.Count(rest, ".") + 1
+}
+
+// createKind says what a door's write would create.
+type createKind int
+
+const (
+ // createNewHost: a new claim, record or route at host.
+ createNewHost createKind = iota + 1
+ // createExpandsCoverage: a claim on host turns Catchall from false to
+ // true (Wildcard+Catchall), so new names below host would serve.
+ createExpandsCoverage
+)
+
+// createRefusal reports whether account may NOT create host: true unless the
+// label directly under the apps domain is account's sqid or a name account
+// holds. It applies to a host two or more labels under the apps domain, to a
+// one-label host L.<apps> whose claim gains coverage below it
+// (createExpandsCoverage), and to an instance catch-all "*.L.<apps>" or
+// deeper, whose host the caller passes as written. Anything else, and
+// anything outside the apps domain, is not this rule's.
+//
+// The door decides kind, and whether to ask at all, from the claim it has
+// read: re-attaching or changing a claim the account already holds without
+// new coverage is not a create (namespaceCreateRefusal). An unread label
+// refuses everyone.
+func (s *Server) createRefusal(v namespaceView, host, account string, kind createKind) bool {
+ h, star := strings.CutPrefix(host, "*.")
+ label, depth := s.appsLabel(h)
+ if label == "" {
+ return false
+ }
+ if depth == 1 && !star && kind != createExpandsCoverage {
+ return false
+ }
+ owner, known := v.labelOwner(label)
+ return !known || account == "" || owner != account
+}
+
+// createDoorRefusal is the answer to a create createRefusal refused, in the
+// approved copy, naming <label>.<apps>: the retryable answer when the
+// label's claim did not read; the other-account answer when another account
+// holds the label as a name, or as its sqid (live or deleted,
+// AccountAnyBySqid, the lookup otherAccountsNamespace makes); and otherwise
+// the answer naming the fix (an operator assigns the label). A sqid-shaped
+// label no account has held is nobody's, so it gets that last answer. The
+// text never names the other account. Only the refusal path pays the
+// lookup.
+func (s *Server) createDoorRefusal(v namespaceView, host, account string) *doorRefusal {
+ label, _ := s.appsLabel(strings.TrimPrefix(host, "*."))
+ where := label + "." + s.appsDomain()
+ unreadable := &doorRefusal{Status: http.StatusBadGateway, Msg: fmt.Sprintf(subdomainCreateUnreadableCopy, where)}
+ other := &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: fmt.Sprintf(subdomainCreateOtherAccountCopy, where)}
+ owner, known := v.labelOwner(label)
+ switch {
+ case !known:
+ return unreadable
+ case owner == "" || owner == account:
+ case v.byName[label] != "":
+ return other
+ case s.store == nil:
+ return unreadable
+ default:
+ a, _, err := s.store.AccountAnyBySqid(owner)
+ if err != nil {
+ log.Printf("console: namespace: account lookup for %s: %v", where, err)
+ return unreadable
+ }
+ if a != nil {
+ return other
+ }
+ }
+ return &doorRefusal{Status: http.StatusUnprocessableEntity, Msg: fmt.Sprintf(subdomainCreateUnassignedCopy, where)}
+}
+
+// namespaceCreateRefusal is a door's decision for a write at host, given
+// the claim the door read there (nil when there is none). A claim account
+// already holds at host is not a new host, whoever's label it sits under;
+// wantCatchall asks for coverage below host, which only a claim that has it
+// on already does not add. nil means the write may go ahead as far as the
+// namespace is concerned.
+func (s *Server) namespaceCreateRefusal(v namespaceView, host, account string, cur *domains.Claim, wantCatchall bool) *doorRefusal {
+ held := cur != nil && cur.Account == account
+ if !held && s.createRefusal(v, host, account, createNewHost) {
+ return s.createDoorRefusal(v, host, account)
+ }
+ if wantCatchall && !(held && cur.Catchall) && s.createRefusal(v, host, account, createExpandsCoverage) {
+ return s.createDoorRefusal(v, host, account)
+ }
+ return nil
+}
+
+// attachCreateRefusal is namespaceCreateRefusal for the attach doors, which
+// hold no claim read of their own at this point: it reads host's claim only
+// when the label is not the account's, so the common case (the account's
+// own sqid, or a host outside the apps domain) costs nothing. A read that
+// fails refuses, retryably.
+//
+// The read and the attach's create-only write are not one step. The only
+// claim that admits here is one the account already holds, so what can slip
+// between them is that same account detaching it and the attach writing it
+// back: a host the account held a moment before.
+func (s *Server) attachCreateRefusal(ctx context.Context, v namespaceView, host, account string, wantCatchall bool) *doorRefusal {
+ if !s.createRefusal(v, host, account, createNewHost) &&
+ !(wantCatchall && s.createRefusal(v, host, account, createExpandsCoverage)) {
+ return nil
+ }
+ cur, err := domains.GetClaim(ctx, s.cfg.Releases, host)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ cur = nil
+ case err != nil:
+ log.Printf("console: namespace: claim read for %s: %v", host, err)
+ label, _ := s.appsLabel(host)
+ return &doorRefusal{Status: http.StatusBadGateway, Msg: fmt.Sprintf(subdomainCreateUnreadableCopy, label+"."+s.appsDomain())}
+ }
+ return s.namespaceCreateRefusal(v, host, account, cur, wantCatchall)
+}
+
+// doorNamespaces loads the view for a door that may create host. A host
+// outside the apps domain needs no view: the zero one comes back and
+// nothing is listed. Under the apps domain, a listing that fails refuses
+// (every attach or create there, the account's own sqid included), and so
+// does a host under a label whose namespace claim did not read; both with
+// the retryable answer.
+func (s *Server) doorNamespaces(ctx context.Context, host string) (namespaceView, *doorRefusal) {
+ domain := s.appsDomain()
+ h := strings.TrimPrefix(host, "*.")
+ if domain == "" || (h != domain && !strings.HasSuffix(h, "."+domain)) {
+ return namespaceView{}, nil
+ }
+ label, _ := s.appsLabel(h)
+ where := domain
+ if label != "" {
+ where = label + "." + domain
+ }
+ v, err := s.loadNamespaces(ctx)
+ if err != nil {
+ log.Printf("console: namespace: %s: %v — refusing", host, err)
+ return namespaceView{}, &doorRefusal{Status: http.StatusBadGateway, Msg: fmt.Sprintf(subdomainCreateUnreadableCopy, where)}
+ }
+ if label != "" && v.unread[label] {
+ return v, &doorRefusal{Status: http.StatusBadGateway, Msg: fmt.Sprintf(subdomainCreateUnreadableCopy, where)}
+ }
+ return v, nil
+}
+
+// occupant is one thing that lives at or under a name: a claim, an instance
+// record, or a pending allocation (a console create whose record is not
+// written yet, which recovery writes later without a door).
+type occupant struct{ Host, Account, App, Source string }
+
+// The occupant sources.
+const (
+ occupantClaim = "claim"
+ occupantRecord = "record"
+ occupantAllocation = "pending allocation"
+)
+
+// namespaceOccupants walks everything at or under <name>.<apps>: claims
+// (the one-label apex included; the name's own namespace claim is the name,
+// not an occupant), declared instance records (provision.RecordHostDeclared
+// Under, ownership from the key) and pending allocations. Strict: a listing
+// that fails, a claim at or under the name that did not read, or a record
+// walk that is incomplete is an error, never a shorter list. Assignment, its
+// re-read after the write, show and remove all use this one walk. Sorted by
+// host, then account, app and source.
+func (s *Server) namespaceOccupants(ctx context.Context, name string) ([]occupant, error) {
+ domain := s.appsDomain()
+ if domain == "" {
+ return nil, errors.New("console: namespace occupants: no apps domain")
+ }
+ if s.cfg.Releases == nil {
+ return nil, errors.New("console: namespace occupants: no deployment bucket")
+ }
+ if s.store == nil {
+ return nil, errors.New("console: namespace occupants: no console store")
+ }
+ root := name + "." + domain
+ under := func(host string) bool {
+ host = strings.TrimPrefix(host, "*.")
+ return host == root || strings.HasSuffix(host, "."+root)
+ }
+ self := domains.NamespaceHost(name, domain)
+ claims, unread, err := s.claims.ListWithUnread(ctx, s.cfg.Releases)
+ if err != nil {
+ return nil, fmt.Errorf("console: namespace occupants: %w", err)
+ }
+ for _, u := range unread {
+ if under(u.Host) {
+ return nil, fmt.Errorf("console: namespace occupants: claim %s could not be read", u.Host)
+ }
+ }
+ var out []occupant
+ for _, c := range claims {
+ if !under(c.Host) || (c.AccountNamespace && c.Host == self) {
+ continue
+ }
+ out = append(out, occupant{Host: c.Host, Account: c.Account, App: c.App, Source: occupantClaim})
+ }
+ records, err := provision.RecordHostDeclaredUnder(ctx, s.cfg.Releases, root)
+ if err != nil {
+ return nil, fmt.Errorf("console: namespace occupants: %w", err)
+ }
+ for _, r := range records {
+ out = append(out, occupant{Host: r.Host, Account: r.Account, App: r.App, Source: occupantRecord})
+ }
+ pending, err := s.store.PendingAllocationsUnder(root)
+ if err != nil {
+ return nil, fmt.Errorf("console: namespace occupants: pending allocations: %w", err)
+ }
+ for _, a := range pending {
+ out = append(out, occupant{Host: a.Host, Account: a.Account, App: a.App, Source: occupantAllocation})
+ }
+ sort.Slice(out, func(i, j int) bool {
+ a, b := out[i], out[j]
+ if a.Host != b.Host {
+ return a.Host < b.Host
+ }
+ if a.Account != b.Account {
+ return a.Account < b.Account
+ }
+ if a.App != b.App {
+ return a.App < b.App
+ }
+ return a.Source < b.Source
+ })
+ return out, nil
+}
+
+// subdomainInfrastructure reports whether the deployment stands on name
+// (§4.2 rule 4): <name>.<apps>, or anything at or below it, is denied by the
+// reserved tier with only its one synthetic apps-domain entry removed
+// (ReservePlatformDomains lists the whole apps domain, which would refuse
+// every name), or by the platform tier; or a reserved or deny entry, a
+// console host (exact), the demo domain or the demo API origin sits at or
+// below <name>.<apps>. An operator deny entry that names the apps domain or
+// an ancestor stays, and refuses every name. With no apps domain there is
+// nowhere for a name to live, and the answer is true.
+func (s *Server) subdomainInfrastructure(name string) bool {
+ domain := s.appsDomain()
+ if domain == "" {
+ return true
+ }
+ root := name + "." + domain
+ reserved := s.reservedDomainsWith(false, false)
+ platform := s.platformDomains(false)
+ if domains.HostDenied(root, reserved) || domains.HostDenied(root, platform) || s.demoDomainReserved(root) {
+ return true
+ }
+ atOrBelow := func(entry string) bool {
+ entry = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(entry)), ".")
+ return entry != "" && (entry == root || strings.HasSuffix(entry, "."+root))
+ }
+ entries := slices.Concat(reserved, platform, s.consoleHosts(), s.cfg.DenyDomains,
+ []string{s.cfg.Demo.Domain, strings.TrimPrefix(s.cfg.DemoAPIOrigin, "https://")})
+ return slices.ContainsFunc(entries, atOrBelow)
+}
+
+// subdomainRefusal applies every §4.2 rule to account taking name, in the
+// spec's order after the store-free rules: a held sqid (live or deleted),
+// another account's name or a name whose claim did not read, the
+// deployment's own hosts, an account that already holds another name, and
+// anything another account has at or under the name (SubdomainOccupied,
+// with those occupants). A read that fails is SubdomainUnreadable. "" means
+// allowed; the account's own name asked again is allowed (the door makes it
+// idempotent).
+//
+// Under choice B a console-made route comes from a claim, a record or an
+// allocation, all of which the walk sees, so routes are not folded in.
+// name is expected normalized (domains.NormalizeSubdomain); anything else
+// is refused for shape.
+func (s *Server) subdomainRefusal(ctx context.Context, v namespaceView, account, name string) (domains.SubdomainRefusal, []occupant) {
+ if r := domains.SubdomainRuleRefusal(name); r != "" {
+ return r, nil
+ }
+ // Rule 1: a sqid an account holds, live or deleted. Only a 7+ letter
+ // sqid reaches here (shorter ones are rule 2's).
+ if domains.ValidSqid(name) {
+ if s.store == nil {
+ return domains.SubdomainUnreadable, nil
+ }
+ a, _, err := s.store.AccountAnyBySqid(name)
+ if err != nil {
+ log.Printf("console: subdomain %s: account lookup: %v", name, err)
+ return domains.SubdomainUnreadable, nil
+ }
+ if a != nil {
+ return domains.SubdomainHeld, nil
+ }
+ }
+ switch owner, known := v.labelOwner(name); {
+ case !known:
+ return domains.SubdomainUnreadable, nil
+ case owner != "" && owner != account && v.byName[name] != "":
+ return domains.SubdomainHeld, nil
+ }
+ if s.subdomainInfrastructure(name) {
+ return domains.SubdomainInfrastructure, nil
+ }
+ if have, ok := v.byAccount[account]; ok && have != name {
+ return domains.SubdomainAccountHasOne, nil
+ }
+ occupants, err := s.namespaceOccupants(ctx, name)
+ if err != nil {
+ log.Printf("console: subdomain %s: %v", name, err)
+ return domains.SubdomainUnreadable, nil
+ }
+ var foreign []occupant
+ for _, o := range occupants {
+ if o.Account != account {
+ foreign = append(foreign, o)
+ }
+ }
+ if len(foreign) > 0 {
+ return domains.SubdomainOccupied, foreign
+ }
+ return "", nil
+}
diff --git a/internal/console/subdomains_test.go b/internal/console/subdomains_test.go
new file mode 100644
index 000000000..ed13f0873
--- /dev/null
+++ b/internal/console/subdomains_test.go
@@ -0,0 +1,702 @@
+package console
+
+// Account subdomains, Task 5 (spec docs/superpowers/specs/
+// 2026-11-11-account-subdomains-design.md §4.2 and §4.5, Paul's choice B):
+// the label directly under the apps domain is platform-owned. A new host two
+// or more labels under it, or a one-label host whose claim gains coverage
+// below it, may only be created under the creator's own sqid or a name it
+// holds, at every console door. Hosts and claims an account already holds
+// keep working.
+//
+// The fixture account is the ops account (fx.sqid, bab); bdq and bcd are the
+// other accounts.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const nsApps = "oncarlos.com"
+
+// nsAccount creates the account whose sqid is Sqid(id), with its bucket
+// manifest, so the record walk knows it too.
+func nsAccount(t *testing.T, fx *consoleFixture, id int64, sqid string) {
+ t.Helper()
+ if domains.Sqid(id) != sqid {
+ t.Fatalf("Sqid(%d) = %s, not %s", id, domains.Sqid(id), sqid)
+ }
+ if err := fx.st.CreateAccount(id, sqid, "Other "+sqid, sqid+"@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ body, err := json.Marshal(domains.AccountManifest{ID: id, Sqid: sqid, Name: "Other " + sqid, CreatedAt: time.Now().UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ putFixtureObject(t, fx.rel, domains.AccountManifestKey(sqid), body)
+}
+
+// nsHold gives account the subdomain name, as the Task 6 door will.
+func nsHold(t *testing.T, fx *consoleFixture, name, account string) {
+ t.Helper()
+ created, err := domains.AttachAccountNamespace(context.Background(), fx.rel, name, nsApps, account,
+ time.Now().UTC().Format(time.RFC3339), "ops@example.com")
+ if err != nil || !created {
+ t.Fatalf("hold %s for %s: created %v, %v", name, account, created, err)
+ }
+}
+
+// nsRelease takes the name back from account.
+func nsRelease(t *testing.T, fx *consoleFixture, name, account string) {
+ t.Helper()
+ _, etag, err := fx.rel.Get(context.Background(), domains.ClaimKey(domains.NamespaceHost(name, nsApps)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ removed, err := domains.DetachAccountNamespaceAt(context.Background(), fx.rel, name, nsApps, account, etag)
+ if err != nil || !removed {
+ t.Fatalf("release %s: removed %v, %v", name, removed, err)
+ }
+}
+
+func nsView(t *testing.T, s *Server) namespaceView {
+ t.Helper()
+ v, err := s.loadNamespaces(context.Background())
+ if err != nil {
+ t.Fatalf("loadNamespaces: %v", err)
+ }
+ return v
+}
+
+func noClaim(t *testing.T, fx *consoleFixture, host string) {
+ t.Helper()
+ if _, err := domains.GetClaim(context.Background(), fx.rel, host); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("a claim at %s (err %v); the door wrote one", host, err)
+ }
+}
+
+// nsFaultStore fails one listing prefix and one key's reads. It embeds
+// release.Store only, so the claim cache takes its plain List path.
+type nsFaultStore struct {
+ release.Store
+ failList string
+ failGet string
+}
+
+func (s *nsFaultStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if s.failList != "" && prefix == s.failList {
+ return nil, errors.New("nsFaultStore: listing refused")
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func (s *nsFaultStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if s.failGet != "" && key == s.failGet {
+ return nil, "", errors.New("nsFaultStore: read refused")
+ }
+ return s.Store.Get(ctx, key)
+}
+
+// TestSubdomainRefusalRules: one row per §4.2 reason subdomainRefusal
+// answers, and an allowed name. SubdomainRolledBack is the assignment
+// door's own answer after its re-read (Task 6), not a rule.
+func TestSubdomainRefusalRules(t *testing.T) {
+ fx, _ := attachFixture(t)
+ fx.srv.cfg.DenyDomains = []string{"monitor." + nsApps}
+ ctx := context.Background()
+ nsAccount(t, fx, 82, "bdq")
+ nsAccount(t, fx, 49, "bcd")
+ // Live and deleted accounts whose sqids are 7 letters: no name may be
+ // either (rule 1).
+ if err := fx.st.CreateAccount(7001, "bcdfghj", "Live", "live@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.CreateAccount(7002, "bcdfghk", "Gone", "gone@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.DeleteAccount(7002, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ nsHold(t, fx, "harbour", "bcd")
+ nsHold(t, fx, "pier", "bdq")
+ // bcd has a host under marina; the fixture account has one too, which
+ // is never another account's occupant.
+ seedClaim(t, fx, domains.Claim{Schema: 1, Host: "blog.marina." + nsApps, Account: "bcd", App: "shop", CreatedAt: "2026-11-11T00:00:00Z"})
+ seedClaim(t, fx, domains.Claim{Schema: 1, Host: "www.marina." + nsApps, Account: fx.sqid, App: "story", CreatedAt: "2026-11-11T00:00:00Z"})
+
+ v := nsView(t, fx.srv)
+ unread := v
+ unread.unread = map[string]bool{"marketx": true}
+
+ for _, c := range []struct {
+ why, name, account string
+ v namespaceView
+ want domains.SubdomainRefusal
+ occupants []occupant
+ }{
+ {"shape", "-harbour", "bdq", v, domains.SubdomainShape, nil},
+ {"could become a sqid", "bcdf", "bdq", v, domains.SubdomainSqidShaped, nil},
+ {"reserved label", "www", "bdq", v, domains.SubdomainReserved, nil},
+ {"a live account's sqid", "bcdfghj", "bdq", v, domains.SubdomainHeld, nil},
+ {"a deleted account's sqid", "bcdfghk", "bdq", v, domains.SubdomainHeld, nil},
+ {"another account's name", "harbour", "bdq", v, domains.SubdomainHeld, nil},
+ {"a name whose claim did not read", "marketx", "bdq", unread, domains.SubdomainUnreadable, nil},
+ {"the deployment stands on it", "monitor", fx.sqid, v, domains.SubdomainInfrastructure, nil},
+ {"the account has a name already", "lighthouse", "bdq", v, domains.SubdomainAccountHasOne, nil},
+ {"another account lives there", "marina", fx.sqid, v, domains.SubdomainOccupied,
+ []occupant{{Host: "blog.marina." + nsApps, Account: "bcd", App: "shop", Source: occupantClaim}}},
+ {"allowed", "lighthouse", fx.sqid, v, "", nil},
+ {"the account's own name again", "pier", "bdq", v, "", nil},
+ } {
+ got, occ := fx.srv.subdomainRefusal(ctx, c.v, c.account, c.name)
+ if got != c.want || !reflect.DeepEqual(occ, c.occupants) {
+ t.Errorf("%s: subdomainRefusal(%s, %s) = %q %+v, want %q %+v", c.why, c.account, c.name, got, occ, c.want, c.occupants)
+ }
+ }
+}
+
+// TestSubdomainInfrastructure: rule 4 reads the reserved tier without the
+// one synthetic apps-domain entry, the platform tier, and anything reserved,
+// denied, console or demo at or below the name.
+func TestSubdomainInfrastructure(t *testing.T) {
+ for _, c := range []struct {
+ why string
+ cfg Config
+ name string
+ want bool
+ }{
+ {"the steering label", Config{}, "edge", true},
+ {"an ordinary name", Config{}, "harbour", false},
+ {"ReservePlatformDomains alone", Config{ReservePlatformDomains: true}, "harbour", false},
+ {"a deny entry naming it", Config{DenyDomains: []string{"harbour." + nsApps}}, "harbour", true},
+ {"a deny entry below it", Config{DenyDomains: []string{"admin.harbour." + nsApps}}, "harbour", true},
+ {"a deny entry below another name", Config{DenyDomains: []string{"admin.harbour." + nsApps}}, "pier", false},
+ {"the console host, reserve off", Config{Origin: "https://console." + nsApps}, "console", true},
+ {"a redirect host below it", Config{RedirectHosts: []string{"old.console." + nsApps}}, "console", true},
+ {"a deny entry naming the apps domain", Config{DenyDomains: []string{nsApps}}, "harbour", true},
+ {"a deny entry naming the apps domain", Config{DenyDomains: []string{nsApps}}, "pier", true},
+ {"the tunnel host below it", Config{TunnelHost: "hub.pier." + nsApps}, "pier", true},
+ {"a configured steering host below it", Config{SteeringHost: "steer.pier." + nsApps}, "pier", true},
+ } {
+ cfg := c.cfg
+ cfg.AppsDomain = nsApps
+ s := &Server{cfg: cfg}
+ if got := s.subdomainInfrastructure(c.name); got != c.want {
+ t.Errorf("%s: subdomainInfrastructure(%s) = %v, want %v", c.why, c.name, got, c.want)
+ }
+ }
+ // The demo domain at or below the name.
+ s := &Server{cfg: Config{AppsDomain: nsApps}}
+ s.cfg.Demo.Domain = "try.demo." + nsApps
+ if !s.subdomainInfrastructure("demo") {
+ t.Error("a demo domain under demo.<apps> does not refuse demo")
+ }
+ if s.subdomainInfrastructure("harbour") {
+ t.Error("a demo domain elsewhere refuses harbour")
+ }
+}
+
+// TestCreateUnderUnassignedLabelRefused (Review Focus 6): a self-hosted
+// operator's account adds blog.team.<apps> where team is no one's subdomain:
+// refused with the approved reason naming the fix. Once the account holds
+// the label, the same attach goes through. A claim it already held under an
+// unassigned label keeps working: re-attached, and changed.
+//
+// team is sqid-shaped (every letter is in the frozen alphabet, four
+// letters) and no account has that sqid, so it is nobody's and gets the
+// same answer as marina, which could never be a sqid. But team can never
+// be a name either (§4.2 rule 2), so "once the account holds it" is shown
+// with marina.
+func TestCreateUnderUnassignedLabelRefused(t *testing.T) {
+ fx, acct := attachFixture(t)
+ shipVersion(t, fx, "story", "v1")
+ seedChannel(t, fx, "story", "canary/live", "v1")
+ ctx := context.Background()
+
+ for _, label := range []string{"team", "marina"} {
+ host := "blog." + label + "." + nsApps
+ _, ref := fx.srv.attachDomain(ctx, acct, "story", host, "", "", "paul@keymail.dev")
+ if want := fmt.Sprintf(subdomainCreateUnassignedCopy, label+"."+nsApps); ref == nil || ref.Msg != want {
+ t.Errorf("attach %s under an unassigned label = %+v, want %q", host, ref, want)
+ }
+ noClaim(t, fx, host)
+ }
+
+ host := "blog.marina." + nsApps
+ nsHold(t, fx, "marina", fx.sqid)
+ res, ref := fx.srv.attachDomain(ctx, acct, "story", host, "", "", "paul@keymail.dev")
+ if ref != nil || !res.FirstRoute {
+ t.Fatalf("attach %s once marina is the account's = %+v %+v, want a first route", host, res, ref)
+ }
+
+ // dock is nobody's and could never be a sqid (firstRouteOutsideNamespace
+ // refuses any first route under an unheld sqid-shaped label, as it did
+ // before names). The account's existing first-route claim under it is
+ // re-attached (declaring its record), and its existing alias converges.
+ first := "x.dock." + nsApps
+ seedClaim(t, fx, domains.Claim{Schema: 1, Host: first, Account: fx.sqid, App: "story", CreatedAt: "2026-11-11T00:00:00Z"})
+ if res, ref := fx.srv.attachDomain(ctx, acct, "story", first, "", "", "paul@keymail.dev"); ref != nil || !res.FirstRoute {
+ t.Errorf("re-attach of the account's own %s = %+v %+v, want its first route", first, res, ref)
+ }
+ alias := "y.dock." + nsApps
+ seedClaim(t, fx, domains.Claim{Schema: 1, Host: alias, Account: fx.sqid, App: "story", Route: "old.story.example.com", CreatedAt: "2026-11-11T00:00:00Z"})
+ ready := "story." + fx.sqid + "." + nsApps
+ fx.srv.cfg.Registry = attachRegistry(t, registry.Route{Host: ready, Kind: "static", App: "story", Account: fx.sqid, Channel: "canary/live", Status: "ready"})
+ if _, ref := fx.srv.attachDomain(ctx, acct, "story", alias, "", "", "paul@keymail.dev"); ref != nil {
+ t.Errorf("re-pointing the account's own %s = %+v, want it changed", alias, ref)
+ }
+ if c, err := domains.GetClaim(ctx, fx.rel, alias); err != nil || c.Route != ready {
+ t.Errorf("claim %s = %+v, %v; want it pointing at %s", alias, c, err, ready)
+ }
+ // A new host beside them is still refused.
+ if _, ref := fx.srv.attachDomain(ctx, acct, "story", "z.dock."+nsApps, "", "", "paul@keymail.dev"); ref == nil {
+ t.Error("a new host under dock was accepted")
+ }
+ noClaim(t, fx, "z.dock."+nsApps)
+}
+
+// TestCreateUnderOtherAccountsNameRefused: while bdq holds harbour, every
+// console door refuses the fixture account x.harbour.<apps>, the operator's
+// platform door included. Doors that already refused another account's
+// sqid keep their text; instance create, which did not, answers with the
+// approved other-account copy.
+func TestCreateUnderOtherAccountsNameRefused(t *testing.T) {
+ fx, member := instanceFixture(t, "code-ns-other")
+ fx.srv.cfg.AppsDomain = nsApps
+ operator := cliToken(t, fx, "paul@keymail.dev", "code-ns-other-paul")
+ nsAccount(t, fx, 82, "bdq")
+ nsHold(t, fx, "harbour", "bdq")
+ enableInstances(t, fx, "titogo", titoManifest())
+ acct, err := fx.st.AccountBySqid(fx.sqid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ host := "x.harbour." + nsApps
+
+ // The browser form's core, and the first-route core.
+ if _, ref := fx.srv.attachDomain(ctx, acct, "titogo", host, "", "", "paul@keymail.dev"); ref == nil || ref.Msg != "that hostname is platform-managed" {
+ t.Errorf("attach core = %+v, want the platform-managed refusal", ref)
+ }
+ if _, ref := fx.srv.attachDomain(ctx, acct, "titogo", host, "static", "", "paul@keymail.dev"); ref == nil {
+ t.Error("first-route core accepted")
+ }
+ u := domainsURL(fx, "bab", "titogo")
+ for _, c := range []struct {
+ door, token, body string
+ want int
+ }{
+ {"API alias", member, attachBody(host, "go.tito.io"), http.StatusBadRequest},
+ {"API first route", member, attachBodyKind(host, "", "static", ""), http.StatusBadRequest},
+ {"API wildcard and catchall", member, `{"host":"` + host + `","route":"go.tito.io","wildcard":true,"catchall":true}`, http.StatusBadRequest},
+ {"platform door", operator, platformAttachBody(host, "go.tito.io"), http.StatusBadRequest},
+ {"one-label platform door", operator, platformAttachBody("harbour."+nsApps, "go.tito.io"), http.StatusBadRequest},
+ {"instance catch-all on the name", member, `{"host":"*.harbour.` + nsApps + `"}`, http.StatusBadRequest},
+ {"instance catch-all under the name", member, `{"host":"*.` + host + `"}`, http.StatusBadRequest},
+ } {
+ if code, _, out := rawReq(t, http.MethodPost, u, c.token, c.body); code != c.want {
+ t.Errorf("%s = %d %s, want %d", c.door, code, out, c.want)
+ }
+ }
+
+ // Instance create: the host's own label decides.
+ m := titoManifest()
+ m.Domain = "harbour." + nsApps
+ enableInstances(t, fx, "titogo", m)
+ code, _, out := rawReq(t, http.MethodPost, instancesURL(fx, "bab", "titogo"), member, `{"host":"`+host+`","region":"ie"}`)
+ if want := fmt.Sprintf(subdomainCreateOtherAccountCopy, "harbour."+nsApps); code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != want {
+ t.Errorf("instance create = %d %s, want 422 %q", code, out, want)
+ }
+ if _, _, err := fx.rel.Get(ctx, provision.RecordKey(fx.sqid, "titogo", host)); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("a record at %s (err %v)", host, err)
+ }
+ for _, h := range []string{host, "harbour." + nsApps, "*.x.harbour." + nsApps} {
+ noClaim(t, fx, h)
+ }
+ if c, err := domains.GetClaim(ctx, fx.rel, "*.harbour."+nsApps); err != nil || !c.AccountNamespace || c.Account != "bdq" {
+ t.Errorf("the namespace claim = %+v, %v; want bdq's, untouched", c, err)
+ }
+}
+
+// TestPlacementsUnderOtherAccountsNameRefused: the regional placements door,
+// the remaining door of TestCreateUnderOtherAccountsNameRefused, and an
+// unassigned label at the same door.
+func TestPlacementsUnderOtherAccountsNameRefused(t *testing.T) {
+ w := newRegionalWorld(t, "code-ns-placements")
+ w.fx.srv.cfg.AppsDomain = nsApps
+ nsAccount(t, w.fx, 82, "bdq")
+ nsHold(t, w.fx, "harbour", "bdq")
+ host := "x.harbour." + nsApps
+ if code, out := w.put(t, host, rdBoth()); code != http.StatusBadRequest {
+ t.Errorf("placements under bdq's name = %d %s, want 400", code, out)
+ }
+ noClaim(t, w.fx, host)
+ unassigned := "x.team." + nsApps
+ code, out := w.put(t, unassigned, rdBoth())
+ if want := fmt.Sprintf(subdomainCreateUnassignedCopy, "team."+nsApps); code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != want {
+ t.Errorf("placements under an unassigned label = %d %s, want 422 %q", code, out, want)
+ }
+ noClaim(t, w.fx, unassigned)
+ // A one-label regional claim with a catch-all covers names below it.
+ yes := true
+ body := rdBoth()
+ body.Wildcard, body.Catchall = &yes, &yes
+ if code, out := w.put(t, "team."+nsApps, body); code != http.StatusUnprocessableEntity {
+ t.Errorf("a regional catch-all on team.<apps> = %d %s, want 422", code, out)
+ }
+ noClaim(t, w.fx, "team."+nsApps)
+}
+
+// TestCatchallUnderUnassignedLabelRefused: a catch-all on L.<apps> serves
+// every name below it, so it is a create under L: Wildcard and Catchall in
+// one attach, an instance catch-all on *.L.<apps>, and an existing claim's
+// false-to-true Catchall are all refused while L is not the account's.
+// Re-attaching the existing claim unchanged passes. team (sqid-shaped, so
+// never a name) and marina are both nobody's; marina is then given to the
+// account, and its catch-all goes through.
+func TestCatchallUnderUnassignedLabelRefused(t *testing.T) {
+ fx, member := instanceFixture(t, "code-ns-catchall")
+ fx.srv.cfg.AppsDomain = nsApps
+ enableInstances(t, fx, "titogo", titoManifest())
+ ctx := context.Background()
+ u := domainsURL(fx, "bab", "titogo")
+
+ for _, label := range []string{"team", "marina"} {
+ parent := label + "." + nsApps
+ unassigned := fmt.Sprintf(subdomainCreateUnassignedCopy, parent)
+ code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"`+parent+`","route":"go.tito.io","wildcard":true,"catchall":true}`)
+ if code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != unassigned {
+ t.Errorf("wildcard and catchall on %s = %d %s, want 422 %q", parent, code, out, unassigned)
+ }
+ noClaim(t, fx, parent)
+ code, _, out = rawReq(t, http.MethodPost, u, member, `{"host":"*.`+parent+`"}`)
+ if code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != unassigned {
+ t.Errorf("instance catch-all on *.%s = %d %s, want 422 %q", parent, code, out, unassigned)
+ }
+ noClaim(t, fx, "*."+parent)
+ }
+
+ // The account's existing claim on marina.<apps>, wildcard on, catchall
+ // off.
+ parent := "marina." + nsApps
+ unassigned := fmt.Sprintf(subdomainCreateUnassignedCopy, parent)
+ seedClaim(t, fx, domains.Claim{Schema: 1, Host: parent, Account: fx.sqid, App: "titogo", Route: "go.tito.io", CreatedAt: "2026-11-11T00:00:00Z"})
+ if _, err := domains.SetClaimCapabilities(ctx, fx.rel, parent, fx.sqid, "titogo", true, false); err != nil {
+ t.Fatal(err)
+ }
+ code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"`+parent+`","route":"go.tito.io","catchall":true}`)
+ if code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != unassigned {
+ t.Errorf("catchall on the existing %s = %d %s, want 422 %q", parent, code, out, unassigned)
+ }
+ for _, body := range []string{
+ `{"host":"` + parent + `","route":"go.tito.io","wildcard":true}`,
+ `{"host":"` + parent + `","route":"go.tito.io"}`,
+ } {
+ if code, _, out := rawReq(t, http.MethodPost, u, member, body); code != http.StatusOK {
+ t.Errorf("re-attach unchanged %s = %d %s, want 200", body, code, out)
+ }
+ }
+ if c, err := domains.GetClaim(ctx, fx.rel, parent); err != nil || !c.Wildcard || c.Catchall {
+ t.Errorf("claim %s = %+v, %v; want wildcard on, catchall off", parent, c, err)
+ }
+
+ // The capability door's own check, under regionalMu, on the claim it
+ // reads there.
+ acct, err := fx.st.AccountBySqid(fx.sqid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ yes := true
+ rec := httptest.NewRecorder()
+ if fx.srv.setDomainCapabilities(rec, httptest.NewRequest(http.MethodPost, "/", nil), ctx, nsView(t, fx.srv), acct, "titogo",
+ Principal{Kind: PrincipalUser, Address: "alice@keymail.dev"}, parent, nil, &yes) {
+ t.Error("setDomainCapabilities turned the catch-all on under an unassigned label")
+ }
+ if rec.Code != http.StatusUnprocessableEntity {
+ t.Errorf("setDomainCapabilities answered %d %s, want 422", rec.Code, rec.Body)
+ }
+
+ // Once marina is the account's, the catch-all is its to turn on.
+ nsHold(t, fx, "marina", fx.sqid)
+ if code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"`+parent+`","route":"go.tito.io","catchall":true}`); code != http.StatusOK {
+ t.Errorf("catchall once marina is the account's = %d %s, want 200", code, out)
+ }
+ if c, err := domains.GetClaim(ctx, fx.rel, parent); err != nil || !c.Catchall {
+ t.Errorf("claim %s = %+v, %v; want catchall on", parent, c, err)
+ }
+}
+
+// TestDoorRefusesWhenNamespacesUnreadable: a namespace listing that fails
+// refuses every attach under the apps domain with the retryable answer, the
+// account's own sqid included, and leaves other hosts alone. A one-label
+// host on another account's name is refused.
+func TestDoorRefusesWhenNamespacesUnreadable(t *testing.T) {
+ fx, acct := attachFixture(t)
+ shipVersion(t, fx, "story", "v1")
+ seedChannel(t, fx, "story", "canary/live", "v1")
+ ctx := context.Background()
+ nsAccount(t, fx, 49, "bcd")
+ nsHold(t, fx, "harbour", "bcd")
+
+ if _, ref := fx.srv.attachDomain(ctx, acct, "story", "harbour."+nsApps, "", "", "paul@keymail.dev"); ref == nil {
+ t.Error("a one-label attach of bcd's harbour was accepted")
+ }
+ noClaim(t, fx, "harbour."+nsApps)
+
+ fx.srv.cfg.Releases = &nsFaultStore{Store: fx.rel, failList: domains.ClaimsPrefix}
+ fx.srv.claims.Reset()
+ own := "blog." + fx.sqid + "." + nsApps
+ _, ref := fx.srv.attachDomain(ctx, acct, "story", own, "", "", "paul@keymail.dev")
+ if want := fmt.Sprintf(subdomainCreateUnreadableCopy, fx.sqid+"."+nsApps); ref == nil || ref.Msg != want || ref.Status != http.StatusBadGateway {
+ t.Errorf("attach %s with the listing down = %+v, want 502 %q", own, ref, want)
+ }
+ noClaim(t, fx, own)
+ if _, err := fx.srv.loadNamespaces(ctx); err == nil {
+ t.Error("loadNamespaces answered with the listing down")
+ }
+ // A host outside the apps domain needs no namespace and still attaches.
+ if _, ref := fx.srv.attachDomain(ctx, acct, "story", "story.example.com", "", "", "paul@keymail.dev"); ref != nil {
+ t.Errorf("attach outside the apps domain with the listing down = %+v, want it attached", ref)
+ }
+}
+
+// TestInstanceCreateChecksHostLabel: instance create checks the host's own
+// label, not the manifest domain's standing: an app whose manifest domain is
+// team.<apps> (store-mode; no door assigns team, a sqid-shaped label) cannot
+// create a.team.<apps>, one on marina.<apps> cannot create a.marina.<apps>
+// until marina is the account's, and one pinned to another account's sqid
+// cannot create there at all.
+func TestInstanceCreateChecksHostLabel(t *testing.T) {
+ fx, member := instanceFixture(t, "code-ns-instance")
+ fx.srv.cfg.AppsDomain = nsApps
+ nsAccount(t, fx, 82, "bdq")
+ m := titoManifest()
+ u := instancesURL(fx, "bab", "titogo")
+ for _, label := range []string{"team", "marina"} {
+ m.Domain = label + "." + nsApps
+ enableInstances(t, fx, "titogo", m)
+ code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"a.`+label+`.`+nsApps+`","region":"ie"}`)
+ if want := fmt.Sprintf(subdomainCreateUnassignedCopy, label+"."+nsApps); code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != want {
+ t.Errorf("create a.%s = %d %s, want 422 %q", label, code, out, want)
+ }
+ }
+ nsHold(t, fx, "marina", fx.sqid)
+ if code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"a.marina.`+nsApps+`","region":"ie"}`); code != http.StatusCreated {
+ t.Fatalf("create a.marina once marina is the account's = %d %s, want 201", code, out)
+ }
+
+ m.Domain = "bdq." + nsApps
+ enableInstances(t, fx, "titogo", m)
+ code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"a.bdq.`+nsApps+`","region":"ie"}`)
+ if want := fmt.Sprintf(subdomainCreateOtherAccountCopy, "bdq."+nsApps); code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != want {
+ t.Errorf("create a.bdq = %d %s, want 422 %q", code, out, want)
+ }
+}
+
+// TestUnreadNamespaceRefusesEveryone: the namespace claim for marketx is
+// listed but its body does not read. It counts as held by an unknown
+// account: creating under marketx is refused for everyone, the one-label
+// host too, and assigning marketx is refused, until the read succeeds.
+func TestUnreadNamespaceRefusesEveryone(t *testing.T) {
+ fx, acct := attachFixture(t)
+ shipVersion(t, fx, "story", "v1")
+ seedChannel(t, fx, "story", "canary/live", "v1")
+ ctx := context.Background()
+ nsAccount(t, fx, 82, "bdq")
+ nsHold(t, fx, "marketx", "bdq")
+ fx.srv.cfg.Releases = &nsFaultStore{Store: fx.rel, failGet: domains.ClaimKey(domains.NamespaceHost("marketx", nsApps))}
+ fx.srv.claims.Reset()
+
+ v := nsView(t, fx.srv)
+ if owner, known := v.labelOwner("marketx"); known || owner != "" {
+ t.Errorf("labelOwner(marketx) = %q, %v; want unknown", owner, known)
+ }
+ for _, account := range []string{fx.sqid, "bdq", "bcd"} {
+ if !fx.srv.createRefusal(v, "x.marketx."+nsApps, account, createNewHost) {
+ t.Errorf("createRefusal admits %s under the unread marketx", account)
+ }
+ }
+ want := fmt.Sprintf(subdomainCreateUnreadableCopy, "marketx."+nsApps)
+ for _, host := range []string{"x.marketx." + nsApps, "marketx." + nsApps} {
+ if _, ref := fx.srv.attachDomain(ctx, acct, "story", host, "", "", "paul@keymail.dev"); ref == nil || ref.Msg != want {
+ t.Errorf("attach %s = %+v, want %q", host, ref, want)
+ }
+ noClaim(t, fx, host)
+ }
+ if got, _ := fx.srv.subdomainRefusal(ctx, v, "bcd", "marketx"); got != domains.SubdomainUnreadable {
+ t.Errorf("assigning marketx = %q, want %q", got, domains.SubdomainUnreadable)
+ }
+ // Other labels are untouched.
+ if _, ref := fx.srv.attachDomain(ctx, acct, "story", "blog."+fx.sqid+"."+nsApps, "", "", "paul@keymail.dev"); ref != nil {
+ t.Errorf("attach under the account's own sqid = %+v, want it attached", ref)
+ }
+}
+
+// TestSubdomainOccupiedByUnmaterializedRecord: bcd's record at
+// shop.harbour.<apps> has no claim and no route, and still occupies the
+// name. A record walk that fails is unreadable, never an empty walk.
+func TestSubdomainOccupiedByUnmaterializedRecord(t *testing.T) {
+ fx, _ := attachFixture(t)
+ ctx := context.Background()
+ nsAccount(t, fx, 82, "bdq")
+ nsAccount(t, fx, 49, "bcd")
+ host := "shop.harbour." + nsApps
+ if err := provision.CreateRecord(ctx, fx.rel, provision.Record{Schema: 1, Host: host, Slug: "shop", App: "shop",
+ Account: "bcd", Channel: "stable", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ noClaim(t, fx, host)
+
+ got, occ := fx.srv.subdomainRefusal(ctx, nsView(t, fx.srv), "bdq", "harbour")
+ want := []occupant{{Host: host, Account: "bcd", App: "shop", Source: occupantRecord}}
+ if got != domains.SubdomainOccupied || !reflect.DeepEqual(occ, want) {
+ t.Errorf("assigning harbour = %q %+v, want %q %+v", got, occ, domains.SubdomainOccupied, want)
+ }
+
+ fx.srv.cfg.Releases = &nsFaultStore{Store: fx.rel, failList: "accounts/"}
+ if got, occ := fx.srv.subdomainRefusal(ctx, nsView(t, fx.srv), "bdq", "harbour"); got != domains.SubdomainUnreadable {
+ t.Errorf("assigning harbour with the record walk down = %q %+v, want %q", got, occ, domains.SubdomainUnreadable)
+ }
+}
+
+// TestSubdomainOccupiedByPendingAllocation: a create stopped after its
+// allocation and before its record write (the allocation stored, no record)
+// occupies the name; recovery then writes the record without a door, and
+// the name stays refused.
+func TestSubdomainOccupiedByPendingAllocation(t *testing.T) {
+ l := newLtOn(t)
+ srv := l.fx.srv
+ srv.cfg.AppsDomain = nsApps
+ nsAccount(t, l.fx, 82, "bdq")
+ ctx := context.Background()
+ host := "shop.harbour." + nsApps
+ key := recKey(ltApp, host)
+
+ l.bucket.setHook(failNth("put", key, 1, true))
+ life, err := l.fx.st.AppLife(OpsAccountID, ltApp)
+ if err != nil || life == nil {
+ t.Fatalf("app life %+v, %v", life, err)
+ }
+ rec := provision.Record{Schema: 1, Host: host, Slug: "shop", App: ltApp, Account: "bab", Channel: "stable", CreatedAt: time.Now().UTC()}
+ if _, err := srv.createRecordWithLifetime(onCtx(t, srv), rec, life.Lifetime); err == nil {
+ t.Fatal("the create wrote its record through a failing bucket")
+ }
+ if _, _, err := l.fx.rel.Get(ctx, key); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("a record at %s (err %v); want the allocation alone", host, err)
+ }
+ if pending, err := l.fx.st.PendingAllocationsUnder("harbour." + nsApps); err != nil || len(pending) != 1 {
+ t.Fatalf("pending allocations under harbour = %+v, %v; want one", pending, err)
+ }
+ got, occ := srv.subdomainRefusal(ctx, nsView(t, srv), "bdq", "harbour")
+ want := []occupant{{Host: host, Account: "bab", App: ltApp, Source: occupantAllocation}}
+ if got != domains.SubdomainOccupied || !reflect.DeepEqual(occ, want) {
+ t.Errorf("assigning harbour over the allocation = %q %+v, want %q %+v", got, occ, domains.SubdomainOccupied, want)
+ }
+
+ l.bucket.setHook(nil)
+ recoverOn(t, srv)
+ if _, _, err := l.fx.rel.Get(ctx, key); err != nil {
+ t.Fatalf("recovery did not write the record: %v", err)
+ }
+ got, occ = srv.subdomainRefusal(ctx, nsView(t, srv), "bdq", "harbour")
+ want = []occupant{{Host: host, Account: "bab", App: ltApp, Source: occupantRecord}}
+ if got != domains.SubdomainOccupied || !reflect.DeepEqual(occ, want) {
+ t.Errorf("assigning harbour after recovery = %q %+v, want %q %+v", got, occ, domains.SubdomainOccupied, want)
+ }
+}
+
+// TestPendingAllocationsUnder: pending allocations at or under the suffix,
+// nothing that only ends in its letters, and nothing settled.
+func TestPendingAllocationsUnder(t *testing.T) {
+ s := openTestStore(t)
+ for i, h := range []string{"harbour." + nsApps, "shop.harbour." + nsApps, "a.b.harbour." + nsApps, "xharbour." + nsApps, "shop.pier." + nsApps, "done.harbour." + nsApps} {
+ if err := s.BeginAllocation(testAllocation(fmt.Sprintf("op-%d", i), h, 1)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.SetAllocationState("op-5", lifetimeCommitted); err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.PendingAllocationsUnder("harbour." + nsApps)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var hosts []string
+ for _, a := range got {
+ hosts = append(hosts, a.Host)
+ }
+ if want := []string{"harbour." + nsApps, "shop.harbour." + nsApps, "a.b.harbour." + nsApps}; !reflect.DeepEqual(hosts, want) {
+ t.Errorf("PendingAllocationsUnder = %v, want %v", hosts, want)
+ }
+ if got, err := s.PendingAllocationsUnder(""); err == nil {
+ t.Errorf("an empty suffix = %+v, nil; want an error", got)
+ }
+}
+
+// TestRemovedNameStopsProtecting: once bdq's harbour is removed, nothing
+// about it protects harbour any more. The one-label harbour.<apps> attaches
+// like any name, and a host under harbour gets the unassigned answer, not
+// the other-account one.
+func TestRemovedNameStopsProtecting(t *testing.T) {
+ fx, acct := attachFixture(t)
+ shipVersion(t, fx, "story", "v1")
+ seedChannel(t, fx, "story", "canary/live", "v1")
+ ctx := context.Background()
+ nsAccount(t, fx, 82, "bdq")
+ nsHold(t, fx, "harbour", "bdq")
+
+ if got := fx.srv.domainHostPolicy(nsView(t, fx.srv), "x.harbour."+nsApps, fx.sqid); got != hostReserved {
+ t.Errorf("policy under bdq's harbour = %v, want reserved", got)
+ }
+ if _, ref := fx.srv.attachDomain(ctx, acct, "story", "harbour."+nsApps, "", "", "paul@keymail.dev"); ref == nil {
+ t.Error("harbour.<apps> attached while bdq holds harbour")
+ }
+
+ nsRelease(t, fx, "harbour", "bdq")
+ if got := fx.srv.domainHostPolicy(nsView(t, fx.srv), "x.harbour."+nsApps, fx.sqid); got != hostOpen {
+ t.Errorf("policy under the removed harbour = %v, want open", got)
+ }
+ if _, ref := fx.srv.attachDomain(ctx, acct, "story", "harbour."+nsApps, "", "", "paul@keymail.dev"); ref != nil {
+ t.Errorf("harbour.<apps> after removal = %+v, want it attached", ref)
+ }
+ _, ref := fx.srv.attachDomain(ctx, acct, "story", "x.harbour."+nsApps, "", "", "paul@keymail.dev")
+ if want := fmt.Sprintf(subdomainCreateUnassignedCopy, "harbour."+nsApps); ref == nil || ref.Msg != want {
+ t.Errorf("attach under the removed harbour = %+v, want %q", ref, want)
+ }
+}
+
+// TestNamespaceClaimOnSqidLabelIgnored: no door writes a namespace claim for
+// a label §4.2 refuses as a name, so one at *.bdq.<apps> (a direct bucket
+// write by bcd) does not make bdq's sqid bcd's: bdq still creates under its
+// own sqid and bcd still cannot.
+func TestNamespaceClaimOnSqidLabelIgnored(t *testing.T) {
+ fx, _ := attachFixture(t)
+ nsAccount(t, fx, 82, "bdq")
+ nsAccount(t, fx, 49, "bcd")
+ nsHold(t, fx, "bdq", "bcd")
+ v := nsView(t, fx.srv)
+ if owner, known := v.labelOwner("bdq"); owner != "bdq" || !known {
+ t.Errorf("labelOwner(bdq) = %q, %v; want bdq's own sqid", owner, known)
+ }
+ if fx.srv.createRefusal(v, "shop.bdq."+nsApps, "bdq", createNewHost) {
+ t.Error("bdq refused under its own sqid")
+ }
+ if !fx.srv.createRefusal(v, "shop.bdq."+nsApps, "bcd", createNewHost) {
+ t.Error("bcd admitted under bdq's sqid")
+ }
+ if _, ok := v.byAccount["bcd"]; ok {
+ t.Error("bcd has a name from a claim on a sqid label")
+ }
+}
diff --git a/internal/provision/account_subdomains_census_test.go b/internal/provision/account_subdomains_census_test.go
index 2b8d50f89..67b1a60dc 100644
--- a/internal/provision/account_subdomains_census_test.go
+++ b/internal/provision/account_subdomains_census_test.go
@@ -54,6 +54,8 @@ package provision
func accountSubdomainsWriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), linkedDeploymentsSlice1WriteCensusInventory()...)
repins := []censusEntry{
+ {"internal/console/apidomains.go", "Server.handleAPIDomainAttach", "key-site", "lit:instances", "b7103016f07b19fe1158d9d13994f02fdc6bb30189a7762f2492692f198d83f9"},
+ {"internal/console/domainattach.go", "Server.attachDomainAs", "record-writer", "key:CreateRecord", "49a9a28a7929f4262d3b73d3cb68d7d263f453202bf9d8a09d20e1c7bbc237c4"},
}
// The one classification change, stated as such rather than slipped
// through a re-pin: the kinds narrow, the class stays.