carlos / platform Public

console: subdomain door; name URL is canonical (T6)

The door (apisubdomain.go, spec §4.3): GET|POST|DELETE
/api/cli/accounts/{account}/subdomain and GET
/api/cli/system/subdomain-inventory, kindCLI with the empty role set.
cliUser, then platformOperator (404 with refuse.not_operator otherwise),
then a 409 with refuse.host_claims while host claims are on, then the
account (AccountBySqid for set, AccountAnyBySqid for show and remove).

- Set: subdomainRefusal, AttachAccountNamespace, then a re-read
  (namespaceOccupants, a second name, the name still the account's); a
  conflict deletes its own claim against the etag read and refuses
  rolled_back with the hosts found. A failed rollback is a 500 saying the
  name is still held (refuse.rollback_failed); show reports it.
  created=false: the account's own trusted namespace claim is answered as
  set (idempotent); anything else at the key is occupied.
- Show: name, host and other accounts' hosts under it; a failed walk, or
  an unread namespace claim that may be the account's, is unreadable.
- Remove: refused (listing them) while the account has claims, records or
  pending allocations under the name, or the walk fails.
- Effective writes and rollbacks reset the claim cache and bump the
  serial; refused and no-op requests do neither.
- Inventory: hosts two or more labels under the apps domain whose label is
  neither an account's sqid nor a held name, by label; strict.

Canonical URLs (canonical.go, §4.8): canonicalHostIn is pure; hostCanon
loads the namespace view once per request, lazily (no listing when no
host is under the apps domain). Only routes a box derives names for
(provisioned or platform, not sidecar) are rewritten. Display sites:
app list row, app header (name link plus "Permanent address"), Running
tab, instance page heading plus "Permanent address" fact, flow card,
ladder, Canaries table, canary create flash, account settings Subdomain
cell (read-only), linked-app URLs on the serving console
(linkPublicationURL), and the demo claim page and status answers. API:
public_host on the instance list, get, record views (create, update,
import, seed, channel move) and the routes read, omitted when equal to
host. Identity is untouched: detail paths, logs, restart forms, records,
apexHost, probes. homelink: with the serving status failing, no URL is
derived; the serving error stands alone.

Fixtures: claim-routes.txt, four refused claim fixtures with their
claimUnsupported reason, the closed-door list in svcroutes_test.go;
TestAPIInstanceListHealthAndFilters is unchanged (public_host omitted for
hosts without a name); the demo claim no-remote fake now answers the
claim listing only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e990eebbfd151997b831f19625e08f15fea6b206 parent db26827
39 files changed, +1,884 −67
  • internal/console/accountfleet.go +1 −1
  • internal/console/accountlinks.go +9 −6
  • internal/console/apiinstanceimport.go +1 −1
  • internal/console/apiinstances.go +23 −5
  • internal/console/apiinstanceseed.go +1 −1
  • internal/console/apilinks.go +11 −5
  • internal/console/apiroutes.go +17 −2
  • internal/console/apisubdomain.go +585 −0
  • internal/console/apisubdomain_test.go +550 −0
  • internal/console/canonical.go +192 −0
  • internal/console/canonical_test.go +278 −0
  • internal/console/channelmove.go +2 −2
  • internal/console/claim_invariant_fixtures_test.go +20 −0
  • internal/console/claim_invariant_test.go +3 −0
  • internal/console/demo_claim_auth.go +2 −1
  • internal/console/demo_claim_choice_test.go +12 −0
  • internal/console/demo_claim_page.go +1 −1
  • internal/console/demo_claim_status_page.go +1 −1
  • internal/console/flow.go +14 −8
  • internal/console/homelink.go +8 −1
  • internal/console/ladder.go +8 −1
  • internal/console/listquery.go +3 −1
  • internal/console/overview.go +25 −7
  • internal/console/remoteinstances.go +11 −1
  • internal/console/routedecls.go +8 −0
  • internal/console/server.go +23 −6
  • internal/console/subdomain_copy.go +5 −1
  • internal/console/subdomains.go +27 −4
  • internal/console/svcpage.go +1 −0
  • internal/console/svcroutes_test.go +8 −0
  • internal/console/templates/account_settings.html +2 −2
  • internal/console/templates/app_instance.html +2 −1
  • internal/console/templates/app_instances.html +1 −1
  • internal/console/templates/app_releases.html +1 −1
  • internal/console/templates/appnav.html +2 −0
  • internal/console/templates/flow.html +2 −2
  • internal/console/templates/ladder.html +1 −1
  • internal/console/testdata/claim-routes.txt +4 −0
  • internal/console/view.go +19 −3

Intent

Attributed to this commit: 25.6 g CO₂e (3,211,325 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/accountfleet.go b/internal/console/accountfleet.go
index efed962fa..82fec2ad4 100644
--- a/internal/console/accountfleet.go
+++ b/internal/console/accountfleet.go
@@ -85,7 +85,7 @@ func (s *Server) assembleAccountFleet(ctx context.Context, acct *Account) (card
// Linked deployments first: their apps are served from a home, not
// from the shared fleet, so the placement split below leaves them out.
- links = s.accountLinks(acct)
+ links = s.accountLinks(ctx, acct)
defer func() {
if warn == "" {
warn = links.Warn
diff --git a/internal/console/accountlinks.go b/internal/console/accountlinks.go
index 8f6923f1f..1ecf01c14 100644
--- a/internal/console/accountlinks.go
+++ b/internal/console/accountlinks.go
@@ -98,7 +98,10 @@ func (s *Server) linkSection() linkSectionCopy {
// channels and (for a revoked link) forward rows. Soft-fail like the rest
// of the Fleet tab: a failed read costs what it would have shown, and Warn
// says so.
-func (s *Server) accountLinks(acct *Account) accountLinksView {
+func (s *Server) accountLinks(ctx context.Context, acct *Account) accountLinksView {
+ // Every linked app's address, as the platform shows it (canonical.go),
+ // from one namespace listing for the whole tab.
+ canon := s.canon(ctx)
v := accountLinksView{linkedApps: map[string]bool{}}
warn := func(format string, args ...any) {
log.Printf("console: linked deployments %s: "+format, append([]any{acct.Sqid}, args...)...)
@@ -172,7 +175,7 @@ func (s *Server) accountLinks(acct *Account) accountLinksView {
}
c.AppsKnown = appsErr == nil
for _, a := range apps {
- c.Apps = append(c.Apps, accountLinkApp{Name: a.App, URL: s.linkAppURL(acct, a.App)})
+ c.Apps = append(c.Apps, accountLinkApp{Name: a.App, URL: s.linkAppURL(canon, acct, a.App)})
}
if seenOK {
c.SeenKnown = true
@@ -200,11 +203,11 @@ func (s *Server) accountLinks(acct *Account) accountLinksView {
// linkAppURL is a linked app's public address, "" on a console with no
// apps domain.
-func (s *Server) linkAppURL(acct *Account, app string) string {
+func (s *Server) linkAppURL(c *hostCanon, acct *Account, app string) string {
if s.apexHost(acct.Sqid, app) == "" {
return ""
}
- return s.linkPublicationURL(acct, app)
+ return s.linkPublicationURL(c, acct, app)
}
// linkedAppView is a linked app's own page on Carloku (spec §5.4): what it
@@ -256,7 +259,7 @@ func (s *Server) handleLinkedAppOverview(w http.ResponseWriter, r *http.Request,
v.Heading = linkCopy(copyLD31, "home", v.Home)
v.Managed = linkCopy(copyLinkedOverviewManaged, "app", p.AppName, "home", v.Home)
v.AddressLabel = copyLinkedOverviewAddress
- v.URL = s.linkAppURL(acct, p.AppName)
+ v.URL = s.linkAppURL(s.canon(r.Context()), acct, p.AppName)
v.ReachableText, v.NotReachableText = copyLD18, copyLD19
if p.BillingNav {
v.UsageText, v.UsageHref = copyLinkedOverviewUsage, p.Nav+"/billing"
@@ -411,7 +414,7 @@ func (s *Server) handleAPILinksList(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- v := s.accountLinks(acct)
+ v := s.accountLinks(r.Context(), acct)
if !v.Known {
jsonError(w, http.StatusServiceUnavailable, copyLinksReadFailed)
return
diff --git a/internal/console/apiinstanceimport.go b/internal/console/apiinstanceimport.go
index c9d45835e..325b29e20 100644
--- a/internal/console/apiinstanceimport.go
+++ b/internal/console/apiinstanceimport.go
@@ -246,7 +246,7 @@ func (s *Server) beginImport(w http.ResponseWriter, r *http.Request, c seedCreat
out := struct {
apiRecordView
VerifyToken string `json:"verify_token"`
- }{recordView(rec), token}
+ }{s.publicRecordView(ctx, rec), token}
out.PrivateStoreBucket = privateBucket
out.RegionFrom = c.regionFrom
out.RegionName = s.placeOf(rec.Region, s.candsOrHome(viewCtx)) // never fleet-placed: refused above
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index be7cefa80..c1a773dc7 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -180,6 +180,8 @@ func (s *Server) instanceManifest(ctx context.Context, w http.ResponseWriter, ac
// stored record that this join was never meant to touch.
type instanceListRecord struct {
provision.Record
+ // PublicHost is as apiRecordView's: the host as the platform shows it.
+ PublicHost string `json:"public_host,omitempty"`
// StagedVersion is registry.Route.Version as last reported by whichever
// box's adopt pass claimed this host, read from that box's own
// status/boxes/<label>.json (internal/status's bucket-private Metrics
@@ -1313,6 +1315,7 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) {
}
health, held := s.instanceHealth(ctx, recs)
fleetHealth(health, recs, join, acct.Sqid, app)
+ canon := s.canon(ctx) // one namespace listing for every row
counts := map[string]int{}
matched := make([]instanceListRecord, 0, len(recs))
home, names := s.regionHome(), s.regionNames()
@@ -1330,7 +1333,7 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) {
}
ro := join.rollout(rec.Host, acct.Sqid, app)
refusal, refusalsCapped := join.refusalFor(rec, ro)
- matched = append(matched, instanceListRecord{Record: rec,
+ matched = append(matched, instanceListRecord{Record: rec, PublicHost: canon.public(rec.Host),
ConfigRefusal: refusal, RefusalsCapped: refusalsCapped,
StagedVersion: join.versions[rec.Host], Health: h, Upstreams: join.upstreams[rec.Host],
ServedBy: served[rec.Host], Gated: rec.Gate != "", DBBytes: join.dbSize(rec.Host),
@@ -1417,7 +1420,7 @@ func (s *Server) handleAPIInstanceGet(w http.ResponseWriter, r *http.Request) {
return
}
home, names := s.regionHome(), s.regionNames()
- writeJSON(w, http.StatusOK, instanceGetRecord{Record: *rec,
+ writeJSON(w, http.StatusOK, instanceGetRecord{Record: *rec, PublicHost: s.canon(ctx).public(rec.Host),
ServedBy: loadEdgesJoin(ctx, s.cfg.Releases)[host], Gated: rec.Gate != "",
RegionName: regionlabel.ForRecord(*rec, home, names).Text, MovePhrase: regionlabel.MovePhrase(*rec, home, names)})
}
@@ -1429,7 +1432,9 @@ func (s *Server) handleAPIInstanceGet(w http.ResponseWriter, r *http.Request) {
// instance lives.
type instanceGetRecord struct {
provision.Record
- ServedBy []servedBy `json:"served_by,omitempty"`
+ // PublicHost is as apiRecordView's.
+ PublicHost string `json:"public_host,omitempty"`
+ ServedBy []servedBy `json:"served_by,omitempty"`
// HiddenGate shadows Record.Gate for encoding/json (a shallower field of
// the same name wins), so the bcrypt hash never leaves the console; it
// is always "" and omitted. Gated is what a member may know.
@@ -1449,6 +1454,11 @@ type apiRecordView struct {
provision.Record
HiddenGate string `json:"gate,omitempty"`
Gated bool `json:"gated"`
+ // PublicHost is the record's host as the platform shows it: the name
+ // host where the account has a subdomain (account subdomains spec §4.8,
+ // canonical.go). Host stays the identity; a client prints this one when
+ // it is present. Omitted when it would be Host itself.
+ PublicHost string `json:"public_host,omitempty"`
// PrivateStoreBucket is the bucket the create door provisioned for this
// instance under the app's private-storage policy (issue #412), empty on
// every other record and every other door. Not part of the record: it is
@@ -1473,6 +1483,14 @@ func recordView(rec provision.Record) apiRecordView {
return apiRecordView{Record: rec, Gated: rec.Gate != ""}
}
+// publicRecordView is recordView with PublicHost, the record's host as the
+// platform shows it (canonical.go).
+func (s *Server) publicRecordView(ctx context.Context, rec provision.Record) apiRecordView {
+ v := recordView(rec)
+ v.PublicHost = s.canon(ctx).public(rec.Host)
+ return v
+}
+
// replicaFields is the #162 slice of the instance-create body. Role and
// placement travel together or not at all — "a replica without a placement"
// and "a placement without a replica role" are both half a decision, and
@@ -2687,7 +2705,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// a box-consumed write (carlos-deploy §3): announce it, and the instance
// is serving seconds after signup instead of on the hour.
s.bumpSerial(ctx)
- out := recordView(rec)
+ out := s.publicRecordView(ctx, rec)
out.PrivateStoreBucket = privateBucket
out.RegionFrom = regionFrom
out.Restore = restore != nil
@@ -3285,7 +3303,7 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request)
// so this announcement is what makes the new set live in seconds instead
// of on the hour.
s.bumpSerial(ctx)
- writeJSON(w, http.StatusOK, recordView(*rec))
+ writeJSON(w, http.StatusOK, s.publicRecordView(ctx, *rec))
}
// handleAPIInstanceDelete retires an instance's route authorization. The
diff --git a/internal/console/apiinstanceseed.go b/internal/console/apiinstanceseed.go
index 4e49a3e0f..273ad33bc 100644
--- a/internal/console/apiinstanceseed.go
+++ b/internal/console/apiinstanceseed.go
@@ -388,7 +388,7 @@ func (s *Server) beginFrom(w http.ResponseWriter, r *http.Request, c seedCreate,
jsonError(w, http.StatusBadGateway, failed)
return nil
}
- out := recordView(rec)
+ out := s.publicRecordView(ctx, rec)
out.RegionFrom = c.regionFrom
out.RegionName = s.placeOf(rec.Region, s.candsOrHome(writeCtx)) // never fleet-placed: refused above
// The region's label (region labels §4), as every create answer has.
diff --git a/internal/console/apilinks.go b/internal/console/apilinks.go
index c5d4c8a8e..d2996efce 100644
--- a/internal/console/apilinks.go
+++ b/internal/console/apilinks.go
@@ -121,9 +121,14 @@ func (s *Server) refuseLinkedHostClaim(w http.ResponseWriter) bool {
return true
}
-// linkPublicationURL is a published app's public address.
-func (s *Server) linkPublicationURL(acct *Account, app string) string {
- return "https://" + s.apexHost(acct.Sqid, app)
+// linkPublicationURL is a published app's public address, as the platform
+// shows it (canonical.go): its name URL where the account has a subdomain.
+// The linking console shows the URL this console gives it (homelink.go), so
+// the rule is applied here, where the claims are. The forward row keeps the
+// sqid host (linkForward): that is the identity, and the name host reaches
+// it through the box's derived alias.
+func (s *Server) linkPublicationURL(c *hostCanon, acct *Account, app string) string {
+ return "https://" + c.host(s.apexHost(acct.Sqid, app))
}
// linkForward is the forward row that serves a linked app: the app's
@@ -151,8 +156,9 @@ func (s *Server) handleLinkGet(w http.ResponseWriter, r *http.Request) {
CreatedAt time.Time `json:"created_at"`
}
pubs := []publication{}
+ canon := s.canon(r.Context())
for _, a := range apps {
- pubs = append(pubs, publication{App: a.App, URL: s.linkPublicationURL(acct, a.App), CreatedAt: a.CreatedAt})
+ pubs = append(pubs, publication{App: a.App, URL: s.linkPublicationURL(canon, acct, a.App), CreatedAt: a.CreatedAt})
}
writeJSON(w, http.StatusOK, map[string]any{
"link_id": l.ID, "account": acct.Sqid, "name": l.Name, "publications": pubs,
@@ -220,7 +226,7 @@ func (s *Server) handleLinkPublish(w http.ResponseWriter, r *http.Request) {
taken := func() {
jsonError(w, http.StatusConflict, linkCopy(copyLD10, "app", name, "account", acct.Name))
}
- body := map[string]string{"app": name, "url": s.linkPublicationURL(acct, name)}
+ body := map[string]string{"app": name, "url": s.linkPublicationURL(s.canon(r.Context()), acct, name)}
// LOCK ORDER (applocks.go): the account lock (planLock), then the app's.
defer s.planLock(acct)()
defer s.lockApp(acct.Sqid, name)()
diff --git a/internal/console/apiroutes.go b/internal/console/apiroutes.go
index 48eeace5d..6846554a3 100644
--- a/internal/console/apiroutes.go
+++ b/internal/console/apiroutes.go
@@ -50,7 +50,11 @@ const routeListTimeout = 15 * time.Second
// registry row EXCEPT Health, which is the same word instanceHealth and
// the Running tab compute (healthByHost).
type apiRoute struct {
- Host string `json:"host"`
+ Host string `json:"host"`
+ // PublicHost is Host as the platform shows it: the name host where the
+ // account has a subdomain (account subdomains spec §4.8, canonical.go).
+ // Host stays what a route is matched by. Omitted when it would be Host.
+ PublicHost string `json:"public_host,omitempty"`
Kind string `json:"kind"`
Upstream string `json:"upstream"`
App string `json:"app"`
@@ -163,9 +167,10 @@ func (s *Server) handleAPIRoutes(w http.ResponseWriter, r *http.Request) {
join := loadBoxJoin(ctx, s.cfg.Releases, time.Now())
rows := make([]apiRoute, 0, len(routeFor))
home, names := s.regionHome(), s.regionNames()
+ canon := s.canon(ctx) // one namespace listing for every row
for _, rt := range routeFor {
rows = append(rows, apiRoute{
- Host: rt.Host, Kind: rt.Kind, Upstream: routeUpstream(rt), App: rt.App,
+ Host: rt.Host, PublicHost: routePublicHost(canon, rt), Kind: rt.Kind, Upstream: routeUpstream(rt), App: rt.App,
Channel: rt.Channel, Environment: rt.Environment, Status: rt.Status,
Health: health[rt.Host], Hibernate: rt.Hibernate, Unit: rt.Unit,
Backing: rt.Backing, Provisioned: rt.Provisioned,
@@ -223,3 +228,13 @@ func (s *Server) handleAPIRoutes(w http.ResponseWriter, r *http.Request) {
// CLI prints them in under each host.
writeJSON(w, http.StatusOK, map[string]any{"routes": rows, "paths": paths})
}
+
+// routePublicHost is rt's public_host: the name host where the account has a
+// subdomain and a box derives one for rt (canonical.go, derivesName), else
+// "".
+func routePublicHost(c *hostCanon, rt registry.Route) string {
+ if !derivesName(rt.Provisioned, rt.Platform, rt.Kind) {
+ return ""
+ }
+ return c.public(rt.Host)
+}
diff --git a/internal/console/apisubdomain.go b/internal/console/apisubdomain.go
new file mode 100644
index 000000000..0a9f200b3
--- /dev/null
+++ b/internal/console/apisubdomain.go
@@ -0,0 +1,585 @@
+package console
+
+// The account subdomain door (account subdomains spec §4.3):
+//
+// GET /api/cli/accounts/{account}/subdomain show
+// POST /api/cli/accounts/{account}/subdomain set {"name": "harbour"}
+// DELETE /api/cli/accounts/{account}/subdomain remove
+// GET /api/cli/system/subdomain-inventory the release inventory
+//
+// Only a platform operator, as a person: cliUser (a service credential is
+// the same 401 as no credential) and then platformOperator (an owner of the
+// ops account or an address on CARLOS_SYSTEM_OPERATORS), not the plan
+// door's store.IsOperator. Anyone else gets a 404 carrying the
+// not-operator answer, before any account is looked up, so the answer says
+// nothing about which accounts exist. With host claims on every method
+// refuses next: the claim mutation boundary has no account-level writes.
+//
+// Set judges every §4.2 rule (subdomainRefusal), writes the namespace claim
+// create-only, and reads again (§4.2, the race): anything of another
+// account's under the name, a second name for the account, or a read that
+// fails, and it deletes its own claim (etag-conditional) and refuses. Show
+// and remove resolve deleted accounts (AccountAnyBySqid); set does not.
+// Every write that lands resets the claim cache and bumps the serial, so
+// boxes and display reads see it at once; refused and no-op requests do
+// neither.
+//
+// The answers are approved copy (subdomain_copy.go). A refusal carries the
+// rule's code (domains.SubdomainRefusal) beside the sentence, and the hosts
+// it is about when it is about hosts, so the CLI can print the list.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// subdomainReply is the door's answer about one account: its name ("" when
+// it has none), the host its apps answer under (<name>.<apps-domain>), and
+// the hosts other accounts have under it (show reports them; set answers
+// it empty).
+type subdomainReply struct {
+ Account string `json:"account"`
+ Name string `json:"name"`
+ Host string `json:"host"`
+ Foreign []occupant `json:"foreign"`
+}
+
+// subdomainRefuse writes a refusal: the approved sentence, the rule's code,
+// and, when the refusal is about hosts, those hosts (never null then).
+func subdomainRefuse(w http.ResponseWriter, status int, code domains.SubdomainRefusal, msg string, hosts []occupant, listed bool) {
+ body := map[string]any{"error": msg, "code": string(code)}
+ if listed {
+ if hosts == nil {
+ hosts = []occupant{}
+ }
+ body["hosts"] = hosts
+ }
+ writeJSON(w, status, body)
+}
+
+// subdomainOperator is the door's gate before any account: a person, a
+// platform operator, host claims off. It writes the refusal itself.
+func (s *Server) subdomainOperator(w http.ResponseWriter, r *http.Request) (string, bool) {
+ addr, ok := s.cliUser(w, r)
+ if !ok {
+ return "", false
+ }
+ if !s.platformOperator(addr) {
+ jsonError(w, http.StatusNotFound, subdomainRefuseNotOperatorCopy)
+ return "", false
+ }
+ if s.cfg.HostClaim {
+ jsonError(w, http.StatusConflict, subdomainRefuseHostClaimsCopy)
+ return "", false
+ }
+ return addr, true
+}
+
+// subdomainAccount is the gate plus the account the path names: a live one
+// for set, a live or deleted one for show and remove. Not found is the
+// plain 404.
+func (s *Server) subdomainAccount(w http.ResponseWriter, r *http.Request, deleted bool) (string, *Account, bool) {
+ addr, ok := s.subdomainOperator(w, r)
+ if !ok {
+ return "", nil, false
+ }
+ seg := r.PathValue("account")
+ var acct *Account
+ var err error
+ if deleted {
+ acct, _, err = s.store.AccountAnyBySqid(seg)
+ } else {
+ acct, err = s.store.AccountBySqid(seg)
+ }
+ if err != nil {
+ log.Printf("console: subdomain door: account %q: %v", seg, err)
+ }
+ if err != nil || acct == nil {
+ http.NotFound(w, r)
+ return "", nil, false
+ }
+ return addr, acct, true
+}
+
+// subdomainRoot is <name>.<apps-domain>, the host a name's apps answer
+// under.
+func (s *Server) subdomainRoot(name string) string {
+ return name + "." + s.appsDomain()
+}
+
+// refuseSubdomain answers refusal ref of name for acct with its approved
+// copy. raw is the name as typed (the shape answer quotes it), have the
+// name the account holds (the has-one answer names it).
+func (s *Server) refuseSubdomain(w http.ResponseWriter, ref domains.SubdomainRefusal, acct *Account, raw, name, have string, hosts []occupant) {
+ root := s.subdomainRoot(name)
+ switch ref {
+ case domains.SubdomainShape:
+ subdomainRefuse(w, http.StatusUnprocessableEntity, ref, fmt.Sprintf(subdomainRefuseShapeCopy, strings.TrimSpace(raw)), nil, false)
+ case domains.SubdomainSqidShaped:
+ subdomainRefuse(w, http.StatusUnprocessableEntity, ref, fmt.Sprintf(subdomainRefuseSqidShapedCopy, name), nil, false)
+ case domains.SubdomainReserved:
+ subdomainRefuse(w, http.StatusUnprocessableEntity, ref, fmt.Sprintf(subdomainRefuseReservedCopy, name), nil, false)
+ case domains.SubdomainInfrastructure:
+ subdomainRefuse(w, http.StatusUnprocessableEntity, ref, fmt.Sprintf(subdomainRefuseInfrastructureCopy, name), nil, false)
+ case domains.SubdomainHeld:
+ subdomainRefuse(w, http.StatusConflict, ref, fmt.Sprintf(subdomainRefuseHeldCopy, name), nil, false)
+ case domains.SubdomainOccupied:
+ subdomainRefuse(w, http.StatusConflict, ref, fmt.Sprintf(subdomainRefuseOccupiedCopy, root), hosts, true)
+ case domains.SubdomainAccountHasOne:
+ subdomainRefuse(w, http.StatusConflict, ref, fmt.Sprintf(subdomainRefuseHasOneCopy, acct.Sqid, have), nil, false)
+ case domains.SubdomainRolledBack:
+ subdomainRefuse(w, http.StatusConflict, ref, fmt.Sprintf(subdomainRefuseRolledBackCopy, root), hosts, true)
+ default: // domains.SubdomainUnreadable, and anything this door does not name
+ subdomainRefuse(w, http.StatusBadGateway, domains.SubdomainUnreadable, fmt.Sprintf(subdomainRefuseUnreadableCopy, root), nil, false)
+ }
+}
+
+// refuseSubdomainUnreadable is the retryable answer naming where (the
+// apps domain when no name is known yet).
+func refuseSubdomainUnreadable(w http.ResponseWriter, where string) {
+ subdomainRefuse(w, http.StatusBadGateway, domains.SubdomainUnreadable, fmt.Sprintf(subdomainRefuseUnreadableCopy, where), nil, false)
+}
+
+// foreignOccupants are the occupants other accounts than account hold.
+func foreignOccupants(occ []occupant, account string) []occupant {
+ out := []occupant{}
+ for _, o := range occ {
+ if o.Account != account {
+ out = append(out, o)
+ }
+ }
+ return out
+}
+
+// subdomainShown is the reply for acct holding name ("" for none).
+func (s *Server) subdomainShown(acct *Account, name string, foreign []occupant) subdomainReply {
+ if foreign == nil {
+ foreign = []occupant{}
+ }
+ reply := subdomainReply{Account: acct.Sqid, Name: name, Foreign: foreign}
+ if name != "" {
+ reply.Host = s.subdomainRoot(name)
+ }
+ return reply
+}
+
+// subdomainWritten tells the readers a namespace claim changed: the claim
+// cache is reset (display reads re-read every claim) and the serial bumped
+// (boxes reconcile now, not on the hourly floor).
+func (s *Server) subdomainWritten(ctx context.Context) {
+ s.claims.Reset()
+ s.bumpSerial(ctx)
+}
+
+// handleAPISubdomainGet is show: the account's name, its host, and the hosts
+// other accounts have under it. A walk that fails is the unreadable answer,
+// never a name with an empty list; so is a namespace claim that did not read
+// and may be this account's.
+func (s *Server) handleAPISubdomainGet(w http.ResponseWriter, r *http.Request) {
+ _, acct, ok := s.subdomainAccount(w, r, true)
+ if !ok {
+ return
+ }
+ ctx := r.Context()
+ v, err := s.loadNamespaces(ctx)
+ if err != nil {
+ log.Printf("console: subdomain show %s: %v", acct.Sqid, err)
+ refuseSubdomainUnreadable(w, s.appsDomain())
+ return
+ }
+ name := v.byAccount[acct.Sqid]
+ if name == "" {
+ if v.mayHoldUnread(acct.Sqid) {
+ refuseSubdomainUnreadable(w, s.appsDomain())
+ return
+ }
+ writeJSON(w, http.StatusOK, s.subdomainShown(acct, "", nil))
+ return
+ }
+ occ, err := s.namespaceOccupants(ctx, name)
+ if err != nil {
+ log.Printf("console: subdomain show %s: %v", acct.Sqid, err)
+ refuseSubdomainUnreadable(w, s.subdomainRoot(name))
+ return
+ }
+ writeJSON(w, http.StatusOK, s.subdomainShown(acct, name, foreignOccupants(occ, acct.Sqid)))
+}
+
+// handleAPISubdomainSet is set {"name": ...}.
+func (s *Server) handleAPISubdomainSet(w http.ResponseWriter, r *http.Request) {
+ addr, acct, ok := s.subdomainAccount(w, r, false)
+ if !ok {
+ return
+ }
+ if !s.allowWrite(Principal{Address: addr}, time.Now()) {
+ jsonError(w, http.StatusTooManyRequests, textTooManyRequests)
+ return
+ }
+ var req struct {
+ Name string `json:"name"`
+ }
+ if !readJSONStrictLimit(w, r, &req, 4<<10) {
+ return
+ }
+ name, shaped := domains.NormalizeSubdomain(req.Name)
+ if !shaped {
+ s.refuseSubdomain(w, domains.SubdomainShape, acct, req.Name, "", "", nil)
+ return
+ }
+ ctx := r.Context()
+ s.subdomainMu.Lock()
+ defer s.subdomainMu.Unlock()
+ v, err := s.loadNamespaces(ctx)
+ if err != nil {
+ log.Printf("console: subdomain set %s %s: %v", acct.Sqid, name, err)
+ s.refuseSubdomain(w, domains.SubdomainUnreadable, acct, req.Name, name, "", nil)
+ return
+ }
+ if ref, occ := s.subdomainRefusal(ctx, v, acct.Sqid, name); ref != "" {
+ s.refuseSubdomain(w, ref, acct, req.Name, name, v.byAccount[acct.Sqid], occ)
+ return
+ }
+ if v.byAccount[acct.Sqid] == name {
+ // The name the account already holds: answered again, nothing
+ // written.
+ writeJSON(w, http.StatusOK, s.subdomainShown(acct, name, nil))
+ return
+ }
+ domain := s.appsDomain()
+ host := domains.NamespaceHost(name, domain)
+ created, err := domains.AttachAccountNamespace(ctx, s.cfg.Releases, name, domain, acct.Sqid,
+ time.Now().UTC().Format(time.RFC3339), addr)
+ if err != nil {
+ log.Printf("console: subdomain set %s %s: write: %v", acct.Sqid, name, err)
+ s.refuseSubdomain(w, domains.SubdomainUnreadable, acct, req.Name, name, "", nil)
+ return
+ }
+ if !created {
+ // The key holds a claim already: the account's own namespace claim
+ // (a view that had not seen it, or a retry) is this same answer
+ // again; anything else at the key (an instance catch-all on
+ // <name>.<apps>) occupies the name.
+ cur, _, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
+ switch {
+ case err != nil:
+ log.Printf("console: subdomain set %s %s: read %s: %v", acct.Sqid, name, host, err)
+ s.refuseSubdomain(w, domains.SubdomainUnreadable, acct, req.Name, name, "", nil)
+ case cur.AccountNamespace && cur.Account == acct.Sqid:
+ // Only a claim every reader trusts as the namespace is the
+ // account's name; one they do not (pending, carrying more)
+ // is not, and reads as unread until an operator fixes it.
+ if byName, _ := domains.AccountNamespaces([]domains.Claim{*cur}, domain); byName[name] != acct.Sqid {
+ s.refuseSubdomain(w, domains.SubdomainUnreadable, acct, req.Name, name, "", nil)
+ return
+ }
+ writeJSON(w, http.StatusOK, s.subdomainShown(acct, name, nil))
+ default:
+ s.refuseSubdomain(w, domains.SubdomainOccupied, acct, req.Name, name, "",
+ []occupant{{Host: cur.Host, Account: cur.Account, App: cur.App, Source: occupantClaim}})
+ }
+ return
+ }
+ log.Printf("console: subdomain set: %s gave account %s the subdomain %s", addr, acct.Sqid, name)
+ if found, conflict := s.subdomainReread(ctx, acct.Sqid, name); conflict {
+ s.subdomainRollBack(w, ctx, acct, req.Name, name, found)
+ return
+ }
+ s.subdomainWritten(ctx)
+ writeJSON(w, http.StatusOK, s.subdomainShown(acct, name, nil))
+}
+
+// subdomainReread is set's read after its write (§4.2, the race): conflict
+// when the walk under the name fails or finds another account's host, when
+// the view does not show name as the account's, or when the account now
+// holds another name too (read, or a namespace claim naming it that did not
+// read). found is the other accounts' hosts the walk found.
+func (s *Server) subdomainReread(ctx context.Context, account, name string) (found []occupant, conflict bool) {
+ v, err := s.loadNamespaces(ctx)
+ if err != nil {
+ log.Printf("console: subdomain set %s %s: re-read: %v", account, name, err)
+ return nil, true
+ }
+ if v.byName[name] != account {
+ log.Printf("console: subdomain set %s %s: re-read does not show the name as the account's", account, name)
+ return nil, true
+ }
+ for other, a := range v.byName {
+ if a == account && other != name {
+ log.Printf("console: subdomain set %s %s: re-read: the account holds %s too", account, name, other)
+ return nil, true
+ }
+ }
+ for other := range v.unread {
+ if v.unreadBy[other] == account {
+ log.Printf("console: subdomain set %s %s: re-read: a namespace claim of the account's at %s did not read", account, name, other)
+ return nil, true
+ }
+ }
+ occ, err := s.namespaceOccupants(ctx, name)
+ if err != nil {
+ log.Printf("console: subdomain set %s %s: re-read: %v", account, name, err)
+ return nil, true
+ }
+ if found = foreignOccupants(occ, account); len(found) > 0 {
+ return found, true
+ }
+ return nil, false
+}
+
+// subdomainRollBack deletes the namespace claim set just wrote, if it is
+// still that claim, and refuses with what the re-read found. A delete that
+// fails leaves the name held: the answer is a 500 saying so and how to
+// remove it, and show reports the name. Either way the claim was written,
+// so the readers are told.
+func (s *Server) subdomainRollBack(w http.ResponseWriter, ctx context.Context, acct *Account, raw, name string, found []occupant) {
+ defer s.subdomainWritten(ctx)
+ domain := s.appsDomain()
+ host := domains.NamespaceHost(name, domain)
+ failed := func(err error) {
+ log.Printf("console: subdomain set %s %s: rollback: %v; the name is still held", acct.Sqid, name, err)
+ jsonErrorCode(w, http.StatusInternalServerError, string(domains.SubdomainRolledBack),
+ fmt.Sprintf(subdomainRefuseRollbackFailedCopy, name, acct.Sqid, acct.Sqid))
+ }
+ cur, etag, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ case err != nil:
+ failed(err)
+ return
+ case cur.AccountNamespace && cur.Account == acct.Sqid:
+ removed, err := domains.DetachAccountNamespaceAt(ctx, s.cfg.Releases, name, domain, acct.Sqid, etag)
+ if err == nil && !removed {
+ err = errors.New("the claim changed before it could be removed")
+ }
+ if err != nil {
+ failed(err)
+ return
+ }
+ }
+ log.Printf("console: subdomain set %s %s: rolled back", acct.Sqid, name)
+ s.refuseSubdomain(w, domains.SubdomainRolledBack, acct, raw, name, "", found)
+}
+
+// handleAPISubdomainDelete is remove: refused while the account itself
+// still has anything under the name (claims, records, pending allocations:
+// hosts attached by hand, which the name would otherwise orphan), or when
+// the walk fails; otherwise the namespace claim is deleted against the
+// revision read. An account with no name answers as show does, writing
+// nothing.
+func (s *Server) handleAPISubdomainDelete(w http.ResponseWriter, r *http.Request) {
+ addr, acct, ok := s.subdomainAccount(w, r, true)
+ if !ok {
+ return
+ }
+ if !s.allowWrite(Principal{Address: addr}, time.Now()) {
+ jsonError(w, http.StatusTooManyRequests, textTooManyRequests)
+ return
+ }
+ ctx := r.Context()
+ s.subdomainMu.Lock()
+ defer s.subdomainMu.Unlock()
+ domain := s.appsDomain()
+ v, err := s.loadNamespaces(ctx)
+ if err != nil {
+ log.Printf("console: subdomain remove %s: %v", acct.Sqid, err)
+ refuseSubdomainUnreadable(w, domain)
+ return
+ }
+ name := v.byAccount[acct.Sqid]
+ if name == "" {
+ if v.mayHoldUnread(acct.Sqid) {
+ refuseSubdomainUnreadable(w, domain)
+ return
+ }
+ writeJSON(w, http.StatusOK, s.subdomainShown(acct, "", nil))
+ return
+ }
+ root := s.subdomainRoot(name)
+ occ, err := s.namespaceOccupants(ctx, name)
+ if err != nil {
+ log.Printf("console: subdomain remove %s %s: %v", acct.Sqid, name, err)
+ refuseSubdomainUnreadable(w, root)
+ return
+ }
+ var own []occupant
+ for _, o := range occ {
+ if o.Account == acct.Sqid {
+ own = append(own, o)
+ }
+ }
+ if len(own) > 0 {
+ subdomainRefuse(w, http.StatusConflict, domains.SubdomainOccupied,
+ fmt.Sprintf(subdomainRefuseRemoveBlockedCopy, acct.Sqid, root), own, true)
+ return
+ }
+ host := domains.NamespaceHost(name, domain)
+ _, etag, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
+ if errors.Is(err, os.ErrNotExist) {
+ writeJSON(w, http.StatusOK, s.subdomainShown(acct, "", nil))
+ return
+ }
+ if err != nil {
+ log.Printf("console: subdomain remove %s %s: read: %v", acct.Sqid, name, err)
+ refuseSubdomainUnreadable(w, root)
+ return
+ }
+ removed, err := domains.DetachAccountNamespaceAt(ctx, s.cfg.Releases, name, domain, acct.Sqid, etag)
+ if err != nil || !removed {
+ log.Printf("console: subdomain remove %s %s: removed %v, %v", acct.Sqid, name, removed, err)
+ refuseSubdomainUnreadable(w, root)
+ return
+ }
+ log.Printf("console: subdomain remove: %s took the subdomain %s from account %s", addr, name, acct.Sqid)
+ s.subdomainWritten(ctx)
+ writeJSON(w, http.StatusOK, s.subdomainShown(acct, "", nil))
+}
+
+// subdomainInventoryLabel is one label of the inventory: a label directly
+// under the apps domain that is neither an account's sqid nor a held name,
+// and every host under it.
+type subdomainInventoryLabel struct {
+ Label string `json:"label"`
+ Hosts []occupant `json:"hosts"`
+}
+
+// handleAPISubdomainInventory is the release inventory (§4.2, "What existed
+// before"): every existing host two or more labels under the apps domain
+// whose label is neither an account's sqid nor a held name, by label, with
+// the account holding each. Strict: a read that fails is the unreadable
+// answer, never a shorter list.
+func (s *Server) handleAPISubdomainInventory(w http.ResponseWriter, r *http.Request) {
+ if _, ok := s.subdomainOperator(w, r); !ok {
+ return
+ }
+ domain := s.appsDomain()
+ labels, err := s.subdomainInventory(r.Context())
+ if err != nil {
+ log.Printf("console: subdomain inventory: %v", err)
+ refuseSubdomainUnreadable(w, domain)
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"apps_domain": domain, "labels": labels})
+}
+
+// subdomainInventory walks the claims and the declared instance records
+// under the apps domain once each.
+func (s *Server) subdomainInventory(ctx context.Context) ([]subdomainInventoryLabel, error) {
+ labels := []subdomainInventoryLabel{}
+ domain := s.appsDomain()
+ if domain == "" {
+ return labels, nil
+ }
+ if s.cfg.Releases == nil || s.store == nil {
+ return nil, errors.New("no deployment bucket or console store")
+ }
+ v, err := s.loadNamespaces(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if len(v.unread) > 0 {
+ return nil, fmt.Errorf("%d namespace claim(s) could not be read", len(v.unread))
+ }
+ claims, unread, err := s.claims.ListWithUnread(ctx, s.cfg.Releases)
+ if err != nil {
+ return nil, err
+ }
+ under := func(host string) (string, bool) {
+ label, depth := s.appsLabel(strings.TrimPrefix(host, "*."))
+ return label, depth >= 2
+ }
+ for _, u := range unread {
+ if _, ok := under(u.Host); ok {
+ return nil, fmt.Errorf("claim %s could not be read", u.Host)
+ }
+ }
+ var hosts []occupant
+ for _, c := range claims {
+ if _, ok := under(c.Host); ok && !c.AccountNamespace {
+ hosts = append(hosts, occupant{Host: c.Host, Account: c.Account, App: c.App, Source: occupantClaim})
+ }
+ }
+ records, err := provision.RecordHostDeclaredUnder(ctx, s.cfg.Releases, domain)
+ if err != nil {
+ return nil, err
+ }
+ for _, rec := range records {
+ if _, ok := under(rec.Host); ok {
+ hosts = append(hosts, occupant{Host: rec.Host, Account: rec.Account, App: rec.App, Source: occupantRecord})
+ }
+ }
+ // assigned answers whether label is an account's sqid (live or
+ // deleted) or a held name, once per label.
+ assigned := map[string]bool{}
+ isAssigned := func(label string) (bool, error) {
+ if got, ok := assigned[label]; ok {
+ return got, nil
+ }
+ held := v.byName[label] != ""
+ if !held && domains.ValidSqid(label) {
+ a, _, err := s.store.AccountAnyBySqid(label)
+ if err != nil {
+ return false, fmt.Errorf("account %s: %w", label, err)
+ }
+ held = a != nil
+ }
+ assigned[label] = held
+ return held, nil
+ }
+ byLabel := map[string][]occupant{}
+ for _, h := range hosts {
+ label, _ := under(h.Host)
+ held, err := isAssigned(label)
+ if err != nil {
+ return nil, err
+ }
+ if !held {
+ byLabel[label] = append(byLabel[label], h)
+ }
+ }
+ for label, hs := range byLabel {
+ sort.Slice(hs, func(i, j int) bool {
+ a, b := hs[i], hs[j]
+ if a.Host != b.Host {
+ return a.Host < b.Host
+ }
+ if a.Account != b.Account {
+ return a.Account < b.Account
+ }
+ return a.Source < b.Source
+ })
+ labels = append(labels, subdomainInventoryLabel{Label: label, Hosts: hs})
+ }
+ sort.Slice(labels, func(i, j int) bool { return labels[i].Label < labels[j].Label })
+ return labels, nil
+}
+
+// accountSubdomainPane fills the account settings page's read-only
+// Subdomain cell: the name the account holds, or none. When that cannot be
+// told (the view did not load, or a namespace claim that may be the
+// account's did not read), the cell is left out rather than saying "None".
+func (s *Server) accountSubdomainPane(ctx context.Context, p *page, acct *Account) {
+ if s.appsDomain() == "" {
+ p.AccountSubdomainKnown = true
+ return
+ }
+ v, err := s.loadNamespaces(ctx)
+ if err != nil {
+ log.Printf("console: account settings %s: subdomain: %v", acct.Sqid, err)
+ return
+ }
+ if name := v.byAccount[acct.Sqid]; name != "" {
+ p.AccountSubdomain, p.AccountSubdomainKnown = name, true
+ return
+ }
+ p.AccountSubdomainKnown = !v.mayHoldUnread(acct.Sqid)
+}
diff --git a/internal/console/apisubdomain_test.go b/internal/console/apisubdomain_test.go
new file mode 100644
index 000000000..4655c61ac
--- /dev/null
+++ b/internal/console/apisubdomain_test.go
@@ -0,0 +1,550 @@
+package console
+
+// Account subdomains, Task 6 (spec docs/superpowers/specs/
+// 2026-11-11-account-subdomains-design.md §4.3): the operator-only door that
+// sets, shows and removes an account's subdomain, and the system inventory
+// door. Neutral names: the fixture account is bab (the ops account), bdq and
+// bcd are the other accounts, harbour the name, oncarlos.com the apps
+// domain.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// sdHost is one occupant as the door answers it.
+type sdHost struct {
+ Host string `json:"host"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Source string `json:"source"`
+}
+
+// sdAnswer is every field the subdomain door answers, success or refusal.
+type sdAnswer struct {
+ Account string `json:"account"`
+ Name string `json:"name"`
+ Host string `json:"host"`
+ Foreign []sdHost `json:"foreign"`
+ Error string `json:"error"`
+ Code string `json:"code"`
+ Hosts []sdHost `json:"hosts"`
+}
+
+func sdURL(fx *consoleFixture, acct string) string {
+ return fx.ts.URL + "/api/cli/accounts/" + acct + "/subdomain"
+}
+
+// sdReq sends one request to acct's subdomain door.
+func sdReq(t *testing.T, fx *consoleFixture, method, acct, token, body string) (int, sdAnswer, string) {
+ t.Helper()
+ code, _, out := rawReq(t, method, sdURL(fx, acct), token, body)
+ var a sdAnswer
+ _ = json.Unmarshal([]byte(out), &a)
+ return code, a, out
+}
+
+// sdFixture is nsShopFixture with account bdq and its owner's CLI token.
+func sdFixture(t *testing.T, code string) (fx *consoleFixture, operator, bdqOwner string) {
+ t.Helper()
+ fx, _, operator = nsShopFixture(t, code)
+ nsAccount(t, fx, 82, "bdq")
+ return fx, operator, cliToken(t, fx, "bdq@example.com", code+"-bdq")
+}
+
+// nsClaimAt reads the claim at host, nil when there is none.
+func nsClaimAt(t *testing.T, fx *consoleFixture, host string) *domains.Claim {
+ t.Helper()
+ c, err := domains.GetClaim(context.Background(), fx.rel, host)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ t.Fatalf("read claim %s: %v", host, err)
+ }
+ return c
+}
+
+// nsHarbourHost is harbour's namespace claim host.
+var nsHarbourHost = domains.NamespaceHost("harbour", nsApps)
+
+// nsRaceStore runs after once, right after the first successful Put of key,
+// as another writer landing between the door's write and its re-read would.
+// failDelete makes every conditional delete fail. It embeds release.Store
+// only, so the claim cache takes its plain List path.
+type nsRaceStore struct {
+ release.Store
+ key string
+ after func()
+ once sync.Once
+ failDelete bool
+}
+
+func (s *nsRaceStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ etag, err := s.Store.Put(ctx, key, body, ifMatch)
+ if err == nil && key == s.key && s.after != nil {
+ s.once.Do(s.after)
+ }
+ return etag, err
+}
+
+func (s *nsRaceStore) DeleteIfMatch(ctx context.Context, key, etag string) error {
+ if s.failDelete {
+ return errors.New("nsRaceStore: delete refused")
+ }
+ return release.DeleteIfMatch(ctx, s.Store, key, etag)
+}
+
+// TestSubdomainDoorOperatorOnly: only a platform operator, as a person,
+// reaches the door. The owner of bdq who is not an operator gets the 404
+// with the not-operator answer and writes nothing; an app token is refused;
+// an owner of the ops account and an address on SystemOperators get in.
+func TestSubdomainDoorOperatorOnly(t *testing.T) {
+ fx, operator, bdqOwner := sdFixture(t, "code-sd-operator")
+ member := cliToken(t, fx, nsActor, "code-sd-operator-member")
+ for _, tok := range []string{bdqOwner, member} {
+ for _, m := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
+ code, a, out := sdReq(t, fx, m, "bdq", tok, `{"name":"harbour"}`)
+ if code != http.StatusNotFound || a.Error != subdomainRefuseNotOperatorCopy {
+ t.Errorf("%s by a non-operator = %d %s, want 404 %q", m, code, out, subdomainRefuseNotOperatorCopy)
+ }
+ }
+ }
+ app := serviceToken(t, fx.st, OpsAccountID, "svc-sd", "shop", svcrole.Admin)
+ if code, _, out := sdReq(t, fx, http.MethodPost, "bdq", app, `{"name":"harbour"}`); code == http.StatusOK {
+ t.Errorf("POST by an app token = %d %s, want refused", code, out)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c != nil {
+ t.Fatalf("a refused caller wrote %+v", c)
+ }
+ if code, _, out := sdReq(t, fx, http.MethodGet, "bdq", operator, ""); code != http.StatusOK {
+ t.Errorf("GET by an ops owner = %d %s, want 200", code, out)
+ }
+ fx.srv.cfg.SystemOperators = []string{"sys@example.com"}
+ sys := cliToken(t, fx, "sys@example.com", "code-sd-operator-sys")
+ if code, _, out := sdReq(t, fx, http.MethodGet, "bdq", sys, ""); code != http.StatusOK {
+ t.Errorf("GET by a system operator = %d %s, want 200", code, out)
+ }
+ if code, _, _ := sdReq(t, fx, http.MethodGet, "bzz", operator, ""); code != http.StatusNotFound {
+ t.Errorf("GET of an account nobody holds = %d, want 404", code)
+ }
+}
+
+// TestSubdomainDoorSetShowRemove: set writes the namespace claim and answers
+// the name and its host; show answers the same; a second, different name is
+// refused (remove first); remove deletes the claim and show then has none.
+func TestSubdomainDoorSetShowRemove(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-ssr")
+ want := sdAnswer{Account: "bdq", Name: "harbour", Host: "harbour." + nsApps, Foreign: []sdHost{}}
+ code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":" Harbour "}`)
+ if code != http.StatusOK || !reflect.DeepEqual(a, want) {
+ t.Fatalf("set harbour = %d %s, want 200 %+v", code, out, want)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c == nil || !c.AccountNamespace || c.Account != "bdq" {
+ t.Fatalf("namespace claim after set = %+v", c)
+ }
+ if code, a, out := sdReq(t, fx, http.MethodGet, "bdq", operator, ""); code != http.StatusOK || !reflect.DeepEqual(a, want) {
+ t.Errorf("show = %d %s, want 200 %+v", code, out, want)
+ }
+ code, a, out = sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"marina"}`)
+ if want := fmt.Sprintf(subdomainRefuseHasOneCopy, "bdq", "harbour"); code != http.StatusConflict || a.Error != want || a.Code != string(domains.SubdomainAccountHasOne) {
+ t.Errorf("set a second name = %d %s, want 409 %q", code, out, want)
+ }
+ if c := nsClaimAt(t, fx, domains.NamespaceHost("marina", nsApps)); c != nil {
+ t.Errorf("the refused second name wrote %+v", c)
+ }
+ code, a, out = sdReq(t, fx, http.MethodDelete, "bdq", operator, "")
+ if code != http.StatusOK || a.Name != "" || a.Account != "bdq" {
+ t.Fatalf("remove = %d %s, want 200 with no name", code, out)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c != nil {
+ t.Errorf("namespace claim after remove = %+v", c)
+ }
+ if code, a, out := sdReq(t, fx, http.MethodGet, "bdq", operator, ""); code != http.StatusOK || a.Name != "" || a.Host != "" {
+ t.Errorf("show after remove = %d %s, want no name", code, out)
+ }
+ for _, c := range []struct{ body, want, code string }{
+ {`{"name":"bad_name"}`, fmt.Sprintf(subdomainRefuseShapeCopy, "bad_name"), string(domains.SubdomainShape)},
+ {`{"name":"www"}`, fmt.Sprintf(subdomainRefuseReservedCopy, "www"), string(domains.SubdomainReserved)},
+ {`{"name":"bcd"}`, fmt.Sprintf(subdomainRefuseSqidShapedCopy, "bcd"), string(domains.SubdomainSqidShaped)},
+ } {
+ code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, c.body)
+ if code != http.StatusUnprocessableEntity || a.Error != c.want || a.Code != c.code {
+ t.Errorf("set %s = %d %s, want 422 %q", c.body, code, out, c.want)
+ }
+ }
+}
+
+// TestSubdomainDoorRollsBackOnRace: another account's claim lands under the
+// name right after the door's write. The re-read sees it, the door deletes
+// its own claim again and refuses, listing what it found.
+func TestSubdomainDoorRollsBackOnRace(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-race")
+ nsAccount(t, fx, 49, "bcd")
+ foreign := domains.Claim{Schema: 1, Host: "x.harbour." + nsApps, Account: "bcd", App: "web", CreatedAt: time.Now().UTC().Format(time.RFC3339)}
+ fx.srv.cfg.Releases = &nsRaceStore{Store: fx.rel, key: domains.ClaimKey(nsHarbourHost), after: func() { nsPutClaim(t, fx, foreign) }}
+ fx.srv.claims.Reset()
+ code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"harbour"}`)
+ want := fmt.Sprintf(subdomainRefuseRolledBackCopy, "harbour."+nsApps)
+ if code != http.StatusConflict || a.Error != want || a.Code != string(domains.SubdomainRolledBack) {
+ t.Fatalf("set under a race = %d %s, want 409 %q", code, out, want)
+ }
+ if wantHosts := []sdHost{{Host: foreign.Host, Account: "bcd", App: "web", Source: occupantClaim}}; !reflect.DeepEqual(a.Hosts, wantHosts) {
+ t.Errorf("rolled-back list = %+v, want %+v", a.Hosts, wantHosts)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c != nil {
+ t.Errorf("the rolled-back namespace claim is still there: %+v", c)
+ }
+}
+
+// TestSubdomainDoorRollsBackSecondName: a second name for the same account
+// appears after the write (a direct bucket write). The door removes its own
+// claim and refuses; the other name is not the door's to remove.
+func TestSubdomainDoorRollsBackSecondName(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-second")
+ fx.srv.cfg.Releases = &nsRaceStore{Store: fx.rel, key: domains.ClaimKey(nsHarbourHost), after: func() { nsHold(t, fx, "marina", "bdq") }}
+ fx.srv.claims.Reset()
+ code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"harbour"}`)
+ if want := fmt.Sprintf(subdomainRefuseRolledBackCopy, "harbour."+nsApps); code != http.StatusConflict || a.Error != want {
+ t.Fatalf("set while a second name lands = %d %s, want 409 %q", code, out, want)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c != nil {
+ t.Errorf("the rolled-back namespace claim is still there: %+v", c)
+ }
+ if c := nsClaimAt(t, fx, domains.NamespaceHost("marina", nsApps)); c == nil {
+ t.Error("the rollback removed the other name too")
+ }
+}
+
+// TestSubdomainRollbackFailureReportsHeld: the rollback's own delete fails.
+// The door answers 500 saying the name is still held and to run remove, and
+// show reports the name.
+func TestSubdomainRollbackFailureReportsHeld(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-rbfail")
+ nsAccount(t, fx, 49, "bcd")
+ foreign := domains.Claim{Schema: 1, Host: "x.harbour." + nsApps, Account: "bcd", App: "web", CreatedAt: time.Now().UTC().Format(time.RFC3339)}
+ fx.srv.cfg.Releases = &nsRaceStore{Store: fx.rel, key: domains.ClaimKey(nsHarbourHost), failDelete: true,
+ after: func() { nsPutClaim(t, fx, foreign) }}
+ fx.srv.claims.Reset()
+ code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"harbour"}`)
+ want := fmt.Sprintf(subdomainRefuseRollbackFailedCopy, "harbour", "bdq", "bdq")
+ if code != http.StatusInternalServerError || a.Error != want {
+ t.Fatalf("set whose rollback fails = %d %s, want 500 %q", code, out, want)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c == nil {
+ t.Fatal("the namespace claim is gone, yet the door said it is held")
+ }
+ code, a, out = sdReq(t, fx, http.MethodGet, "bdq", operator, "")
+ if code != http.StatusOK || a.Name != "harbour" || len(a.Foreign) != 1 || a.Foreign[0].Host != foreign.Host {
+ t.Errorf("show after a failed rollback = %d %s, want harbour with the foreign host", code, out)
+ }
+}
+
+// TestSubdomainSetIdempotent: setting the name the account already holds
+// answers it again and writes nothing, also when the view is stale and the
+// create-only write finds the account's own claim at the key.
+func TestSubdomainSetIdempotent(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-idem")
+ want := sdAnswer{Account: "bdq", Name: "harbour", Host: "harbour." + nsApps, Foreign: []sdHost{}}
+ for i := 0; i < 2; i++ {
+ if code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"harbour"}`); code != http.StatusOK || !reflect.DeepEqual(a, want) {
+ t.Fatalf("set harbour (%d) = %d %s, want 200 %+v", i+1, code, out, want)
+ }
+ }
+ if got := serial(t, fx); got != 1 {
+ t.Errorf("serial after one effective set and one repeat = %d, want 1", got)
+ }
+ // The stale view: the key already holds bdq's claim, but the listing the
+ // door judges from does not show it.
+ fx2, operator2, _ := sdFixture(t, "code-sd-idem-stale")
+ nsHold(t, fx2, "harbour", "bdq")
+ fx2.srv.cfg.Releases = &nsHideKeyStore{Store: fx2.rel, key: domains.ClaimKey(nsHarbourHost)}
+ fx2.srv.claims.Reset()
+ if code, a, out := sdReq(t, fx2, http.MethodPost, "bdq", operator2, `{"name":"harbour"}`); code != http.StatusOK || a.Name != "harbour" {
+ t.Errorf("set over its own unlisted claim = %d %s, want 200 harbour", code, out)
+ }
+ if got := serial(t, fx2); got != 0 {
+ t.Errorf("serial after a no-op set = %d, want 0", got)
+ }
+}
+
+// nsHideKeyStore leaves key out of every listing: a view that has not seen
+// a claim already written.
+type nsHideKeyStore struct {
+ release.Store
+ key string
+}
+
+func (s *nsHideKeyStore) List(ctx context.Context, prefix string) ([]string, error) {
+ keys, err := s.Store.List(ctx, prefix)
+ out := keys[:0:0]
+ for _, k := range keys {
+ if k != s.key {
+ out = append(out, k)
+ }
+ }
+ return out, err
+}
+
+// TestSubdomainSetRefusedOverCatchallKey: an instance catch-all on
+// harbour.<apps> sits at the namespace claim's key. Another account's is
+// an occupant; bdq's own passes the walk and is found by the create-only
+// write instead. Both are refused as occupied, and nothing is written.
+func TestSubdomainSetRefusedOverCatchallKey(t *testing.T) {
+ for _, owner := range []string{"bcd", "bdq"} {
+ t.Run(owner, func(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-catchall-"+owner)
+ nsAccount(t, fx, 49, "bcd")
+ catchall := domains.Claim{Schema: 1, Host: nsHarbourHost, Account: owner, App: "web", Instances: true,
+ CreatedAt: time.Now().UTC().Format(time.RFC3339)}
+ nsPutClaim(t, fx, catchall)
+ code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"harbour"}`)
+ if want := fmt.Sprintf(subdomainRefuseOccupiedCopy, "harbour."+nsApps); code != http.StatusConflict || a.Error != want || a.Code != string(domains.SubdomainOccupied) {
+ t.Errorf("set over %s's catch-all = %d %s, want 409 %q", owner, code, out, want)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c == nil || c.AccountNamespace || !c.Instances {
+ t.Errorf("the catch-all changed: %+v", c)
+ }
+ if got := serial(t, fx); got != 0 {
+ t.Errorf("serial after a refused set = %d, want 0", got)
+ }
+ })
+ }
+}
+
+// TestSubdomainShowListsForeign: show lists the hosts other accounts have
+// under the name (a claim and a record, both direct bucket writes), never
+// the account's own.
+func TestSubdomainShowListsForeign(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-foreign")
+ nsAccount(t, fx, 49, "bcd")
+ nsHold(t, fx, "harbour", "bdq")
+ now := time.Now().UTC()
+ nsPutClaim(t, fx, domains.Claim{Schema: 1, Host: "x.harbour." + nsApps, Account: "bcd", App: "web", CreatedAt: now.Format(time.RFC3339)})
+ nsPutClaim(t, fx, domains.Claim{Schema: 1, Host: "blog.harbour." + nsApps, Account: "bdq", App: "blog", CreatedAt: now.Format(time.RFC3339)})
+ if err := provision.CreateRecord(context.Background(), fx.rel, provision.Record{Schema: 1, Host: "y.harbour." + nsApps, Slug: "y", App: "web",
+ Account: "bcd", Channel: "stable", CreatedAt: now}); err != nil {
+ t.Fatal(err)
+ }
+ code, a, out := sdReq(t, fx, http.MethodGet, "bdq", operator, "")
+ want := []sdHost{
+ {Host: "x.harbour." + nsApps, Account: "bcd", App: "web", Source: occupantClaim},
+ {Host: "y.harbour." + nsApps, Account: "bcd", App: "web", Source: occupantRecord},
+ }
+ if code != http.StatusOK || a.Name != "harbour" || !reflect.DeepEqual(a.Foreign, want) {
+ t.Errorf("show = %d %s, want harbour with %+v", code, out, want)
+ }
+}
+
+// TestSubdomainShowUnreadableIsNotEmpty: a walk that fails answers the
+// unreadable refusal, never a name with an empty foreign list.
+func TestSubdomainShowUnreadableIsNotEmpty(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-show-unread")
+ nsHold(t, fx, "harbour", "bdq")
+ fx.srv.cfg.Releases = &nsFaultStore{Store: fx.rel, failList: "accounts/"}
+ fx.srv.claims.Reset()
+ code, a, out := sdReq(t, fx, http.MethodGet, "bdq", operator, "")
+ want := fmt.Sprintf(subdomainRefuseUnreadableCopy, "harbour."+nsApps)
+ if code != http.StatusBadGateway || a.Error != want || a.Code != string(domains.SubdomainUnreadable) {
+ t.Errorf("show with the record walk down = %d %s, want 502 %q", code, out, want)
+ }
+ // A namespace claim that does not read may be bdq's: show cannot say
+ // bdq has none.
+ fx2, operator2, _ := sdFixture(t, "code-sd-show-unread2")
+ nsHold(t, fx2, "harbour", "bdq")
+ fx2.srv.cfg.Releases = &nsFaultStore{Store: fx2.rel, failGet: domains.ClaimKey(nsHarbourHost)}
+ fx2.srv.claims.Reset()
+ if code, a, out := sdReq(t, fx2, http.MethodGet, "bdq", operator2, ""); code != http.StatusBadGateway || a.Code != string(domains.SubdomainUnreadable) {
+ t.Errorf("show with its namespace claim unread = %d %s, want 502 unreadable", code, out)
+ }
+}
+
+// TestSubdomainRemoveRefusedWhileHandAttached: remove is refused while bdq
+// still has a claim of its own under the name, and lists it.
+func TestSubdomainRemoveRefusedWhileHandAttached(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-rm-hand")
+ nsHold(t, fx, "harbour", "bdq")
+ nsPutClaim(t, fx, domains.Claim{Schema: 1, Host: "blog.harbour." + nsApps, Account: "bdq", App: "blog", CreatedAt: time.Now().UTC().Format(time.RFC3339)})
+ code, a, out := sdReq(t, fx, http.MethodDelete, "bdq", operator, "")
+ want := fmt.Sprintf(subdomainRefuseRemoveBlockedCopy, "bdq", "harbour."+nsApps)
+ if code != http.StatusConflict || a.Error != want {
+ t.Fatalf("remove with a hand-attached claim = %d %s, want 409 %q", code, out, want)
+ }
+ if wantHosts := []sdHost{{Host: "blog.harbour." + nsApps, Account: "bdq", App: "blog", Source: occupantClaim}}; !reflect.DeepEqual(a.Hosts, wantHosts) {
+ t.Errorf("remove refusal lists %+v, want %+v", a.Hosts, wantHosts)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c == nil {
+ t.Error("a refused remove deleted the namespace claim")
+ }
+ if got := serial(t, fx); got != 0 {
+ t.Errorf("serial after a refused remove = %d, want 0", got)
+ }
+}
+
+// TestSubdomainRemoveRefusedOverOwnRecordOrAllocation: an instance record of
+// bdq's under the name blocks remove like a claim; a failed walk refuses
+// too, retryably.
+func TestSubdomainRemoveRefusedOverOwnRecordOrAllocation(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-rm-record")
+ nsHold(t, fx, "harbour", "bdq")
+ if err := provision.CreateRecord(context.Background(), fx.rel, provision.Record{Schema: 1, Host: "c1.harbour." + nsApps, Slug: "c1", App: "shop",
+ Account: "bdq", Channel: "stable", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ code, a, out := sdReq(t, fx, http.MethodDelete, "bdq", operator, "")
+ if code != http.StatusConflict || len(a.Hosts) != 1 || a.Hosts[0].Source != occupantRecord {
+ t.Errorf("remove over bdq's record = %d %s, want 409 listing the record", code, out)
+ }
+ fx.srv.cfg.Releases = &nsFaultStore{Store: fx.rel, failList: "accounts/"}
+ fx.srv.claims.Reset()
+ code, a, out = sdReq(t, fx, http.MethodDelete, "bdq", operator, "")
+ if code != http.StatusBadGateway || a.Code != string(domains.SubdomainUnreadable) {
+ t.Errorf("remove with the walk down = %d %s, want 502 unreadable", code, out)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c == nil {
+ t.Error("a refused remove deleted the namespace claim")
+ }
+
+ // A pending allocation of bab's (a create stopped before its record)
+ // under bab's name.
+ fx2, operator2, _ := sdFixture(t, "code-sd-rm-alloc")
+ nsHold(t, fx2, "marina", fx2.sqid)
+ if err := fx2.st.BeginAllocation(testAllocation("op-sd", "c2.marina."+nsApps, 1)); err != nil {
+ t.Fatal(err)
+ }
+ code, a, out = sdReq(t, fx2, http.MethodDelete, fx2.sqid, operator2, "")
+ if code != http.StatusConflict || len(a.Hosts) != 1 || a.Hosts[0].Source != occupantAllocation {
+ t.Errorf("remove over a pending allocation = %d %s, want 409 listing it", code, out)
+ }
+}
+
+// TestSubdomainRemoveForDeletedAccount: a deleted account keeps its claim;
+// show and remove still find the account, set does not.
+func TestSubdomainRemoveForDeletedAccount(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-deleted")
+ nsHold(t, fx, "harbour", "bdq")
+ if err := fx.st.DeleteAccount(82, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if code, a, out := sdReq(t, fx, http.MethodGet, "bdq", operator, ""); code != http.StatusOK || a.Name != "harbour" {
+ t.Errorf("show of a deleted account = %d %s, want harbour", code, out)
+ }
+ if code, _, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"marina"}`); code != http.StatusNotFound {
+ t.Errorf("set on a deleted account = %d %s, want 404", code, out)
+ }
+ if code, a, out := sdReq(t, fx, http.MethodDelete, "bdq", operator, ""); code != http.StatusOK || a.Name != "" {
+ t.Errorf("remove on a deleted account = %d %s, want 200", code, out)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c != nil {
+ t.Errorf("namespace claim after remove = %+v", c)
+ }
+}
+
+// TestSubdomainDoorRefusedWithHostClaim: with host claims on, every method
+// of both doors refuses after the operator gate and writes nothing.
+func TestSubdomainDoorRefusedWithHostClaim(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-hostclaim")
+ fx.srv.cfg.HostClaim = true
+ for _, m := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
+ code, a, out := sdReq(t, fx, m, "bdq", operator, `{"name":"harbour"}`)
+ if code != http.StatusConflict || a.Error != subdomainRefuseHostClaimsCopy {
+ t.Errorf("%s with host claims on = %d %s, want 409 %q", m, code, out, subdomainRefuseHostClaimsCopy)
+ }
+ }
+ code, _, out := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/system/subdomain-inventory", operator, "")
+ if code != http.StatusConflict || jsonErrorText(t, out) != subdomainRefuseHostClaimsCopy {
+ t.Errorf("inventory with host claims on = %d %s, want 409", code, out)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c != nil {
+ t.Errorf("a refused set wrote %+v", c)
+ }
+}
+
+// TestSubdomainWritesBumpSerial: an effective set and remove each bump the
+// serial; a refused set, a repeated set and a remove with nothing to remove
+// do not.
+func TestSubdomainWritesBumpSerial(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-serial")
+ step := func(method, body string, want int64) {
+ t.Helper()
+ sdReq(t, fx, method, "bdq", operator, body)
+ if got := serial(t, fx); got != want {
+ t.Errorf("%s %s: serial %d, want %d", method, body, got, want)
+ }
+ }
+ step(http.MethodPost, `{"name":"www"}`, 0)
+ step(http.MethodPost, `{"name":"harbour"}`, 1)
+ step(http.MethodPost, `{"name":"harbour"}`, 1)
+ step(http.MethodPost, `{"name":"marina"}`, 1)
+ step(http.MethodDelete, "", 2)
+ step(http.MethodDelete, "", 2)
+}
+
+// TestSubdomainInventory: every host two or more labels under the apps
+// domain whose label is neither an account's sqid nor a held name, grouped
+// by label with its account. A failed walk is an error, not an empty list.
+func TestSubdomainInventory(t *testing.T) {
+ fx, operator, bdqOwner := sdFixture(t, "code-sd-inventory")
+ now := time.Now().UTC()
+ put := func(host, account string) {
+ nsPutClaim(t, fx, domains.Claim{Schema: 1, Host: host, Account: account, App: "web", CreatedAt: now.Format(time.RFC3339)})
+ }
+ put("x.team."+nsApps, "bdq") // legacy, under an unassigned label
+ put("shop.bdq."+nsApps, "bdq") // under bdq's own sqid
+ put("shop."+fx.sqid+"."+nsApps, fx.sqid) // under bab's own sqid
+ put("team."+nsApps, "bdq") // one label: not under a label
+ put("shop.example.com", "bdq") // not under the apps domain
+ nsHold(t, fx, "harbour", "bdq")
+ put("blog.harbour."+nsApps, "bdq") // under a held name
+ if err := provision.CreateRecord(context.Background(), fx.rel, provision.Record{Schema: 1, Host: "z.pier." + nsApps, Slug: "z", App: "web",
+ Account: "bdq", Channel: "stable", CreatedAt: now}); err != nil {
+ t.Fatal(err)
+ }
+ u := fx.ts.URL + "/api/cli/system/subdomain-inventory"
+ if code, _, out := rawReq(t, http.MethodGet, u, bdqOwner, ""); code != http.StatusNotFound {
+ t.Errorf("inventory by a non-operator = %d %s, want 404", code, out)
+ }
+ code, _, out := rawReq(t, http.MethodGet, u, operator, "")
+ type label struct {
+ Label string `json:"label"`
+ Hosts []sdHost `json:"hosts"`
+ }
+ var got struct {
+ AppsDomain string `json:"apps_domain"`
+ Labels []label `json:"labels"`
+ }
+ if err := json.Unmarshal([]byte(out), &got); code != http.StatusOK || err != nil {
+ t.Fatalf("inventory = %d %s (%v)", code, out, err)
+ }
+ want := []label{
+ {Label: "pier", Hosts: []sdHost{{Host: "z.pier." + nsApps, Account: "bdq", App: "web", Source: occupantRecord}}},
+ {Label: "team", Hosts: []sdHost{{Host: "x.team." + nsApps, Account: "bdq", App: "web", Source: occupantClaim}}},
+ }
+ if got.AppsDomain != nsApps || !reflect.DeepEqual(got.Labels, want) {
+ t.Errorf("inventory = %+v, want %s %+v", got, nsApps, want)
+ }
+ for _, fail := range []*nsFaultStore{
+ {Store: fx.rel, failList: "accounts/"},
+ {Store: fx.rel, failList: domains.ClaimsPrefix},
+ {Store: fx.rel, failGet: domains.ClaimKey("x.team." + nsApps)},
+ } {
+ fx.srv.cfg.Releases = fail
+ fx.srv.claims.Reset()
+ if code, _, out := rawReq(t, http.MethodGet, u, operator, ""); code != http.StatusBadGateway {
+ t.Errorf("inventory with %+v = %d %s, want 502", fail, code, out)
+ }
+ }
+}
diff --git a/internal/console/canonical.go b/internal/console/canonical.go
new file mode 100644
index 000000000..004e2c1ff
--- /dev/null
+++ b/internal/console/canonical.go
@@ -0,0 +1,192 @@
+package console
+
+// The name URL is canonical (account subdomains spec §4.8). Wherever an
+// account holds a subdomain, every console page and API answer that shows an
+// app URL gives <prefix>.<name>.<apps-domain> in place of
+// <prefix>.<sqid>.<apps-domain>, and the sqid URL stays underneath as the
+// permanent address. The rule lives in one pure function, canonicalHostIn;
+// a request reads the namespace view at most once (hostCanon, one claim
+// listing) and rewrites every host it shows from it.
+//
+// Only display changes. Identity keeps the sqid host: CARLOS_HOST, apexHost,
+// probe targets, instance detail paths, logs, restart and update form
+// actions, and every record, route and registry row. A custom domain is
+// never under the apps domain, so it is never rewritten and keeps whatever
+// precedence it has (apexHost picks among the hosts as they are; the pick is
+// rewritten afterwards).
+
+import (
+ "context"
+ "log"
+ "strings"
+ "sync"
+)
+
+// canonicalHostIn is host as the platform shows it: for a host
+// <prefix>.<sqid>.<appsDomain> of an account that holds a name in v, it is
+// <prefix>.<name>.<appsDomain>; anything else (a custom domain, the label
+// itself, an account with no name, no apps domain) is host unchanged.
+func canonicalHostIn(v namespaceView, appsDomain, host string) string {
+ if appsDomain == "" || host == "" {
+ return host
+ }
+ rest, ok := strings.CutSuffix(host, "."+appsDomain)
+ if !ok {
+ return host
+ }
+ dot := strings.LastIndex(rest, ".")
+ if dot <= 0 {
+ return host
+ }
+ name := v.byAccount[rest[dot+1:]]
+ if name == "" {
+ return host
+ }
+ return rest[:dot] + "." + name + "." + appsDomain
+}
+
+// hostCanon is one request's canonical hosts: the namespace view, read the
+// first time a host that could need it (two or more labels under the apps
+// domain) is asked about, and never again in the request. A view that fails
+// to load is logged and leaves every host unchanged. A nil *hostCanon
+// changes nothing.
+type hostCanon struct {
+ s *Server
+ ctx context.Context
+ once sync.Once
+ v namespaceView
+}
+
+// canon is the request's hostCanon. Callers build one per request and hand
+// it to every place that shows a host.
+func (s *Server) canon(ctx context.Context) *hostCanon {
+ return &hostCanon{s: s, ctx: ctx}
+}
+
+// host is h as the platform shows it (canonicalHostIn).
+func (c *hostCanon) host(h string) string {
+ if c == nil {
+ return h
+ }
+ if _, depth := c.s.appsLabel(h); depth < 2 {
+ return h
+ }
+ c.once.Do(func() {
+ v, err := c.s.loadNamespaces(c.ctx)
+ if err != nil {
+ log.Printf("console: canonical hosts: %v; showing sqid hosts", err)
+ return
+ }
+ c.v = v
+ })
+ return canonicalHostIn(c.v, c.s.appsDomain(), h)
+}
+
+// public is h's public_host on an API answer: the shown host when it is
+// not h itself, else "" (the field is omitted, and a client prints host,
+// so an answer about a host with no name is the bytes it always was).
+func (c *hostCanon) public(h string) string {
+ if p := c.host(h); p != h {
+ return p
+ }
+ return ""
+}
+
+// derivesName reports whether a box derives a name host for a route like
+// this one (domains.ReconcileNamespaceAliases: provisioned or platform
+// routes, never a sidecar). A hand-added route gets no name alias, so its
+// name URL would not answer, and it is shown as it is.
+func derivesName(provisioned, platform bool, kind string) bool {
+ return (provisioned || platform) && kind != "sidecar"
+}
+
+// canonicalViews sets the shown host of every host views carry: each
+// route's PublicHost (for a route whose name a box derives), and from those
+// each canary's PublicHosts and each ladder route's PublicHost. Host stays
+// as it is everywhere.
+func (c *hostCanon) canonicalViews(views []AppView) {
+ for i := range views {
+ v := &views[i]
+ shown := map[string]string{}
+ for j := range v.Routes {
+ rt := &v.Routes[j]
+ if derivesName(rt.Provisioned, rt.Platform, rt.Kind) {
+ rt.PublicHost = c.host(rt.Host)
+ shown[rt.Host] = rt.PublicHost
+ }
+ }
+ for j := range v.Canaries {
+ cv := &v.Canaries[j]
+ cv.PublicHosts = make([]string, len(cv.Hosts))
+ for k, h := range cv.Hosts {
+ cv.PublicHosts[k] = shownHost(h, shown[h])
+ }
+ }
+ for _, rung := range v.Ladder {
+ for _, ch := range rung.Channels {
+ for k := range ch.Routes {
+ ch.Routes[k].PublicHost = shown[ch.Routes[k].Host]
+ }
+ }
+ }
+ }
+}
+
+// shownHost is public when it is set, else host: the host a page shows and
+// links to. A view built without a hostCanon shows its hosts as they are.
+func shownHost(host, public string) string {
+ if public != "" {
+ return public
+ }
+ return host
+}
+
+// shownRouteHost is host as routes show it: the PublicHost of the route at
+// host, or host itself when no route is there or none carries one.
+func shownRouteHost(routes []RouteView, host string) string {
+ for _, rt := range routes {
+ if rt.Host == host {
+ return shownHost(rt.Host, rt.PublicHost)
+ }
+ }
+ return host
+}
+
+// appApex is the app page's address, apexHost over the viewed account's own
+// routes (summarize's rule), as it is and as it is shown.
+func (p page) appApex() (host, shown string) {
+ if p.Detail == nil || p.Account == nil {
+ return "", ""
+ }
+ var mine []RouteView
+ for _, rt := range p.Detail.Routes {
+ if rt.Account == p.Account.Sqid {
+ mine = append(mine, rt)
+ }
+ }
+ host = apexHost(mine)
+ return host, shownRouteHost(mine, host)
+}
+
+// AppNameURL is the app header's link, the app's name URL: set only when
+// the account has a subdomain and the app's address is under its sqid, so
+// every other app's header is as it was.
+func (p page) AppNameURL() string {
+ if host, shown := p.appApex(); shown != host {
+ return shown
+ }
+ return ""
+}
+
+// AppPermanentURL is the sqid URL the header shows under AppNameURL, as
+// the permanent address; "" whenever AppNameURL is.
+func (p page) AppPermanentURL() string {
+ if host, shown := p.appApex(); shown != host {
+ return host
+ }
+ return ""
+}
+
+// SqidURLLabel labels the sqid URL wherever a page shows it second
+// (console.app.sqid_url.label).
+func (page) SqidURLLabel() string { return appSqidURLLabelCopy }
diff --git a/internal/console/canonical_test.go b/internal/console/canonical_test.go
new file mode 100644
index 000000000..5d55ea6d9
--- /dev/null
+++ b/internal/console/canonical_test.go
@@ -0,0 +1,278 @@
+package console
+
+// Account subdomains, Task 6 (spec §4.8): wherever an account has a
+// subdomain, every console page and API answer that shows an app URL gives
+// <prefix>.<name>.<apps-domain>; the sqid URL stays the permanent address
+// and the identity (detail paths, logs, form actions). Neutral names: bab is
+// the fixture account, harbour its name, oncarlos.com the apps domain.
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestCanonicalHost(t *testing.T) {
+ v := namespaceView{byName: map[string]string{"harbour": "bdq"}, byAccount: map[string]string{"bdq": "harbour"}}
+ for _, c := range []struct{ in, want string }{
+ {"shop.bdq." + nsApps, "shop.harbour." + nsApps},
+ {"c1.shop.bdq." + nsApps, "c1.shop.harbour." + nsApps},
+ {"shop.example.com", "shop.example.com"}, // a custom domain
+ {"shop.bcd." + nsApps, "shop.bcd." + nsApps}, // an account with no name
+ {"bdq." + nsApps, "bdq." + nsApps}, // the label itself
+ {"shop.harbour." + nsApps, "shop.harbour." + nsApps}, // already the name
+ {"shop.bdq.example.com", "shop.bdq.example.com"}, // another domain
+ {nsApps, nsApps},
+ {"", ""},
+ } {
+ if got := canonicalHostIn(v, nsApps, c.in); got != c.want {
+ t.Errorf("canonicalHostIn(%q) = %q, want %q", c.in, got, c.want)
+ }
+ }
+ if got := canonicalHostIn(v, "", "shop.bdq."+nsApps); got != "shop.bdq."+nsApps {
+ t.Errorf("with no apps domain = %q, want the host unchanged", got)
+ }
+ if got := canonicalHostIn(namespaceView{}, nsApps, "shop.bdq."+nsApps); got != "shop.bdq."+nsApps {
+ t.Errorf("with no names = %q, want the host unchanged", got)
+ }
+}
+
+// canonFixture is the base console on the apps domain with app shop in bab,
+// a route at shop.bab.<apps>, an instance at c1.shop.bab.<apps>, and bab
+// holding harbour; paul (an owner of bab, the ops account) is signed in.
+func canonFixture(t *testing.T) (*consoleFixture, *http.Client) {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.AppsDomain = nsApps
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ for _, h := range []string{"shop.bab." + nsApps, "c1.shop.bab." + nsApps} {
+ fx.addRoute(t, registry.Route{Host: h, App: "shop", Account: "bab", Kind: "instance", Status: "ready", Channel: "stable", Provisioned: true})
+ }
+ nsHold(t, fx, "harbour", fx.sqid)
+ return fx, signInPaul(t, fx)
+}
+
+func canonHas(t *testing.T, what, body string, wants ...string) {
+ t.Helper()
+ for _, w := range wants {
+ if !strings.Contains(body, w) {
+ t.Errorf("%s does not contain %q", what, w)
+ }
+ }
+}
+
+func canonLacks(t *testing.T, what, body string, nots ...string) {
+ t.Helper()
+ for _, n := range nots {
+ if strings.Contains(body, n) {
+ t.Errorf("%s contains %q", what, n)
+ }
+ }
+}
+
+// TestAppsPageLinksToName: the app list links to the name URL; the app's
+// own page leads with it and shows the sqid URL as the permanent address.
+func TestAppsPageLinksToName(t *testing.T) {
+ fx, c := canonFixture(t)
+ _, _, body := get(t, c, fx.u("/"))
+ canonHas(t, "the app list", body, `href="https://shop.harbour.`+nsApps+`"`)
+ canonLacks(t, "the app list", body, `href="https://shop.bab.`+nsApps+`"`)
+ _, _, body = get(t, c, fx.u("/apps/shop"))
+ canonHas(t, "the app page", body, `href="https://shop.harbour.`+nsApps+`"`,
+ appSqidURLLabelCopy, `href="https://shop.bab.`+nsApps+`"`)
+}
+
+// TestInstanceListLinksToName: the Running tab's open link is the name URL;
+// the row's detail link keeps the sqid host. The instance page leads with
+// the name host, shows the sqid host as the permanent address, and its logs
+// link keeps the sqid host.
+func TestInstanceListLinksToName(t *testing.T) {
+ fx, c := canonFixture(t)
+ _, _, body := get(t, c, fx.u("/apps/shop/instances"))
+ canonHas(t, "the instance list", body, `href="https://c1.shop.harbour.`+nsApps+`"`,
+ "/apps/shop/instances/c1.shop.bab."+nsApps)
+ canonLacks(t, "the instance list", body, `href="https://c1.shop.bab.`+nsApps+`"`)
+ // A hand-added route: no box derives a name for it, so it is shown as
+ // it is.
+ fx.addRoute(t, registry.Route{Host: "hand.shop.bab." + nsApps, App: "shop", Account: "bab", Kind: "instance", Status: "ready", Channel: "stable"})
+ _, _, body = get(t, c, fx.u("/apps/shop/instances"))
+ canonHas(t, "the instance list with a hand route", body, `href="https://hand.shop.bab.`+nsApps+`"`)
+ canonLacks(t, "the instance list with a hand route", body, "hand.shop.harbour")
+ _, _, body = get(t, c, fx.u("/apps/shop/instances/c1.shop.bab."+nsApps))
+ canonHas(t, "the instance page", body, `href="https://c1.shop.harbour.`+nsApps+`"`,
+ appSqidURLLabelCopy, `href="https://c1.shop.bab.`+nsApps+`"`, "logs?host=c1.shop.bab."+nsApps)
+}
+
+// TestCanaryLinksUseName: the canary create flash and the Canaries table
+// both name the name URL.
+func TestCanaryLinksUseName(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.AppsDomain = nsApps
+ nsHold(t, fx, "harbour", fx.sqid)
+ c := signInPaul(t, fx)
+ csrf := sessionToken(t, fx, c)
+ fx.addRoute(t, registry.Route{Host: "rc.kass.bab." + nsApps, Kind: "instance", Status: "ready", App: "kass", Account: "bab",
+ Channel: "canary/rc", Canary: true, Provisioned: true})
+ postForm(t, c, fx.u("/apps/kass/canary"), url.Values{"csrf": {csrf}, "name": {"rc"}, "version": {"v1"}})
+ _, _, body := get(t, c, fx.u("/apps/kass"))
+ canonHas(t, "the canary flash", body, "live at https://rc.kass.harbour."+nsApps)
+ _, _, body = get(t, c, fx.u("/apps/kass/releases"))
+ canonHas(t, "the canaries table", body, `<a href="https://rc.kass.harbour.`+nsApps+`">rc.kass.harbour.`+nsApps+`</a>`)
+}
+
+// nsCountStore counts the claim listings. It embeds release.Store only, so
+// the claim cache takes its plain List path, one List per listing.
+type nsCountStore struct {
+ release.Store
+ mu sync.Mutex
+ lists int
+}
+
+func (s *nsCountStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if prefix == "domains/" {
+ s.mu.Lock()
+ s.lists++
+ s.mu.Unlock()
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func (s *nsCountStore) count() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.lists
+}
+
+// TestCanonicalPageLoadsNamespacesOnce: a page that shows many app URLs
+// lists the claims once, not once per URL.
+func TestCanonicalPageLoadsNamespacesOnce(t *testing.T) {
+ fx, c := canonFixture(t)
+ for _, h := range []string{"c2.shop.bab." + nsApps, "c3.shop.bab." + nsApps} {
+ fx.addRoute(t, registry.Route{Host: h, App: "shop", Account: "bab", Kind: "instance", Status: "ready", Channel: "stable", Provisioned: true})
+ }
+ counter := &nsCountStore{Store: fx.rel}
+ fx.srv.cfg.Releases = counter
+ for p, want := range map[string]string{"/": "shop.harbour." + nsApps, "/apps/shop/instances": "c3.shop.harbour." + nsApps} {
+ before := counter.count()
+ _, _, body := get(t, c, fx.u(p))
+ canonHas(t, p, body, want)
+ if got := counter.count() - before; got != 1 {
+ t.Errorf("GET %s listed the claims %d times, want 1", p, got)
+ }
+ }
+}
+
+// TestRemovedNameFlipsDisplayBack (Review Focus 5): once the name is
+// removed through the door, the next read of every page and answer shows
+// the sqid host again.
+func TestRemovedNameFlipsDisplayBack(t *testing.T) {
+ fx, c := canonFixture(t)
+ op := cliToken(t, fx, "paul@keymail.dev", "code-canon-flip-cli")
+ _, _, body := get(t, c, fx.u("/apps/shop/instances"))
+ canonHas(t, "the instance list before", body, `href="https://c1.shop.harbour.`+nsApps+`"`)
+ if code, _, out := sdReq(t, fx, http.MethodDelete, fx.sqid, op, ""); code != http.StatusOK {
+ t.Fatalf("remove = %d %s", code, out)
+ }
+ _, _, body = get(t, c, fx.u("/apps/shop/instances"))
+ canonHas(t, "the instance list after", body, `href="https://c1.shop.bab.`+nsApps+`"`)
+ canonLacks(t, "the instance list after", body, "harbour")
+ _, _, body = get(t, c, fx.u("/"))
+ canonHas(t, "the app list after", body, `href="https://shop.bab.`+nsApps+`"`)
+ _, _, body = get(t, c, fx.u("/apps/shop"))
+ canonLacks(t, "the app page after", body, appSqidURLLabelCopy)
+}
+
+// TestInstanceAnswersCarryPublicHost: the create, list and get answers and
+// the routes read carry public_host, the name host, beside host, which
+// stays the sqid host.
+func TestInstanceAnswersCarryPublicHost(t *testing.T) {
+ fx, member, _ := nsShopFixture(t, "code-canon-api")
+ enableInstances(t, fx, "shop", nsShopManifest("shop.bab."+nsApps))
+ nsHold(t, fx, "harbour", fx.sqid)
+ host, public := "c1.shop.bab."+nsApps, "c1.shop.harbour."+nsApps
+ type rec struct {
+ Host string `json:"host"`
+ PublicHost string `json:"public_host"`
+ }
+ check := func(what string, r rec) {
+ t.Helper()
+ if r.Host != host || r.PublicHost != public {
+ t.Errorf("%s = host %q public_host %q, want %q %q", what, r.Host, r.PublicHost, host, public)
+ }
+ }
+ code, _, out := rawReq(t, http.MethodPost, instancesURL(fx, "bab", "shop"), member, `{"host":"`+host+`","region":"ie"}`)
+ var created rec
+ if err := json.Unmarshal([]byte(out), &created); code != http.StatusCreated || err != nil {
+ t.Fatalf("create = %d %s", code, out)
+ }
+ check("the create answer", created)
+ code, _, out = rawReq(t, http.MethodGet, instancesURL(fx, "bab", "shop"), member, "")
+ var list struct {
+ Instances []rec `json:"instances"`
+ }
+ if err := json.Unmarshal([]byte(out), &list); code != http.StatusOK || err != nil || len(list.Instances) != 1 {
+ t.Fatalf("list = %d %s", code, out)
+ }
+ check("the list answer", list.Instances[0])
+ code, _, out = rawReq(t, http.MethodGet, instancesURL(fx, "bab", "shop")+"/"+host, member, "")
+ var one rec
+ if err := json.Unmarshal([]byte(out), &one); code != http.StatusOK || err != nil {
+ t.Fatalf("get = %d %s", code, out)
+ }
+ check("the get answer", one)
+
+ fx.addRoute(t, registry.Route{Host: host, App: "shop", Account: "bab", Kind: "instance", Status: "ready", Channel: "stable", Provisioned: true})
+ code, _, out = rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps/bab/shop/routes", member, "")
+ var routes struct {
+ Routes []rec `json:"routes"`
+ }
+ if err := json.Unmarshal([]byte(out), &routes); code != http.StatusOK || err != nil || len(routes.Routes) != 1 {
+ t.Fatalf("routes = %d %s", code, out)
+ }
+ check("the routes answer", routes.Routes[0])
+}
+
+// TestHomeLinkOmitsURLWhenServingStatusFails: the home console shows the
+// URL the serving console gives. When it cannot ask, it shows no URL rather
+// than one it derives itself, which could be the wrong one (the serving
+// deployment's names are not the home's to know), and says why.
+func TestHomeLinkOmitsURLWhenServingStatusFails(t *testing.T) {
+ home := newHomeFixture(t)
+ home.srv.cfg.AppsDomain = "apps.test"
+ op := cliToken(t, home, "paul@keymail.dev", "code-home-omit")
+ f := newFakeServing(t)
+ linkHomeTo(t, home, f)
+ if err := homeRegistry(t, home).PutHomeLinkApp(registry.HomeLinkApp{Name: "demo", HomeAccount: home.sqid, HomeApp: "shop",
+ HomeHost: "shop." + home.sqid + ".apps.test"}); err != nil {
+ t.Fatal(err)
+ }
+ f.mu.Lock()
+ f.pubs["demo"] = true
+ f.mu.Unlock()
+ if st := homeStatus(t, home, op); len(st.Apps) != 1 || st.Apps[0].URL != "https://demo.bab.apps.example.com" {
+ t.Fatalf("status apps with the serving console up = %+v", st.Apps)
+ }
+ f.mu.Lock()
+ f.handle = func(w http.ResponseWriter, r *http.Request) bool {
+ if r.Method == http.MethodGet && r.URL.Path == "/api/link" {
+ jsonError(w, http.StatusServiceUnavailable, "down")
+ return true
+ }
+ return false
+ }
+ f.mu.Unlock()
+ st := homeStatus(t, home, op)
+ if st.ServingError == "" || len(st.Apps) != 1 || st.Apps[0].URL != "" {
+ t.Errorf("status with the serving console down = error %q apps %+v, want an error and no URL", st.ServingError, st.Apps)
+ }
+}
diff --git a/internal/console/channelmove.go b/internal/console/channelmove.go
index ea6185dce..3223007c8 100644
--- a/internal/console/channelmove.go
+++ b/internal/console/channelmove.go
@@ -147,7 +147,7 @@ func (s *Server) handleAPIInstanceChannel(w http.ResponseWriter, r *http.Request
// Nothing changed: no write, no serial bump, no audit line. A serial
// that names no change sends every box in the fleet converging for
// nothing, and buries the tenant's audit log under no-ops.
- writeJSON(w, http.StatusOK, recordView(*rec))
+ writeJSON(w, http.StatusOK, s.publicRecordView(ctx, *rec))
return
}
pipe, err := release.GetPipeline(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, app)
@@ -200,7 +200,7 @@ func (s *Server) handleAPIInstanceChannel(w http.ResponseWriter, r *http.Request
// column from this record, so announcing it is what makes the move take
// seconds instead of an hour.
s.bumpSerial(ctx)
- writeJSON(w, http.StatusOK, recordView(*rec))
+ writeJSON(w, http.StatusOK, s.publicRecordView(ctx, *rec))
}
// isCanaryChannel reports whether a name is in the reserved canary
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 2ffec9cb0..0c1e42afe 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1435,6 +1435,26 @@ var claimFixtures = map[string]claimFixture{
// ---- POST: unauthenticated, signed ----
// SES delivery events count against the sending app (mail_sender_counts).
+ // Account subdomains (apisubdomain.go): every method of the door and
+ // the inventory refuses on a host-claim console, after the operator
+ // gate and before any read. bab/titogo is the watched app the
+ // refusal must leave alone; the doors name no app.
+ "route GET /api/cli/accounts/{account}/subdomain": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"), do: claimRefusedAPI(http.MethodGet, "/api/cli/accounts/bab/subdomain", ""),
+ status: http.StatusConflict, msg: subdomainRefuseHostClaimsCopy,
+ }},
+ "route POST /api/cli/accounts/{account}/subdomain": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"), do: claimRefusedAPI(http.MethodPost, "/api/cli/accounts/bab/subdomain", `{"name":"harbour"}`),
+ status: http.StatusConflict, msg: subdomainRefuseHostClaimsCopy,
+ }},
+ "route DELETE /api/cli/accounts/{account}/subdomain": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"), do: claimRefusedAPI(http.MethodDelete, "/api/cli/accounts/bab/subdomain", ""),
+ status: http.StatusConflict, msg: subdomainRefuseHostClaimsCopy,
+ }},
+ "route GET /api/cli/system/subdomain-inventory": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"), do: claimRefusedAPI(http.MethodGet, "/api/cli/system/subdomain-inventory", ""),
+ status: http.StatusConflict, msg: subdomainRefuseHostClaimsCopy,
+ }},
"route POST /api/cli/fleets/{account}/managed-plan": {refused: &claimRefusalFixture{
apps: claimRefs("bab/titogo"), do: claimRefusedAPI(http.MethodPost, "/api/cli/fleets/bab/managed-plan", `{"name":"production","kind":"create","region":"eu-west-1","size":"large","boxes":1}`), status: http.StatusConflict, msg: errManagedHostClaim.Error(),
}},
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index 5623e96fb..ce9d70fc1 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -126,6 +126,9 @@ var claimUnsupported = map[string]string{
"both doors refuse after their caller gates and before they read or write anything",
placementsHostClaimMsg: "a regional claim is written by SetClaimPlacements, which no host-claim operation gates (#447 plan note 9); " +
"the placements PUT refuses after its caller gates and before it reads or writes anything",
+ subdomainRefuseHostClaimsCopy: "an account subdomain is an account-level namespace claim, and the claim mutation boundary has no " +
+ "account-level writes (account subdomains spec §4.3); every method of the door and the inventory refuses after the operator gate " +
+ "and before it reads or writes anything",
errManagedHostClaim.Error(): "managed enrolment refuses host-claim consoles before reading reservations or granting authority; claim-bound reservation transactions remain unavailable",
copyLinkedHostClaim: "a linked app is an apps row that no claim operation gates (linked deployments slice 1); " +
"the publish and unpublish doors refuse after linkRoute's gate and before they read or write any app",
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go
index 9391ad03b..ede96e8c9 100644
--- a/internal/console/demo_claim_auth.go
+++ b/internal/console/demo_claim_auth.go
@@ -499,7 +499,8 @@ func (s *Server) demoClaimLink(w http.ResponseWriter, r *http.Request, link stri
func (s *Server) demoClaimStatusReply(w http.ResponseWriter, r *http.Request, op claimOp) {
switch op.Phase {
case "done":
- demoClaimReply(w, 200, map[string]any{"state": "claimed", "accountId": op.Target.Sqid, "app": op.Target.App, "url": "https://" + op.Target.Host, "next": "cli_login"})
+ // The URL as the platform shows it (canonical.go).
+ demoClaimReply(w, 200, map[string]any{"state": "claimed", "accountId": op.Target.Sqid, "app": op.Target.App, "url": "https://" + s.canon(r.Context()).host(op.Target.Host), "next": "cli_login"})
case "aborted":
demoClaimReply(w, 200, map[string]any{"state": "aborted"})
default:
diff --git a/internal/console/demo_claim_choice_test.go b/internal/console/demo_claim_choice_test.go
index 4b3a8842a..147907e90 100644
--- a/internal/console/demo_claim_choice_test.go
+++ b/internal/console/demo_claim_choice_test.go
@@ -17,6 +17,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
)
@@ -157,6 +158,17 @@ func TestDemoClaimStatusDoor(t *testing.T) {
// Any accidental remote operation panics, including a newly added Store method.
type claimNoRemoteStore struct{ release.Store }
+// List allows one read, on purpose: the claim listing a claimed app's URL is
+// shown through (canonical.go, account subdomains spec §4.8: the name URL
+// where the account has a subdomain), answered as a deployment with no
+// claims. Every other listing still panics.
+func (claimNoRemoteStore) List(_ context.Context, prefix string) ([]string, error) {
+ if prefix == domains.ClaimsPrefix {
+ return nil, nil
+ }
+ panic("claimNoRemoteStore: List " + prefix)
+}
+
type claimRoomStore struct {
release.Store
calls atomic.Int32
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index 77b4e04d9..305973ad6 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -176,7 +176,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
if op.Phase == "done" {
p.State = "claimed"
p.App = op.Target.App
- p.URL = "https://" + op.Target.Host
+ p.URL = "https://" + s.canon(r.Context()).host(op.Target.Host) // shown as the platform shows it (canonical.go)
canContinue := keptErr != nil && err == nil && hash == op.FlowHash && op.Person != ""
if !canContinue && address != "" {
role, roleErr := s.store.Role(op.Target.AccountID, address)
diff --git a/internal/console/demo_claim_status_page.go b/internal/console/demo_claim_status_page.go
index 110ea5f44..782719b1a 100644
--- a/internal/console/demo_claim_status_page.go
+++ b/internal/console/demo_claim_status_page.go
@@ -39,7 +39,7 @@ func (s *Server) handleDemoClaimBrowserStatus(w http.ResponseWriter, r *http.Req
state, step := demoClaimProgressStep(op.Phase)
body := map[string]any{"state": state, "step": step}
if state == "claimed" {
- body["url"] = "https://" + op.Target.Host
+ body["url"] = "https://" + s.canon(r.Context()).host(op.Target.Host) // as the platform shows it (canonical.go)
}
demoClaimReply(w, http.StatusOK, body)
}
diff --git a/internal/console/flow.go b/internal/console/flow.go
index fa138bad6..954140d63 100644
--- a/internal/console/flow.go
+++ b/internal/console/flow.go
@@ -99,9 +99,11 @@ type FlowStage struct {
// FlowAddress is one address hanging off a stage, with its health.
type FlowAddress struct {
- Host string
- Health string // healthWord's plain word, as the Running tab shows it
- Version string // what this address reports it is running, "" unknown
+ Host string
+ // PublicHost is Host as the platform shows it (canonical.go).
+ PublicHost string
+ Health string // healthWord's plain word, as the Running tab shows it
+ Version string // what this address reports it is running, "" unknown
// Tone is how the health word should read: ok, idle, wait or bad.
// Asleep is idle rather than bad on purpose — hibernating is the system
// working, and colouring it as a problem trains owners to ignore the
@@ -111,6 +113,9 @@ type FlowAddress struct {
Region string
}
+// ShownHost is the host the flow card shows and links to.
+func (a FlowAddress) ShownHost() string { return shownHost(a.Host, a.PublicHost) }
+
// addressTone maps healthWord's vocabulary onto the four tones. An
// unrecognised word falls to idle: a health word nobody taught this function
// is missing information, and missing information must never render as
@@ -200,11 +205,12 @@ func assembleFlow(view *AppView, rows []InstanceRow, latest, latestAt, instances
byChannel := map[string][]FlowAddress{}
for _, r := range rows {
byChannel[r.Channel] = append(byChannel[r.Channel], FlowAddress{
- Host: r.Host,
- Health: r.HealthWord,
- Version: r.Version,
- Tone: addressTone(r.HealthWord),
- Region: r.Region,
+ Host: r.Host,
+ PublicHost: r.PublicHost,
+ Health: r.HealthWord,
+ Version: r.Version,
+ Tone: addressTone(r.HealthWord),
+ Region: r.Region,
})
}
chans := make(map[string]ChannelView, len(view.Channels))
diff --git a/internal/console/homelink.go b/internal/console/homelink.go
index 504201e7c..55547d4ad 100644
--- a/internal/console/homelink.go
+++ b/internal/console/homelink.go
@@ -464,12 +464,14 @@ func (s *Server) handleAPIHomeLinkStatus(w http.ResponseWriter, r *http.Request)
urls := map[string]string{}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
+ served := false
if st, err := newLinkClient(l.ServingURL, l.Token).Status(ctx); err != nil {
out.ServingError = homeLinkServingSentence(l.ServingURL, err)
if l.RotatePending {
out.KeyRevocation = "pending"
}
} else {
+ served = true
out.Name = st.Name
for _, p := range st.Publications {
urls[p.App] = p.URL
@@ -485,9 +487,14 @@ func (s *Server) handleAPIHomeLinkStatus(w http.ResponseWriter, r *http.Request)
s.homeLinkConfirmRotation(reg, l)
}
}
+ // The serving console's URL is the app's URL: it applies its own
+ // deployment's rules (an account subdomain makes it the name URL, which
+ // this console cannot see). When the status call failed there is none
+ // to show, and the serving error above says why; deriving a sqid URL
+ // here would show an address the serving console no longer gives.
for _, a := range apps {
u := urls[a.Name]
- if u == "" {
+ if u == "" && served {
u = homeLinkPublicURL(l, a.Name)
}
out.Apps = append(out.Apps, homeLinkAppWire{App: a.Name, HomeAccount: a.HomeAccount, HomeApp: a.HomeApp, URL: u})
diff --git a/internal/console/ladder.go b/internal/console/ladder.go
index 883628ef2..b0c78bb28 100644
--- a/internal/console/ladder.go
+++ b/internal/console/ladder.go
@@ -73,6 +73,9 @@ type LadderChannel struct {
// LadderRoute is one host under the channel it follows.
type LadderRoute struct {
Host string
+ // PublicHost is Host as the platform shows it (canonical.go); "" when
+ // the ladder was built from routes without one.
+ PublicHost string
// Environment is the named config bundle this route is wired to — ""
// (rendered "default" in ladder.html) means the app's default bundle
// alone. Independent of the channel it is listed under (spec §4a).
@@ -99,6 +102,9 @@ type LadderRoute struct {
Caps string
}
+// ShownHost is the host the ladder shows and links to.
+func (r LadderRoute) ShownHost() string { return shownHost(r.Host, r.PublicHost) }
+
// LadderStep is the move from one rung to the one above it.
type LadderStep struct {
// To is the rung above.
@@ -152,6 +158,7 @@ func assembleLadder(channels []ChannelView, routes []RouteView, pipeline *releas
age := expiredFor[rt.Channel]
byChannel[rt.Channel] = append(byChannel[rt.Channel], LadderRoute{
Host: rt.Host,
+ PublicHost: rt.PublicHost,
Environment: rt.Environment,
Canary: ok && rung == release.RungCanary,
ProdWired: prod[rt.Host],
@@ -249,7 +256,7 @@ func assemblePipelineLadder(p *release.Pipeline, channels []ChannelView, routes
byRoute := map[string][]LadderRoute{}
for _, rt := range routes {
byRoute[rt.Channel] = append(byRoute[rt.Channel], LadderRoute{
- Host: rt.Host, Environment: rt.Environment,
+ Host: rt.Host, PublicHost: rt.PublicHost, Environment: rt.Environment,
ProdWired: prod[rt.Host], Caps: rt.Caps,
})
}
diff --git a/internal/console/listquery.go b/internal/console/listquery.go
index 29ea61d23..6e8a13df2 100644
--- a/internal/console/listquery.go
+++ b/internal/console/listquery.go
@@ -145,7 +145,9 @@ func pageInstanceRows(rows []InstanceRow, q instanceQuery, limit int) instancePa
var matched []InstanceRow
for _, r := range rows {
p.Counts[r.HealthWord]++
- if q.Q != "" && !strings.Contains(r.Host, q.Q) {
+ // The row shows its name host where the account has one, so the
+ // filter finds what the reader sees as well as the sqid host.
+ if q.Q != "" && !strings.Contains(r.Host, q.Q) && !strings.Contains(r.ShownHost(), q.Q) {
continue
}
if q.Channel != "" && r.Channel != q.Channel {
diff --git a/internal/console/overview.go b/internal/console/overview.go
index ca72ee3ee..89a1326a1 100644
--- a/internal/console/overview.go
+++ b/internal/console/overview.go
@@ -278,13 +278,17 @@ func domainNeedsAttention(d DomainView) bool {
// its readings from the shared sweep. The join key is the host — the one name
// owners have for an instance.
type InstanceRow struct {
- Host string
- Channel string
- Version string // what the route reports it is running, "" unknown
- Kind string
- Status string // registry status; "" means ready
- Hibernate bool
- Metrics InstanceMetrics // zero-valued (Reporting false) when unswept
+ Host string
+ // PublicHost is Host as the platform shows it (canonical.go): the name
+ // host where the account has a subdomain. Links to the app use it; the
+ // detail path, logs and form actions keep Host.
+ PublicHost string
+ Channel string
+ Version string // what the route reports it is running, "" unknown
+ Kind string
+ Status string // registry status; "" means ready
+ Hibernate bool
+ Metrics InstanceMetrics // zero-valued (Reporting false) when unswept
// HealthWord is the Status enum + hibernate + reporting folded into one
// plain word — the column's whole job.
@@ -296,6 +300,19 @@ type InstanceRow struct {
Moving string
}
+// ShownHost is the host the Running tab and the instance page show and
+// link to.
+func (r InstanceRow) ShownHost() string { return shownHost(r.Host, r.PublicHost) }
+
+// Permanent is the sqid host when the page shows a name host in its place,
+// else "": the instance page's permanent address.
+func (r InstanceRow) Permanent() string {
+ if r.ShownHost() != r.Host {
+ return r.Host
+ }
+ return ""
+}
+
// assembleInstanceRows joins the app's routes with the sweep's readings, in
// host order (the routes' own order). Only routes stamped with the viewed
// account join — the same tenant boundary appResourceMetrics draws, kept
@@ -321,6 +338,7 @@ func assembleInstanceRows(view *AppView, acct *Account, metrics []InstanceMetric
}
rows = append(rows, InstanceRow{
Host: rt.Host,
+ PublicHost: rt.PublicHost,
Channel: rt.Channel,
Version: rt.Version,
Kind: rt.Kind,
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go
index afa0a22f7..1dcecea05 100644
--- a/internal/console/remoteinstances.go
+++ b/internal/console/remoteinstances.go
@@ -579,6 +579,9 @@ func (s *Server) assembleApps(ctx context.Context, acct string, apps []string) (
// assembleAppsNamed is assembleApps for a caller that knows the account's
// name, which the frame cache keeps so a write addressed by name clears it.
//
+// Each view's hosts carry their shown host (RouteView.PublicHost and its
+// kin, canonical.go), from one namespace listing.
+//
// Each app's frame and instance records, and the box reports, are read
// before Assemble runs, all at once (readConcurrency at a time), and
// Assemble is handed what they read: the same reads, through the same
@@ -632,12 +635,19 @@ func (s *Server) assembleAppsNamed(ctx context.Context, acct, acctName string, a
}
remote = &read
}
- return assembleViews(ctx, s.cfg.Registry, acct, apps, dns, remote, func(app string) appFrame {
+ views, err := assembleViews(ctx, s.cfg.Registry, acct, apps, dns, remote, func(app string) appFrame {
if i := index(app); i >= 0 {
return frames[i]
}
return s.appFrame(ctx, acct, acctName, app)
})
+ if err != nil {
+ return nil, err
+ }
+ // Every host the pages show from these views, as the platform shows it
+ // (canonical.go): one namespace listing for the whole page.
+ s.canon(ctx).canonicalViews(views)
+ return views, nil
}
// errRetireUnsettled is channelHosts' answer when no record names the
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index f2c7c4ec0..160a5d7a6 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -980,6 +980,14 @@ var routeDecls = []routeDecl{
{Pattern: "POST /api/cli/accounts/{account}/store/approve", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIStoreApprove},
{Pattern: "GET /api/cli/accounts/{account}/plan", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIAccountPlanGet},
{Pattern: "POST /api/cli/accounts/{account}/plan", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIAccountPlanSet},
+ // Account subdomains (apisubdomain.go, spec §4.3): a platform operator,
+ // as a person, sets, shows and removes an account's subdomain, and
+ // lists the hosts under labels no account holds. Closed to every
+ // service credential; the handler admits platformOperator only.
+ {Pattern: "GET /api/cli/accounts/{account}/subdomain", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISubdomainGet},
+ {Pattern: "POST /api/cli/accounts/{account}/subdomain", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISubdomainSet},
+ {Pattern: "DELETE /api/cli/accounts/{account}/subdomain", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISubdomainDelete},
+ {Pattern: "GET /api/cli/system/subdomain-inventory", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISubdomainInventory},
{Pattern: "GET /api/cli/billing/problems", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIBillingProblems},
{Pattern: "GET /api/cli/billing/revenue", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIBillingRevenue},
{Pattern: "GET /api/cli/billing/payments", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIBillingPayments},
diff --git a/internal/console/server.go b/internal/console/server.go
index eec0e02c4..739752018 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1553,6 +1553,12 @@ type Server struct {
// regionalFloorHooks are test seams around regionalFloorPublish's
// critical section; nil in production.
regionalFloorHooks regionalFloorHooks
+ // subdomainMu serializes this console's subdomain door writes
+ // (apisubdomain.go), each from its first read to its re-read and any
+ // rollback, so two operators' sets on one console do not interleave.
+ // It is not the guard against another writer (the bucket key is, and
+ // the re-read): consoles do not share it. The zero value is ready.
+ subdomainMu sync.Mutex
// fleetFloorMu is the fleet forward floor's mutex (fleet public routes
// spec §9): every system pointer publication holds it from its last
// fleet floor judgment to its pointer write (fleetFloorPublish). It is
@@ -2339,10 +2345,16 @@ type page struct {
TemporaryApps []appRow
AppFilter string
AppListCopy appListCopy
- Detail *AppView // /a/{sqid}/apps/{app}
- Versions []VersionView // app page: shipped releases, newest first
- Tags []release.Tag // releases tab: every tag this app has cut, changelog and all
- RetentionKeep int // releases tab: >0 when an ambient retention policy is set (spec 2026-08-10-releases-retention-design.md §7)
+ // AccountSubdomain is the account's subdomain on the settings page
+ // ("" for none), read-only (account subdomains spec §4.8);
+ // AccountSubdomainKnown is false when that could not be told, and the
+ // page then leaves the cell out rather than say "None".
+ AccountSubdomain string
+ AccountSubdomainKnown bool
+ Detail *AppView // /a/{sqid}/apps/{app}
+ Versions []VersionView // app page: shipped releases, newest first
+ Tags []release.Tag // releases tab: every tag this app has cut, changelog and all
+ RetentionKeep int // releases tab: >0 when an ambient retention policy is set (spec 2026-08-10-releases-retention-design.md §7)
// VersionsPageNum is the Releases tab's page of Versions (1-based), and
// VersionsMore reports an older page after it.
VersionsPageNum int
@@ -4178,6 +4190,7 @@ func (s *Server) handleAccountSettings(w http.ResponseWriter, r *http.Request) {
// The analytics switch is the OTHER half of that same resolved object —
// one settings file, one read — under the name its own section uses.
p.AnalyticsSetting, p.AnalyticsUnread = p.ErrLevelSetting, p.ErrLevelUnread
+ s.accountSubdomainPane(r.Context(), &p, acct)
s.render(w, http.StatusOK, "account_settings", p)
}
@@ -6594,7 +6607,9 @@ func (s *Server) handleNewCanary(w http.ResponseWriter, r *http.Request) {
// so a registry hiccup just falls back to the generic "attach one" copy
// rather than failing the create that already succeeded.
if hosts, _ := s.channelHosts(ctx, acct.Sqid, app, channel); len(hosts) > 0 {
- back("ok", "Created canary "+name+" — live at https://"+hosts[0]+" serving "+version+" (test versions have no safety delay).")
+ // Shown as the platform shows it: the name host where the account
+ // has a subdomain (canonical.go).
+ back("ok", "Created canary "+name+" — live at https://"+s.canon(ctx).host(hosts[0])+" serving "+version+" (test versions have no safety delay).")
return
}
domain, absent := s.instanceDomainFor(ctx, acct.Sqid, app)
@@ -6857,7 +6872,9 @@ func summarize(v AppView, acct string) appRow {
}
}
deployment := observedDeployment(v.Routes, acct)
- row := appRow{App: v.App, URL: apexHost(mine), Deployment: deployment}
+ // The apex is picked among the hosts as they are (a custom domain keeps
+ // its precedence) and then shown as the platform shows it (canonical.go).
+ row := appRow{App: v.App, URL: shownRouteHost(mine, apexHost(mine)), Deployment: deployment}
attention, unknown := false, false
for _, rt := range mine {
if !rt.Platform && rt.Status == "failed" {
diff --git a/internal/console/subdomain_copy.go b/internal/console/subdomain_copy.go
index 57a091621..000a61190 100644
--- a/internal/console/subdomain_copy.go
+++ b/internal/console/subdomain_copy.go
@@ -7,7 +7,9 @@ package console
//
// 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.
+// other refuse.* strings are the assignment door's (apisubdomain.go), and
+// console.app.sqid_url.label labels the sqid URL on the app and instance
+// pages (canonical.go).
const (
// refuse.shape
@@ -44,4 +46,6 @@ const (
subdomainCreateUnassignableCopy = "nothing can be added under %s. use an address under the account's own label, or a custom domain"
// refuse.create.unreadable
subdomainCreateUnreadableCopy = "could not check which account holds %s. try again"
+ // console.app.sqid_url.label
+ appSqidURLLabelCopy = "Permanent address"
)
diff --git a/internal/console/subdomains.go b/internal/console/subdomains.go
index 49aebd73f..424c745c5 100644
--- a/internal/console/subdomains.go
+++ b/internal/console/subdomains.go
@@ -42,12 +42,28 @@ import (
// 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.
+// be trusted this read, with unreadBy the account each such claim names
+// when anything read said ("" when nothing did). 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
+ unreadBy map[string]string
+}
+
+// mayHoldUnread reports whether account may hold a name this read could not
+// trust: an unread namespace claim that names account, or names nobody
+// known. A reader that answers "account has no name" must not, while this
+// is true.
+func (v namespaceView) mayHoldUnread(account string) bool {
+ for name := range v.unread {
+ if by := v.unreadBy[name]; by == "" || by == account {
+ return true
+ }
+ }
+ return false
}
// labelOwner is the account whose namespace label, one label directly under
@@ -106,11 +122,12 @@ func (s *Server) loadNamespaces(ctx context.Context) (namespaceView, error) {
kept = append(kept, c)
}
}
- v := namespaceView{unread: map[string]bool{}}
+ v := namespaceView{unread: map[string]bool{}, unreadBy: map[string]string{}}
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
+ v.unreadBy[name] = u.Account
}
}
for _, c := range kept {
@@ -120,6 +137,7 @@ func (s *Server) loadNamespaces(ctx context.Context) (namespaceView, error) {
if name, ok := domains.ParseNamespaceHost(c.Host, domain); ok {
if _, held := v.byName[name]; !held {
v.unread[name] = true
+ v.unreadBy[name] = c.Account
sayUntrustedNamespaceOnce(c)
}
}
@@ -439,7 +457,12 @@ func (s *Server) doorNamespaces(ctx context.Context, host string) (namespaceView
// 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 }
+type occupant struct {
+ Host string `json:"host"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Source string `json:"source"`
+}
// The occupant sources.
const (
diff --git a/internal/console/svcpage.go b/internal/console/svcpage.go
index 50972e267..8d09a7ca1 100644
--- a/internal/console/svcpage.go
+++ b/internal/console/svcpage.go
@@ -220,6 +220,7 @@ func (s *Server) serviceSettingsPage(w http.ResponseWriter, r *http.Request, add
p.HasApps = n > 0
}
s.servicePane(&p, acct)
+ s.accountSubdomainPane(r.Context(), &p, acct)
return p
}
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 1da0cca4f..7d111bbc7 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -236,6 +236,14 @@ var closedDoors = []string{
"POST /api/cli/accounts/{account}/domains/purchases",
"GET /api/cli/accounts/{account}/plan",
"POST /api/cli/accounts/{account}/plan",
+ // An account's subdomain, and the inventory of labels no account
+ // holds, are a platform operator's (account subdomains spec §4.3): a
+ // person, never a machine credential. The handler admits
+ // platformOperator only.
+ "GET /api/cli/accounts/{account}/subdomain",
+ "POST /api/cli/accounts/{account}/subdomain",
+ "DELETE /api/cli/accounts/{account}/subdomain",
+ "GET /api/cli/system/subdomain-inventory",
// Billing problems are settled by a fleet operator in the provider's
// dashboard (plans 6a, Calls 1 and 2); no machine credential lists or
// closes them.
diff --git a/internal/console/templates/account_settings.html b/internal/console/templates/account_settings.html
index bdcf61a24..f90945e25 100644
--- a/internal/console/templates/account_settings.html
+++ b/internal/console/templates/account_settings.html
@@ -9,8 +9,8 @@
<h2>Identity</h2>
<div class="tablewrap">
<table>
- <tr><th>Name</th><th>ID</th><th>Your role</th></tr>
- <tr><td>{{.Account.Name}}</td><td><code>{{.Account.Sqid}}</code></td><td>{{.Role}}</td></tr>
+ <tr><th>Name</th><th>ID</th>{{if .AccountSubdomainKnown}}<th>Subdomain</th>{{end}}<th>Your role</th></tr>
+ <tr><td>{{.Account.Name}}</td><td><code>{{.Account.Sqid}}</code></td>{{if .AccountSubdomainKnown}}<td>{{with .AccountSubdomain}}<code>{{.}}</code>{{else}}None{{end}}</td>{{end}}<td>{{.Role}}</td></tr>
</table>
</div>
{{with .AccountStore}}
diff --git a/internal/console/templates/app_instance.html b/internal/console/templates/app_instance.html
index 01c10c354..e46c4c0ec 100644
--- a/internal/console/templates/app_instance.html
+++ b/internal/console/templates/app_instance.html
@@ -4,7 +4,7 @@
{{template "appnav" .}}
<p><a href="{{.InstanceListURL}}">Running</a></p>
{{with .InstanceDetail}}
-<h2 class="instance-address">{{.Row.Host}} <a class="instance-open" href="https://{{.Row.Host}}" aria-label="{{$.InstanceCopy.Open}} {{.Row.Host}}">{{icon "external-link"}}</a></h2>
+<h2 class="instance-address">{{.Row.ShownHost}} <a class="instance-open" href="https://{{.Row.ShownHost}}" aria-label="{{$.InstanceCopy.Open}} {{.Row.ShownHost}}">{{icon "external-link"}}</a></h2>
<p><a href="{{$.Nav}}/apps/{{$.AppName}}/logs?host={{.Row.Host}}">Logs</a></p>
{{if .Row.Restartable}}<form method="post" action="{{$.Base}}/apps/{{$.AppName}}/instances/{{.Row.Host}}/restart">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
@@ -23,6 +23,7 @@
<dt>{{$.InstanceCopy.Target}}</dt><dd>{{if .TargetErr}}Can't tell right now{{else if .TargetVersion}}<code>{{.TargetVersion}}</code>{{else}}—{{end}}</dd>
<dt>CPU</dt><dd>{{pct .Row.Metrics.CPUFrac}}{{if .Row.Metrics.SparkCPU}}<svg class="cellspark" aria-hidden="true" viewBox="0 0 240 40" preserveAspectRatio="none"><polyline fill="none" stroke="currentColor" points="{{.Row.Metrics.SparkCPU}}"/></svg>{{end}}</dd>
<dt>Memory</dt><dd>{{bytesOrDash .Row.Metrics.MemBytes}}{{if .Row.Metrics.SparkMem}}<svg class="cellspark" aria-hidden="true" viewBox="0 0 240 40" preserveAspectRatio="none"><polyline fill="none" stroke="currentColor" points="{{.Row.Metrics.SparkMem}}"/></svg>{{end}}</dd>
+ {{with .Row.Permanent}}<dt>{{$.SqidURLLabel}}</dt><dd><a href="https://{{.}}">{{.}}</a></dd>{{end}}
{{if .Aliases}}<dt>Web addresses</dt><dd>{{range .Aliases}}<div><a href="https://{{.}}">{{.}}</a></div>{{end}}</dd>{{end}}
</dl>
{{with .PromoteRetryText}}<p class="small">{{.}}</p>{{end}}
diff --git a/internal/console/templates/app_instances.html b/internal/console/templates/app_instances.html
index c6a176689..3617bdffd 100644
--- a/internal/console/templates/app_instances.html
+++ b/internal/console/templates/app_instances.html
@@ -82,7 +82,7 @@ against that copy's own peak.</p>
{{define "instance_row"}}
<tr>
- <td class="instance-address"><a href="{{.Page.Nav}}/apps/{{.Page.AppName}}/instances/{{.Row.Host}}{{.Page.InstanceQuerySuffix}}">{{.Row.Host}}</a> <a class="instance-open" href="https://{{.Row.Host}}" aria-label="{{.Page.InstanceCopy.Open}} {{.Row.Host}}">{{icon "external-link"}}</a></td>
+ <td class="instance-address"><a href="{{.Page.Nav}}/apps/{{.Page.AppName}}/instances/{{.Row.Host}}{{.Page.InstanceQuerySuffix}}">{{.Row.ShownHost}}</a> <a class="instance-open" href="https://{{.Row.ShownHost}}" aria-label="{{.Page.InstanceCopy.Open}} {{.Row.ShownHost}}">{{icon "external-link"}}</a></td>
<td>{{if .Row.Region}}{{.Row.Region}}{{else}}—{{end}}{{if .Row.Moving}}<br><span class="small">{{.Row.Moving}}</span>{{end}}</td>
<td><span class="chip chip-health-{{healthTone .Row.HealthWord}}">{{.Row.HealthWord}}</span></td>
<td>{{if .Row.Version}}<code>{{.Row.Version}}</code>{{else}}—{{end}}</td>
diff --git a/internal/console/templates/app_releases.html b/internal/console/templates/app_releases.html
index 323bd45d7..0e322005d 100644
--- a/internal/console/templates/app_releases.html
+++ b/internal/console/templates/app_releases.html
@@ -162,7 +162,7 @@ add more.</p>
{{else}}
<td><code>{{.Version}}</code></td>
<td><span title="{{fmtTime .PromotedAt}}">{{ago .PromotedAt}}</span></td>
- <td>{{if .Hosts}}{{range .Hosts}}<a href="https://{{.}}">{{.}}</a> {{end}}{{else}}no host yet{{end}}</td>
+ <td>{{if .Hosts}}{{range .ShownHosts}}<a href="https://{{.}}">{{.}}</a> {{end}}{{else}}no host yet{{end}}</td>
{{end}}
<td>{{if $.CanPromote}}
<form method="post" action="{{$.Base}}/apps/{{$.Detail.App}}/canary/retire">
diff --git a/internal/console/templates/appnav.html b/internal/console/templates/appnav.html
index 4c2797138..967f978fb 100644
--- a/internal/console/templates/appnav.html
+++ b/internal/console/templates/appnav.html
@@ -3,6 +3,8 @@
<p class="eyebrow">App · {{.Account.Name}}</p>
<h1>{{.AppName}}</h1>
{{with .MobileTitle}}<h1 class="mobile-title">{{.}}</h1>{{end}}
+ {{with .AppNameURL}}<p><a href="https://{{.}}">{{.}}</a></p>
+ <p class="small">{{$.SqidURLLabel}}: <a href="https://{{$.AppPermanentURL}}">{{$.AppPermanentURL}}</a></p>{{end}}
{{if not .ExpiresAt.IsZero}}
<p class="small">Temporary. It moves to the Trash on {{fmtTime .ExpiresAt}}, and is deleted 3 days after that.</p>
<form method="post" action="{{.Base}}/apps/{{.AppName}}/keep">
diff --git a/internal/console/templates/flow.html b/internal/console/templates/flow.html
index 9617def99..bfb86632b 100644
--- a/internal/console/templates/flow.html
+++ b/internal/console/templates/flow.html
@@ -34,7 +34,7 @@
<ul class="flow-addrs">
{{range .Addresses}}
<li class="flow-addr flow-tone-{{.Tone}}">
- <a href="https://{{.Host}}">{{.Host}}</a>
+ <a href="https://{{.ShownHost}}">{{.ShownHost}}</a>
{{if .Region}}<span class="flow-region">{{.Region}}</span>{{end}}
<span class="flow-health">{{if eq .Tone "bad"}}{{icon "triangle-alert"}}{{end}}{{.Health}}</span>
</li>
@@ -46,7 +46,7 @@
<ul class="flow-addrs">
{{range .Addresses}}
<li class="flow-addr flow-tone-{{.Tone}}">
- <a href="https://{{.Host}}">{{.Host}}</a>
+ <a href="https://{{.ShownHost}}">{{.ShownHost}}</a>
{{if .Region}}<span class="flow-region">{{.Region}}</span>{{end}}
<span class="flow-health">{{if eq .Tone "bad"}}{{icon "triangle-alert"}}{{end}}{{.Health}}</span>
</li>
diff --git a/internal/console/templates/ladder.html b/internal/console/templates/ladder.html
index 76121aa04..de97b261d 100644
--- a/internal/console/templates/ladder.html
+++ b/internal/console/templates/ladder.html
@@ -85,7 +85,7 @@ Promoting moves it one step up; whatever follows that step picks it up.</p>
{{if .Routes}}
<ul class="routes">
{{range .Routes}}
- <li><a href="https://{{.Host}}">{{.Host}}</a>
+ <li><a href="https://{{.ShownHost}}">{{.ShownHost}}</a>
<span class="chip chip-env">{{icon "layers"}} {{if .Environment}}{{.Environment}}{{else}}default{{end}}</span>
{{if .ProdWired}}<span class="chip chip-prod">{{icon "triangle-alert"}} canary in front of everybody</span>
{{else if .Canary}}<span class="chip chip-canary">{{icon "flask-conical"}} canary</span>{{end}}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index be779d7ad..f2e3ad24b 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -15,6 +15,7 @@ route /fleet/billing/sync/status
route /fleet/economics/bill
route /fleet/economics/scenarios
route /fleet/economics/tier
+route DELETE /api/cli/accounts/{account}/subdomain
route DELETE /api/cli/apps/{account}/{app}/domains/{host}
route DELETE /api/cli/apps/{account}/{app}/email/credentials/{name}
route DELETE /api/cli/apps/{account}/{app}/email/domains/{domain}
@@ -75,6 +76,7 @@ route GET /api/box/interactive/{id}
route GET /api/box/runs/{id}
route GET /api/cli/accounts/{account}/domains/purchases/{id}
route GET /api/cli/accounts/{account}/plan
+route GET /api/cli/accounts/{account}/subdomain
route GET /api/cli/apps
route GET /api/cli/apps/{account}/list
route GET /api/cli/apps/{account}/{app}/analytics
@@ -148,6 +150,7 @@ route GET /api/cli/system/managed-fleets
route GET /api/cli/system/pdf
route GET /api/cli/system/pointer-digests
route GET /api/cli/system/status
+route GET /api/cli/system/subdomain-inventory
route GET /api/link
route GET /apps
route GET /apps/{app}
@@ -258,6 +261,7 @@ route POST /api/cli/accounts/{account}/plan
route POST /api/cli/accounts/{account}/store/apply
route POST /api/cli/accounts/{account}/store/approve
route POST /api/cli/accounts/{account}/store/decline
+route POST /api/cli/accounts/{account}/subdomain
route POST /api/cli/apps/{account}/new
route POST /api/cli/apps/{account}/new-temporary
route POST /api/cli/apps/{account}/{app}/assets/purge
diff --git a/internal/console/view.go b/internal/console/view.go
index 498cd49d7..fa9b3c654 100644
--- a/internal/console/view.go
+++ b/internal/console/view.go
@@ -293,16 +293,32 @@ type CanaryView struct {
Version string
PromotedAt time.Time
Hosts []string
+ // PublicHosts are Hosts as the platform shows them (canonical.go), index
+ // for index; nil when the view was built without a hostCanon.
+ PublicHosts []string
// Err mirrors ChannelView.Err: an unreadable pointer is one bad row.
Err string
}
+// ShownHosts are the hosts the Canaries table shows and links to: the
+// name hosts where the account has a subdomain (canonical.go).
+func (c CanaryView) ShownHosts() []string {
+ if len(c.PublicHosts) == len(c.Hosts) {
+ return c.PublicHosts
+ }
+ return c.Hosts
+}
+
// RouteView is one row of the routes table.
type RouteView struct {
Host, Kind, Status, Version, Channel string
- Hibernate bool
- Platform bool
- Restartable bool
+ // PublicHost is Host as the platform shows it (canonical.go): the name
+ // host where the account has a subdomain. "" when the view was built
+ // without a hostCanon. Display only; Host is the identity.
+ PublicHost string
+ Hibernate bool
+ Platform bool
+ Restartable bool
// Account is what the ROUTE says its account is (release.RouteAccount:
// the stamped account, or the ops account when unstamped). Routes are
// grouped by app NAME here, and app names are unique per account rather