carlos / platform Public

console: platform doors to create, list and show customer accounts

Three doors under /api/cli/platform/{account}/customers, Exactly(Platform)
(Admin is out), with platformGate in front: binding or ownership, a live
grant generation, and pending mints finished under the platform lifecycle
lock. Customer create is idempotent on ref, capped with pending mints
counted, and promises the account (ReservePlatformMint) before the bucket
is touched. Under the lifecycle lock it re-reads the platform and its grant
and finishes pending mints before it reads refs or capacity. List and show
carry plan and current-period usage; the list reads plans and caps in two
queries (LinkedCustomerPlans).

Every pending mint reaches an end state. A mint the bucket gave an id this
console holds for another account rewrites its manifest to describe that
account, then drops the promise. A mint whose ref a live customer took is
finished without the ref.

platformSeams holds the lifecycle lock table and the mint-step seam,
embedded in Server with one line (server.go's file-lines record raised by
one). The claim census, its fixtures and probes, and the link walk's
placeholder table cover the new routes. Task 7's management test now
checks the customer list door, and its mint test checks the doors list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d46e1a661ffb8cc365380d2070468e603c8c9030 parent ffd1b7e
15 files changed, +2,078 −9
  • .amadan/code-health.tsv +1 −1
  • internal/console/apiplatformcustomers.go +691 −0
  • internal/console/apiplatformcustomers_test.go +1,136 −0
  • internal/console/applocks.go +21 −0
  • internal/console/claim_invariant_fixtures_test.go +9 −0
  • internal/console/claim_invariant_probes_nonapp_test.go +36 −0
  • internal/console/claim_invariant_probes_read_test.go +4 −0
  • internal/console/links_auth_test.go +1 −0
  • internal/console/platform_copy.go +15 −1
  • internal/console/platform_credentials_test.go +11 −5
  • internal/console/platform_seams.go +30 −0
  • internal/console/platform_store.go +108 −2
  • internal/console/routedecls.go +11 −0
  • internal/console/server.go +1 −0
  • internal/console/testdata/claim-routes.txt +3 −0
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index ae1864170..d9b83946d 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -2230,7 +2230,7 @@ file-lines . apimode.go - 4199
file-lines . apimode_test.go - 3530 # raised: fdc912b (batch 2, #1123) landed before the ratchet; tests for the system update refusals
file-lines internal/activator activator.go - 3778
file-lines internal/activator activator_test.go - 5499
-file-lines internal/console server.go - 4219
+file-lines internal/console server.go - 4220 # raised: platform accounts pre-flight C1, the one line embedding platformSeams in Server
file-lines internal/host agent.go - 3214
file-lines internal/provision reconcile_test.go - 3094
file-lines internal/registry registry_test.go - 3261
diff --git a/internal/console/apiplatformcustomers.go b/internal/console/apiplatformcustomers.go
new file mode 100644
index 000000000..16c64a808
--- /dev/null
+++ b/internal/console/apiplatformcustomers.go
@@ -0,0 +1,691 @@
+package console
+
+// The platform doors (platform accounts spec §6.1): a platform account
+// creates, lists and shows the customer accounts it runs.
+//
+// Every door is registered with svcrole.Exactly(svcrole.Platform), so the
+// only service credential that reaches one is a platform credential (Admin
+// is out on purpose); a person reaches them too, and platformGate admits an
+// owner of the platform account only.
+//
+// Customer creation keeps one invariant (Astra r1-1): one live account per
+// (platform, ref), and a promised account uses capacity from the moment it
+// is promised until it exists. The promise (a pending mint) is written
+// before the bucket is touched, the bucket write is idempotent on the
+// promise's id (domains.MintLinkedAccount), and every path finishes
+// promises before it reads capacity or refs. Creation and platform deletion
+// share the platform lifecycle lock (lockPlatformLifecycle; Astra r1-3,
+// r2-1), so a create never lands on a platform being deleted.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// Account-level audit actions for customer creation, with app
+// accountAuditSubject: one on the platform account's history, one on the
+// customer's.
+const (
+ auditPlatformCustomerCreate = "platform-customer-create"
+ auditPlatformCustomerCreated = "platform-customer-created"
+)
+
+// maxPlatformRef is the longest customer reference (decision D5).
+const maxPlatformRef = 64
+
+// platformCaller is who passed platformGate: the principal, the platform
+// account it speaks for, and the grant it was admitted under.
+type platformCaller struct {
+ P Principal
+ Platform *Account
+ Grant *PlatformGrant
+ Actor string // auditActor(P, Platform)
+ // failRow is the copy id of the door's own failure row (pre-flight
+ // C10), "" on a read door.
+ failRow string
+}
+
+// platformCustomerView is one customer account as the platform doors show
+// it. Plan and PlanSource are empty for a customer with no plan row (a
+// console with no plan catalog).
+type platformCustomerView struct {
+ Account string `json:"account"`
+ Name string `json:"name"`
+ Ref string `json:"ref,omitempty"`
+ Plan string `json:"plan,omitempty"`
+ PlanSource string `json:"plan_source,omitempty"`
+ Claimed bool `json:"claimed"`
+ CreatedAt time.Time `json:"created_at"`
+ Usage []platformUsageView `json:"usage"`
+}
+
+// platformUsageView is one cap's usage in its current period.
+type platformUsageView struct {
+ Cap string `json:"cap"`
+ Used int64 `json:"used"`
+ Limit int64 `json:"limit"`
+ Level string `json:"level"`
+ GraceEnds *time.Time `json:"grace_ends,omitempty"`
+}
+
+// platformCustomerList is the list door's reply. Count is what counts
+// against MaxCustomers: live customers and unfinished promises.
+type platformCustomerList struct {
+ Platform string `json:"platform"`
+ MaxCustomers int `json:"max_customers"`
+ Count int `json:"count"`
+ Customers []platformCustomerView `json:"customers"`
+}
+
+// platformCreateReply is the create door's reply: 201 with created true
+// for a new account, 200 with created false for a ref already held.
+type platformCreateReply struct {
+ Created bool `json:"created"`
+ Customer platformCustomerView `json:"customer"`
+}
+
+// validPlatformRef reports whether ref is a customer reference: 1 to 64 of
+// A-Z a-z 0-9 . _ : - (decision D5). Case-sensitive.
+func validPlatformRef(ref string) bool {
+ if len(ref) < 1 || len(ref) > maxPlatformRef {
+ return false
+ }
+ for i := 0; i < len(ref); i++ {
+ switch c := ref[i]; {
+ case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
+ case c == '.', c == '_', c == ':', c == '-':
+ default:
+ return false
+ }
+ }
+ return true
+}
+
+// platformGate is a read door's gate: platformGateFor with no failure row,
+// so a pending mint that cannot be finished is logged and the request goes
+// on.
+func (s *Server) platformGate(w http.ResponseWriter, r *http.Request) (platformCaller, bool) {
+ return s.platformGateFor(w, r, "")
+}
+
+// platformGateFor is the gate every platform door runs, in order:
+//
+// - apiPrincipalAccount: the platform credential's own account, or an
+// account the person belongs to; anything else is the family's 404;
+// - a person who is not an owner is 403 door.not_owner;
+// - no grant is 403 door.not_platform, and a grant whose generation is not
+// live is 403 door.revoked. It authorizes on PlatformGenerationLive,
+// never on the grant row's state alone: a deleted platform's grant row
+// can still read active. A platform credential is held to the
+// generation it was minted in, which resolution already checked (Task
+// 7); a revoke landing since then is caught here;
+// - when the platform has pending mints, they are finished under the
+// platform lifecycle lock, released before the handler runs (the lock
+// is not re-entrant). failRow is the caller's door's own failure row
+// (pre-flight C10): on a write door a finish that fails is 502 with it;
+// with failRow "" (a read door) it is logged and the request goes on.
+// One indexed query when there are none.
+func (s *Server) platformGateFor(w http.ResponseWriter, r *http.Request, failRow string) (platformCaller, bool) {
+ p, acct, ok := s.apiPrincipalAccount(w, r)
+ if !ok {
+ return platformCaller{}, false
+ }
+ ctx := r.Context()
+ gen := int64(0)
+ switch p.Kind {
+ case PrincipalUser:
+ if acct.Role != RoleOwner {
+ jsonError(w, http.StatusForbidden, platformCopy["door.not_owner"])
+ return platformCaller{}, false
+ }
+ case PrincipalService:
+ // The role gate admitted only the platform role, and resolution
+ // bound it to its own account. Fail closed if either ever changed.
+ if p.Role != svcrole.Platform || p.PlatformAccountID != acct.ID || p.PlatformGeneration == 0 {
+ http.NotFound(w, r)
+ return platformCaller{}, false
+ }
+ gen = p.PlatformGeneration
+ default:
+ http.NotFound(w, r)
+ return platformCaller{}, false
+ }
+ c := platformCaller{P: p, Platform: acct, Actor: auditActor(p, acct), failRow: failRow}
+ g, err := s.store.PlatformGrant(ctx, acct.ID)
+ if err != nil {
+ log.Printf("console: platform %s: read grant: %v", acct.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return platformCaller{}, false
+ }
+ if g == nil {
+ jsonError(w, http.StatusForbidden, platformCopy["door.not_platform"])
+ return platformCaller{}, false
+ }
+ if gen == 0 {
+ gen = g.Generation
+ }
+ if _, live := s.store.PlatformGenerationLive(ctx, s.store.db, acct.ID, gen); !live || gen != g.Generation {
+ jsonError(w, http.StatusForbidden, platformCopy["door.revoked"])
+ return platformCaller{}, false
+ }
+ c.Grant = g
+
+ pending, err := s.store.PendingPlatformMints(ctx, acct.Sqid)
+ if err == nil && len(pending) > 0 {
+ unlock := s.lockPlatformLifecycle(acct.Sqid)
+ err = s.finishPendingMints(ctx, acct)
+ unlock()
+ }
+ if err != nil {
+ log.Printf("console: platform %s: finish pending customer creates: %v", acct.Sqid, err)
+ if failRow != "" {
+ s.platformDoorFailed(w, c)
+ return platformCaller{}, false
+ }
+ }
+ return c, true
+}
+
+// platformDoorFailed answers a store or bucket failure: 502 with the
+// door's own failure row on a write door (pre-flight C10), and on a read
+// door, which has no row of its own, a 500 with the status text.
+func (s *Server) platformDoorFailed(w http.ResponseWriter, c platformCaller) {
+ if c.failRow == "" {
+ jsonError(w, http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))
+ return
+ }
+ jsonError(w, http.StatusBadGateway, platformCopy[c.failRow])
+}
+
+// platformCustomer resolves the {customer} segment to a live customer of
+// the caller's platform. Anything else (unknown, deleted, unlinked, or
+// another platform's) is the stdlib 404, byte-identical whatever the
+// reason. The *Account is the customer's, for the doors that act on it.
+func (s *Server) platformCustomer(w http.ResponseWriter, r *http.Request, c platformCaller) (*LinkedCustomer, *Account, bool) {
+ cust, err := s.store.LinkedCustomer(r.Context(), c.Platform.Sqid, r.PathValue("customer"))
+ if err != nil {
+ log.Printf("console: platform %s: read customer: %v", c.Platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return nil, nil, false
+ }
+ if cust == nil {
+ http.NotFound(w, r)
+ return nil, nil, false
+ }
+ return cust, &Account{ID: cust.ID, Sqid: cust.Sqid, Name: cust.Name, CreatedAt: cust.CreatedAt.UTC()}, true
+}
+
+// handlePlatformCustomerList answers GET .../customers: every live customer
+// with its plan and usage, or with ?ref= the one holding that reference.
+func (s *Server) handlePlatformCustomerList(w http.ResponseWriter, r *http.Request) {
+ c, ok := s.platformGate(w, r)
+ if !ok {
+ return
+ }
+ ctx := r.Context()
+ now := time.Now()
+ views := []platformCustomerView{}
+ if ref := r.URL.Query().Get("ref"); ref != "" {
+ cust, err := s.store.LinkedCustomerByRef(ctx, c.Platform.Sqid, ref)
+ if err != nil {
+ log.Printf("console: platform %s: customer by ref: %v", c.Platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ if cust != nil {
+ v, err := s.customerView(ctx, *cust, now)
+ if err != nil {
+ log.Printf("console: platform %s: customer %s: %v", c.Platform.Sqid, cust.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ views = append(views, v)
+ }
+ } else {
+ customers, err := s.store.LinkedCustomers(ctx, c.Platform.Sqid)
+ if err != nil {
+ log.Printf("console: platform %s: list customers: %v", c.Platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ planRows, capRows, err := s.store.LinkedCustomerPlans(ctx, c.Platform.Sqid)
+ if err != nil {
+ log.Printf("console: platform %s: customer plans: %v", c.Platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ for _, cust := range customers {
+ var plan *AccountPlanRow
+ if row, ok := planRows[cust.ID]; ok {
+ plan = &row
+ }
+ views = append(views, platformView(cust, plan, capRows[cust.ID], now))
+ }
+ }
+ count, err := s.store.LinkedCustomerCount(ctx, c.Platform.Sqid)
+ if err != nil {
+ log.Printf("console: platform %s: count customers: %v", c.Platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ writeJSON(w, http.StatusOK, platformCustomerList{Platform: c.Platform.Sqid, MaxCustomers: c.Grant.MaxCustomers,
+ Count: count, Customers: views})
+}
+
+// handlePlatformCustomerShow answers GET .../customers/{customer}.
+func (s *Server) handlePlatformCustomerShow(w http.ResponseWriter, r *http.Request) {
+ c, ok := s.platformGate(w, r)
+ if !ok {
+ return
+ }
+ cust, _, ok := s.platformCustomer(w, r, c)
+ if !ok {
+ return
+ }
+ v, err := s.customerView(r.Context(), *cust, time.Now())
+ if err != nil {
+ log.Printf("console: platform %s: customer %s: %v", c.Platform.Sqid, cust.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ writeJSON(w, http.StatusOK, v)
+}
+
+// customerView reads one customer's plan row and cap rows and builds its
+// view.
+func (s *Server) customerView(ctx context.Context, cust LinkedCustomer, now time.Time) (platformCustomerView, error) {
+ plan, err := s.store.AccountPlanContext(ctx, cust.ID)
+ if err != nil {
+ return platformCustomerView{}, err
+ }
+ caps, err := s.store.CapStatesContext(ctx, cust.ID)
+ if err != nil {
+ return platformCustomerView{}, err
+ }
+ return platformView(cust, plan, caps, now), nil
+}
+
+// platformView is the customer's view: its usage is the cap rows of the
+// current period only, in capOrder (caps arrive in it).
+func platformView(cust LinkedCustomer, plan *AccountPlanRow, caps []capState, now time.Time) platformCustomerView {
+ v := platformCustomerView{Account: cust.Sqid, Name: cust.Name, Ref: cust.Ref, Claimed: cust.Owners > 0,
+ CreatedAt: cust.CreatedAt.UTC(), Usage: []platformUsageView{}}
+ if plan != nil {
+ v.Plan, v.PlanSource = plan.Plan, plan.Source
+ }
+ for _, st := range caps {
+ if st.Period != capPeriod(st.Cap, now) {
+ continue
+ }
+ u := platformUsageView{Cap: string(st.Cap), Used: st.Used, Limit: st.Limit, Level: string(st.Level)}
+ if !st.GraceEnds.IsZero() {
+ g := st.GraceEnds.UTC()
+ u.GraceEnds = &g
+ }
+ v.Usage = append(v.Usage, u)
+ }
+ return v
+}
+
+type createPlatformCustomerRequest struct {
+ Name string `json:"name"`
+ Ref string `json:"ref"`
+ Plan string `json:"plan"`
+}
+
+// handlePlatformCustomerCreate answers POST .../customers. The steps, in
+// order (platform accounts plan, Task 8):
+//
+// 1. validate the body: name, ref, and a plan within the grant;
+// 2. take the platform lifecycle lock (no other lock held) and re-read the
+// platform and its grant under it: a platform deleted or revoked while
+// this request waited gets nothing, and the plan and the cap are the
+// grant's as it stands now;
+// 3. finish the platform's pending mints, so a retry after a failed finish
+// lands on the account the first attempt minted;
+// 4. a ref a live customer holds answers 200 with it, spending nothing;
+// 5. the create budget, then the cap, pending mints included;
+// 6. promise the customer (ReservePlatformMint) before the bucket is
+// touched;
+// 7. mint into the bucket and finish the promise (finishPlatformMint).
+//
+// A failure in step 7 leaves the promise in place, still counting against
+// the cap and holding its ref, and the next platform request finishes it.
+func (s *Server) handlePlatformCustomerCreate(w http.ResponseWriter, r *http.Request) {
+ c, ok := s.platformGateFor(w, r, "create.failed")
+ if !ok {
+ return
+ }
+ var req createPlatformCustomerRequest
+ if !readJSONStrictLimit(w, r, &req, 8<<10) {
+ return
+ }
+ if !domains.ValidAccountName(req.Name) {
+ jsonError(w, http.StatusBadRequest, platformCopy["create.name"])
+ return
+ }
+ if req.Ref != "" && !validPlatformRef(req.Ref) {
+ jsonError(w, http.StatusBadRequest, platformCopy["create.ref"])
+ return
+ }
+ plan, refusal := s.platformCreatePlan(c.Grant, req.Plan)
+ if refusal != "" {
+ jsonError(w, http.StatusBadRequest, refusal)
+ return
+ }
+ ctx := r.Context()
+ if s.cfg.Releases == nil {
+ log.Printf("console: platform %s: create customer: no deployment bucket", c.Platform.Sqid)
+ s.platformDoorFailed(w, c)
+ return
+ }
+
+ // Step 2. Platform deletion takes this lock too (Astra r1-3, r2-1).
+ if err := s.platformStep("lock"); err != nil {
+ log.Printf("console: platform %s: create customer: %v", c.Platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ defer s.lockPlatformLifecycle(c.Platform.Sqid)()
+ platform, err := s.store.AccountByIDContext(ctx, c.Platform.ID)
+ if err != nil {
+ log.Printf("console: platform %s: create customer: re-read platform: %v", c.Platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ if platform == nil || platform.Sqid != c.Platform.Sqid {
+ http.NotFound(w, r)
+ return
+ }
+ if _, live := s.store.PlatformGenerationLive(ctx, s.store.db, platform.ID, c.Grant.Generation); !live {
+ jsonError(w, http.StatusForbidden, platformCopy["door.revoked"])
+ return
+ }
+ // The grant as it stands under the lock: an operator may have changed
+ // its plans or its max since the gate read it.
+ grant, err := s.store.PlatformGrant(ctx, platform.ID)
+ if err != nil || grant == nil {
+ log.Printf("console: platform %s: create customer: re-read grant: %+v %v", platform.Sqid, grant, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ if plan, refusal = s.platformCreatePlan(grant, req.Plan); refusal != "" {
+ jsonError(w, http.StatusBadRequest, refusal)
+ return
+ }
+
+ // Step 3.
+ if err := s.finishPendingMints(ctx, platform); err != nil {
+ log.Printf("console: platform %s: create customer: finish pending creates: %v", platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+
+ // Step 4.
+ if req.Ref != "" {
+ held, err := s.store.LinkedCustomerByRef(ctx, platform.Sqid, req.Ref)
+ if err != nil {
+ log.Printf("console: platform %s: create customer: ref: %v", platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ if held != nil {
+ s.writePlatformCreated(ctx, w, c, *held, false)
+ return
+ }
+ }
+
+ // Step 5.
+ now := time.Now()
+ if !s.allowCreate(c.P, now) {
+ jsonError(w, http.StatusTooManyRequests, platformCopy["create.rate"])
+ return
+ }
+ count, err := s.store.LinkedCustomerCount(ctx, platform.Sqid)
+ if err != nil {
+ log.Printf("console: platform %s: create customer: count: %v", platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ if count >= grant.MaxCustomers {
+ jsonError(w, http.StatusConflict, fmt.Sprintf(platformCopy["create.cap"], count))
+ return
+ }
+
+ // Step 6.
+ mintID, err := newCredentialID()
+ if err != nil {
+ log.Printf("console: platform %s: create customer: mint id: %v", platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ m := PendingMint{MintID: mintID, Platform: platform.Sqid, Ref: req.Ref, Name: req.Name, Plan: plan,
+ PlanReason: fmt.Sprintf("platform %s", platform.Sqid), By: c.Actor, CreatedAt: now}
+ if err := s.store.ReservePlatformMint(ctx, m); err != nil {
+ log.Printf("console: platform %s: create customer: reserve: %v", platform.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+
+ // Step 7.
+ cust, err := s.finishPlatformMint(ctx, platform, m)
+ if err != nil {
+ s.platformDoorFailed(w, c)
+ return
+ }
+ created, err := s.store.LinkedCustomer(ctx, platform.Sqid, cust.Sqid)
+ if err != nil || created == nil {
+ log.Printf("console: platform %s: created customer %s but could not read it back: %v", platform.Sqid, cust.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ s.writePlatformCreated(ctx, w, c, *created, true)
+}
+
+// platformCreatePlan is the plan a new customer goes on, or the refusal's
+// text. Empty means the grant's default. A named plan must be one of the
+// grant's. With no plan catalog there is no plan at all: a named one is
+// refused, and the customer gets no plan row (decision D8).
+func (s *Server) platformCreatePlan(g *PlatformGrant, plan string) (string, string) {
+ if s.cfg.PlanCatalog == nil {
+ if plan != "" {
+ return "", platformCopy["create.no_catalog_plan"]
+ }
+ return "", ""
+ }
+ if plan == "" {
+ return g.DefaultPlan, ""
+ }
+ if !slices.Contains(g.Plans, plan) {
+ return "", fmt.Sprintf(platformCopy["create.plan"], strings.Join(g.Plans, ", "))
+ }
+ return plan, ""
+}
+
+// writePlatformCreated answers a create: 201 for a new account, 200 for a
+// ref already held.
+func (s *Server) writePlatformCreated(ctx context.Context, w http.ResponseWriter, c platformCaller, cust LinkedCustomer, created bool) {
+ v, err := s.customerView(ctx, cust, time.Now())
+ if err != nil {
+ log.Printf("console: platform %s: customer %s: %v", c.Platform.Sqid, cust.Sqid, err)
+ s.platformDoorFailed(w, c)
+ return
+ }
+ status := http.StatusOK
+ if created {
+ status = http.StatusCreated
+ }
+ writeJSON(w, status, platformCreateReply{Created: created, Customer: v})
+}
+
+// restoreHeldManifest rewrites the manifest a pending mint wrote at an id
+// this console already holds for another account, so that it describes
+// that account, as ensureAccountManifest's backfill would have (its name,
+// its creation, its own link, a tombstone's deletion; no owner), instead of
+// naming this platform and ref. It writes only over the mint's own
+// manifest, read and replaced under its etag; a manifest that no longer
+// carries this platform and mint id, or a row whose sqid is not the key's,
+// is left alone.
+func (s *Server) restoreHeldManifest(ctx context.Context, platform *Account, m PendingMint, id int64, sqid string) error {
+ row, ok, err := s.store.accountManifestRow(ctx, id)
+ if err != nil {
+ return err
+ }
+ if !ok || row.Sqid != sqid {
+ return nil
+ }
+ key := domains.AccountManifestKey(sqid)
+ body, etag, err := s.cfg.Releases.Get(ctx, key)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ var cur domains.AccountManifest
+ if err := json.Unmarshal(body, &cur); err != nil || cur.Platform != platform.Sqid || cur.PlatformMint != m.MintID {
+ return nil
+ }
+ out, err := json.Marshal(row)
+ if err != nil {
+ return err
+ }
+ _, err = s.cfg.Releases.Put(ctx, key, out, etag)
+ return err
+}
+
+// errPlatformMintEnded is a pending mint that reached its end state without
+// an account: the customer it would have finished was deleted, or the
+// bucket gave its id to an id this console holds for another account. The
+// promise is gone, so it holds no capacity and no ref.
+var errPlatformMintEnded = errors.New("console: the pending customer create ended without an account")
+
+// finishPendingMints finishes every pending mint of the platform, oldest
+// first. The caller holds s.lockPlatformLifecycle(platform.Sqid). A mint
+// that ends without an account (errPlatformMintEnded) has reached its end
+// state and the next is finished; any other failure stops it, and is
+// returned (Astra r1-1).
+func (s *Server) finishPendingMints(ctx context.Context, platform *Account) error {
+ pending, err := s.store.PendingPlatformMints(ctx, platform.Sqid)
+ if err != nil {
+ return err
+ }
+ for _, m := range pending {
+ if _, err := s.finishPlatformMint(ctx, platform, m); err != nil && !errors.Is(err, errPlatformMintEnded) {
+ return err
+ }
+ }
+ return nil
+}
+
+// finishPlatformMint takes one pending mint to an end state. The caller
+// holds the platform lifecycle lock. MintLinkedAccount is idempotent on the
+// mint id, so the account a first attempt wrote is found again rather than
+// minted twice; then the account's analytics, then CreateLinkedAccount,
+// which records the account and deletes the promise in one transaction
+// (over a row materialization already made, after a restart). Every
+// failure is logged with the mint id, and the sqid once known, like
+// mintAccount's.
+//
+// Every pending mint reaches an end state:
+//
+// - finished: the account exists, the promise is gone, and the creation
+// is audited on both accounts (here, so a create finished by a later
+// request is audited too);
+// - a failure that can pass (the bucket, the database, analytics) keeps
+// the promise, and the next platform request tries again;
+// - the customer was materialized and then deleted (ErrAccountGone): the
+// store has dropped the promise, and the account stays deleted;
+// - the bucket gave the mint an id this console already holds for another
+// account (errLinkedIDTaken). That happens only when the bucket has no
+// manifest for an account this console has, and it is permanent: every
+// retry finds the same manifest by its mint id and lands on the same
+// id. The manifest this mint wrote is rewritten to describe the account
+// that holds the id (restoreHeldManifest), then the promise is dropped,
+// so the platform's retry promises afresh and mints the next free id.
+// The bucket then names this platform and ref nowhere, so a console
+// rebuilt from it cannot find two accounts for one ref. Tombstoning the
+// manifest instead would make the next start reap the other account. A
+// rewrite that fails keeps the promise, and the next request tries
+// again;
+// - a live customer of the platform already holds the ref (only a
+// bucket manifest written outside this console can cause it): the
+// account is finished without the ref, which is what materialization
+// would make of its manifest at the next start. One account per ref
+// holds either way.
+func (s *Server) finishPlatformMint(ctx context.Context, platform *Account, m PendingMint) (*Account, error) {
+ if s.cfg.Releases == nil {
+ return nil, fmt.Errorf("pending customer create %s: no deployment bucket", m.MintID)
+ }
+ if err := s.platformStep("mint"); err != nil {
+ log.Printf("console: platform %s: pending customer create %s (%q): mint: %v", platform.Sqid, m.MintID, m.Name, err)
+ return nil, err
+ }
+ id, sqid, _, err := domains.MintLinkedAccount(ctx, s.cfg.Releases, m.Name, platform.Sqid, m.Ref, m.MintID, m.CreatedAt)
+ if err != nil {
+ log.Printf("console: platform %s: pending customer create %s (%q): mint: %v", platform.Sqid, m.MintID, m.Name, err)
+ return nil, err
+ }
+ if err := s.startNewAccountAnalytics(ctx, sqid); err != nil {
+ log.Printf("console: platform %s: minted customer %s (id %d, pending create %s) into the bucket but "+
+ "could not turn analytics on: %v; the next platform request finishes it", platform.Sqid, sqid, id, m.MintID, err)
+ return nil, err
+ }
+ if err := s.platformStep("finish"); err != nil {
+ log.Printf("console: platform %s: minted customer %s (id %d, pending create %s) into the bucket but "+
+ "could not record it: %v; the next platform request finishes it", platform.Sqid, sqid, id, m.MintID, err)
+ return nil, err
+ }
+ a := NewLinkedAccount{ID: id, Sqid: sqid, Name: m.Name, Platform: platform.Sqid, Ref: m.Ref, MintID: m.MintID,
+ Plan: m.Plan, PlanReason: m.PlanReason, By: m.By}
+ err = s.store.CreateLinkedAccount(ctx, a, m.CreatedAt)
+ if errors.Is(err, ErrPlatformRefTaken) && a.Ref != "" {
+ log.Printf("console: platform %s: customer %s (pending create %s) names ref %q, which another live "+
+ "customer of the platform holds; finishing it without the ref", platform.Sqid, sqid, m.MintID, m.Ref)
+ a.Ref = ""
+ err = s.store.CreateLinkedAccount(ctx, a, m.CreatedAt)
+ }
+ switch {
+ case err == nil:
+ case errors.Is(err, ErrAccountGone):
+ log.Printf("console: platform %s: pending customer create %s ended: customer %s was deleted before it was finished",
+ platform.Sqid, m.MintID, sqid)
+ return nil, fmt.Errorf("%w: %w", errPlatformMintEnded, err)
+ case errors.Is(err, errLinkedIDTaken):
+ if rerr := s.restoreHeldManifest(ctx, platform, m, id, sqid); rerr != nil {
+ log.Printf("console: platform %s: pending customer create %s: the bucket gave it id %d, which this console "+
+ "holds for another account, and accounts/%s/account.json could not be restored: %v; the next platform "+
+ "request tries again", platform.Sqid, m.MintID, id, sqid, rerr)
+ return nil, rerr
+ }
+ if derr := s.store.DropPendingMint(ctx, platform.Sqid, m.MintID); derr != nil {
+ log.Printf("console: platform %s: pending customer create %s: drop after an id conflict: %v", platform.Sqid, m.MintID, derr)
+ return nil, derr
+ }
+ log.Printf("console: platform %s: pending customer create %s dropped: the bucket gave it id %d, which this "+
+ "console holds for another account; accounts/%s/account.json now describes that account", platform.Sqid,
+ m.MintID, id, sqid)
+ return nil, fmt.Errorf("%w: %w", errPlatformMintEnded, err)
+ default:
+ log.Printf("console: platform %s: minted customer %s (id %d, pending create %s) into the bucket but "+
+ "could not record it: %v; the next platform request finishes it", platform.Sqid, sqid, id, m.MintID, err)
+ return nil, err
+ }
+ cust := &Account{ID: id, Sqid: sqid, Name: m.Name, CreatedAt: m.CreatedAt.UTC()}
+ s.audit(platform, accountAuditSubject, m.By, auditPlatformCustomerCreate,
+ fmt.Sprintf(platformCopy["audit.customer_create"], m.Name, sqid))
+ s.audit(cust, accountAuditSubject, m.By, auditPlatformCustomerCreated,
+ fmt.Sprintf(platformCopy["audit.customer_created_by"], platform.Sqid))
+ return cust, nil
+}
diff --git a/internal/console/apiplatformcustomers_test.go b/internal/console/apiplatformcustomers_test.go
new file mode 100644
index 000000000..07e7ff69f
--- /dev/null
+++ b/internal/console/apiplatformcustomers_test.go
@@ -0,0 +1,1136 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// platformDoorPatterns is every platform door Task 8 registers.
+var platformDoorPatterns = []string{
+ "GET /api/cli/platform/{account}/customers",
+ "GET /api/cli/platform/{account}/customers/{customer}",
+ "POST /api/cli/platform/{account}/customers",
+}
+
+func platformCustomersURL(base, sqid string) string {
+ return base + "/api/cli/platform/" + sqid + "/customers"
+}
+
+// grantPlatformAccount makes the account a platform account for up to max
+// customers on plans, the first of them the default, and returns the grant.
+func grantPlatformAccount(t *testing.T, fx *consoleFixture, sqid string, max int, plans ...string) *PlatformGrant {
+ t.Helper()
+ acct, err := fx.st.AccountBySqid(sqid)
+ if err != nil || acct == nil {
+ t.Fatalf("account %s: %+v %v", sqid, acct, err)
+ }
+ g := PlatformGrant{AccountID: acct.ID, MaxCustomers: max, Plans: plans, Reason: "r", GrantedBy: "ops@keymail.dev"}
+ if len(plans) > 0 {
+ g.DefaultPlan = plans[0]
+ }
+ ctx := context.Background()
+ if err := fx.st.PutPlatformGrant(ctx, g, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ got, err := fx.st.PlatformGrant(ctx, acct.ID)
+ if err != nil || got == nil {
+ t.Fatalf("grant %+v %v", got, err)
+ }
+ return got
+}
+
+// platformToken mints the platform account's platform credential.
+func platformToken(t *testing.T, fx *consoleFixture, platformID int64, name string) string {
+ t.Helper()
+ return serviceToken(t, fx.st, platformID, name, "", svcrole.Platform)
+}
+
+// callJSON is one request with no *testing.T, so goroutines can make it.
+func callJSON(method, u, bearer string, body any) (int, map[string]any, string, error) {
+ var rdr io.Reader
+ if body != nil {
+ b, err := json.Marshal(body)
+ if err != nil {
+ return 0, nil, "", err
+ }
+ rdr = bytes.NewReader(b)
+ }
+ req, err := http.NewRequest(method, u, rdr)
+ if err != nil {
+ return 0, nil, "", err
+ }
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ if bearer != "" {
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ }
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return 0, nil, "", err
+ }
+ defer res.Body.Close()
+ raw, err := io.ReadAll(res.Body)
+ if err != nil {
+ return 0, nil, "", err
+ }
+ var out map[string]any
+ _ = json.Unmarshal(raw, &out) // a stdlib 404 is not JSON
+ return res.StatusCode, out, string(raw), nil
+}
+
+func createCustomer(t *testing.T, base, sqid, bearer string, body map[string]any) (int, map[string]any, string) {
+ t.Helper()
+ status, out, raw, err := callJSON(http.MethodPost, platformCustomersURL(base, sqid), bearer, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return status, out, raw
+}
+
+func getPlatform(t *testing.T, u, bearer string) (int, map[string]any, string) {
+ t.Helper()
+ status, out, raw, err := callJSON(http.MethodGet, u, bearer, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return status, out, raw
+}
+
+// customerIn is the reply's customer object.
+func customerIn(t *testing.T, out map[string]any) map[string]any {
+ t.Helper()
+ c, ok := out["customer"].(map[string]any)
+ if !ok {
+ t.Fatalf("reply %v has no customer", out)
+ }
+ return c
+}
+
+func customersIn(t *testing.T, out map[string]any) []map[string]any {
+ t.Helper()
+ list, ok := out["customers"].([]any)
+ if !ok {
+ t.Fatalf("reply %v has no customers list", out)
+ }
+ var cs []map[string]any
+ for _, c := range list {
+ cs = append(cs, c.(map[string]any))
+ }
+ return cs
+}
+
+// platformManifests is every account manifest in the bucket that names
+// platformSqid as its platform, tombstones included.
+func platformManifests(t *testing.T, rel release.Store, platformSqid string) []domains.AccountManifest {
+ t.Helper()
+ ctx := context.Background()
+ keys, err := rel.List(ctx, "accounts/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []domains.AccountManifest
+ for _, key := range keys {
+ if _, ok := domains.AccountManifestSqid(key); !ok {
+ continue
+ }
+ body, _, err := rel.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var m domains.AccountManifest
+ if err := json.Unmarshal(body, &m); err != nil {
+ continue
+ }
+ if m.Platform == platformSqid {
+ out = append(out, m)
+ }
+ }
+ return out
+}
+
+// failStep is a platformMintStep that fails step, every time or (once) the
+// first time only.
+func failStep(step string, once bool) func(string) error {
+ var fired atomic.Bool
+ return func(s string) error {
+ if s != step {
+ return nil
+ }
+ if once && !fired.CompareAndSwap(false, true) {
+ return nil
+ }
+ return fmt.Errorf("injected %s failure", step)
+ }
+}
+
+// restartConsole stands in for a console restart: the first server stops
+// answering and a new one starts over the same console.db and bucket, so
+// startup runs MaterializeAccounts (Task 5).
+func restartConsole(t *testing.T, fx *consoleFixture) (*Server, string) {
+ t.Helper()
+ fx.ts.Close()
+ srv, err := NewServer(fx.srv.cfg, fx.st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(srv.replicaKicks.Wait)
+ ts := httptest.NewServer(srv)
+ t.Cleanup(ts.Close)
+ return srv, ts.URL
+}
+
+func TestPlatformDoorsTakeOnlyThePlatformRole(t *testing.T) {
+ fx := newConsoleFixture(t)
+ var doors []string
+ for pattern, set := range fx.srv.cliRoles {
+ path := pattern
+ if _, p, ok := strings.Cut(pattern, " "); ok {
+ path = p
+ }
+ if !strings.HasPrefix(path, "/api/cli/platform/") {
+ if set.Permits(svcrole.Platform) {
+ t.Errorf("%s permits the platform role; only the platform doors may", pattern)
+ }
+ continue
+ }
+ doors = append(doors, pattern)
+ for _, r := range svcrole.All() {
+ if set.Permits(r) != (r == svcrole.Platform) {
+ t.Errorf("%s: Permits(%q) = %v, want exactly the platform role", pattern, r, set.Permits(r))
+ }
+ }
+ }
+ slices.Sort(doors)
+ if !slices.Equal(doors, platformDoorPatterns) {
+ t.Fatalf("platform doors %v, want %v", doors, platformDoorPatterns)
+ }
+
+ // A platform credential's mint names exactly those doors.
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ owner := cliToken(t, fx, "owner"+acct.Sqid+"@example.com", "code-platform-doors")
+ status, out := postJSON(t, servicesURL(fx, acct.Sqid), map[string]any{"name": "cms", "role": "platform"}, owner)
+ if status != http.StatusCreated {
+ t.Fatalf("mint = %d %v", status, out)
+ }
+ if got := fmt.Sprint(out["doors"]); got != fmt.Sprint(platformDoorPatterns) {
+ t.Fatalf("mint doors %s, want %v", got, platformDoorPatterns)
+ }
+}
+
+func TestAdminCredentialIsRefusedAtPlatformDoors(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ admin := serviceToken(t, fx.st, acct.ID, "adm", "", svcrole.Admin)
+ base := platformCustomersURL(fx.ts.URL, acct.Sqid)
+ for _, c := range []struct {
+ method, u string
+ body any
+ }{
+ {http.MethodGet, base, nil},
+ {http.MethodGet, base + "/bcd", nil},
+ {http.MethodPost, base, map[string]any{"name": "shop"}},
+ } {
+ status, out, raw, err := callJSON(c.method, c.u, admin, c.body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ msg, _ := out["error"].(string)
+ if status != http.StatusForbidden || !strings.Contains(msg, `holds role "admin"`) {
+ t.Errorf("admin %s %s = %d %s, want the role gate's 403", c.method, c.u, status, raw)
+ }
+ }
+ if m := platformManifests(t, fx.rel, acct.Sqid); len(m) != 0 {
+ t.Fatalf("refused admin wrote manifests %+v", m)
+ }
+}
+
+func TestPlatformDoorRefusesANonPlatformAndARevokedGrant(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ owner := cliToken(t, fx, "owner"+acct.Sqid+"@example.com", "code-platform-gate")
+ list := platformCustomersURL(fx.ts.URL, acct.Sqid)
+
+ status, out, _ := getPlatform(t, list, owner)
+ wantPlatformError(t, "list with no grant", status, out, http.StatusForbidden, "door.not_platform")
+ status, out, _ = createCustomer(t, fx.ts.URL, acct.Sqid, owner, map[string]any{"name": "shop"})
+ wantPlatformError(t, "create with no grant", status, out, http.StatusForbidden, "door.not_platform")
+
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ for _, bearer := range []string{owner, tok} {
+ if status, out, _ := getPlatform(t, list, bearer); status != http.StatusOK {
+ t.Fatalf("list under the grant = %d %v", status, out)
+ }
+ }
+ if _, err := fx.st.RevokePlatformGrant(context.Background(), acct.ID, "ops@keymail.dev", "r", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ status, out, _ = getPlatform(t, list, owner)
+ wantPlatformError(t, "owner's list after the revoke", status, out, http.StatusForbidden, "door.revoked")
+ status, out, _ = createCustomer(t, fx.ts.URL, acct.Sqid, owner, map[string]any{"name": "shop"})
+ wantPlatformError(t, "owner's create after the revoke", status, out, http.StatusForbidden, "door.revoked")
+ // The platform credential's generation ended: resolution refuses it.
+ if status, _, _ := getPlatform(t, list, tok); status != http.StatusUnauthorized {
+ t.Fatalf("platform credential after the revoke = %d, want 401", status)
+ }
+ if m := platformManifests(t, fx.rel, acct.Sqid); len(m) != 0 {
+ t.Fatalf("refused creates wrote manifests %+v", m)
+ }
+}
+
+func TestPlatformDoorAdmitsAnOwnerNotAMember(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ if err := fx.st.AddMember(acct.ID, "member@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ owner := cliToken(t, fx, "owner"+acct.Sqid+"@example.com", "code-platform-owner")
+ member := cliToken(t, fx, "member@example.com", "code-platform-member")
+ stranger := cliToken(t, fx, "stranger@example.com", "code-platform-stranger")
+ list := platformCustomersURL(fx.ts.URL, acct.Sqid)
+
+ if status, out, _ := getPlatform(t, list, owner); status != http.StatusOK || out["platform"] != acct.Sqid {
+ t.Fatalf("owner's list = %d %v", status, out)
+ }
+ status, out, _ := getPlatform(t, list, member)
+ wantPlatformError(t, "member's list", status, out, http.StatusForbidden, "door.not_owner")
+ status, out, _ = createCustomer(t, fx.ts.URL, acct.Sqid, member, map[string]any{"name": "shop"})
+ wantPlatformError(t, "member's create", status, out, http.StatusForbidden, "door.not_owner")
+ if status, _, raw := getPlatform(t, list, stranger); status != http.StatusNotFound || raw != "404 page not found\n" {
+ t.Fatalf("stranger's list = %d %q, want the stdlib 404", status, raw)
+ }
+}
+
+func TestCustomerCreateMintsALinkedOwnerlessAccount(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5, "free", "personal")
+ tok := platformToken(t, fx, acct.ID, "cms")
+
+ status, out, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ if status != http.StatusCreated || out["created"] != true {
+ t.Fatalf("create = %d %s", status, raw)
+ }
+ c := customerIn(t, out)
+ sqid, _ := c["account"].(string)
+ if c["name"] != "shop" || c["ref"] != "4812" || c["plan"] != "free" || c["plan_source"] != PlanSourcePlatform ||
+ c["claimed"] != false || fmt.Sprint(c["usage"]) != "[]" {
+ t.Fatalf("customer %v", c)
+ }
+
+ ms := platformManifests(t, fx.rel, acct.Sqid)
+ if len(ms) != 1 || ms[0].Sqid != sqid || ms[0].Owner != "" || ms[0].PlatformRef != "4812" || len(ms[0].PlatformMint) != 32 {
+ t.Fatalf("manifests %+v, want one ownerless manifest for %s linked with ref 4812", ms, sqid)
+ }
+ cust, err := fx.st.AccountBySqid(sqid)
+ if err != nil || cust == nil {
+ t.Fatalf("customer row %s: %+v %v", sqid, cust, err)
+ }
+ if members, err := fx.st.Members(cust.ID); err != nil || len(members) != 0 {
+ t.Fatalf("customer members %+v %v, want none", members, err)
+ }
+ row, err := fx.st.AccountPlan(cust.ID)
+ if err != nil || row == nil || row.Plan != "free" || row.Source != PlanSourcePlatform || row.Reason != "platform "+acct.Sqid {
+ t.Fatalf("plan row %+v %v, want free from platform %s", row, err, acct.Sqid)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints after a create %+v", p)
+ }
+ actor := "service:" + acct.Sqid + "/cms"
+ rows := platformAudit(t, fx, acct.ID, auditPlatformCustomerCreate)
+ if want := fmt.Sprintf(platformCopy["audit.customer_create"], "shop", sqid); len(rows) != 1 || rows[0].Detail != want || rows[0].Address != actor {
+ t.Fatalf("platform audit %+v, want %q by %s", rows, want, actor)
+ }
+ rows = platformAudit(t, fx, cust.ID, auditPlatformCustomerCreated)
+ if want := fmt.Sprintf(platformCopy["audit.customer_created_by"], acct.Sqid); len(rows) != 1 || rows[0].Detail != want || rows[0].Address != actor {
+ t.Fatalf("customer audit %+v, want %q by %s", rows, want, actor)
+ }
+}
+
+func TestCustomerCreateIsIdempotentOnRef(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ status, out, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ if status != http.StatusCreated {
+ t.Fatalf("first create = %d %s", status, raw)
+ }
+ first := customerIn(t, out)["account"]
+ status, out, raw = createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "other", "ref": "4812"})
+ if status != http.StatusOK || out["created"] != false {
+ t.Fatalf("second create = %d %s, want 200 created false", status, raw)
+ }
+ if c := customerIn(t, out); c["account"] != first || c["name"] != "shop" {
+ t.Fatalf("second create answered %v, want %v named shop", c, first)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 1 {
+ t.Fatalf("manifests %+v, want one", ms)
+ }
+}
+
+func TestCustomerCreateConcurrentSameRefMakesOneAccount(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 50)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ const n = 8
+ statuses := make([]int, n)
+ sqids := make([]string, n)
+ errs := make([]error, n)
+ var wg sync.WaitGroup
+ for i := range n {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ status, out, _, err := callJSON(http.MethodPost, platformCustomersURL(fx.ts.URL, acct.Sqid), tok,
+ map[string]any{"name": fmt.Sprintf("shop-%d", i), "ref": "4812"})
+ statuses[i], errs[i] = status, err
+ if c, ok := out["customer"].(map[string]any); ok {
+ sqids[i], _ = c["account"].(string)
+ }
+ }()
+ }
+ wg.Wait()
+ created := 0
+ for i := range n {
+ if errs[i] != nil {
+ t.Fatal(errs[i])
+ }
+ switch statuses[i] {
+ case http.StatusCreated:
+ created++
+ case http.StatusOK:
+ default:
+ t.Fatalf("create %d = %d", i, statuses[i])
+ }
+ if sqids[i] == "" || sqids[i] != sqids[0] {
+ t.Fatalf("creates answered %v, want one sqid", sqids)
+ }
+ }
+ if created != 1 {
+ t.Fatalf("%d creates answered 201, want 1 (%v)", created, statuses)
+ }
+ if n := linkedCount(t, fx.st, acct.Sqid); n != 1 {
+ t.Fatalf("LinkedCustomerCount = %d, want 1", n)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 1 {
+ t.Fatalf("manifests %+v, want one", ms)
+ }
+}
+
+func TestCustomerCreateSurvivesAFailedFinish(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 1)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ fx.srv.platformMintStep = failStep("finish", true)
+
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ wantPlatformError(t, "create with a failed finish", status, out, http.StatusBadGateway, "create.failed")
+ ms := platformManifests(t, fx.rel, acct.Sqid)
+ if len(ms) != 1 {
+ t.Fatalf("manifests after the failed finish %+v, want one", ms)
+ }
+ stranded := ms[0].Sqid
+ if row, err := fx.st.AccountBySqid(stranded); err != nil || row != nil {
+ t.Fatalf("account row %s = %+v %v, want none", stranded, row, err)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 1 || p[0].Ref != "4812" || p[0].MintID != ms[0].PlatformMint {
+ t.Fatalf("pending mints %+v, want the one the manifest carries", p)
+ }
+ if n := linkedCount(t, fx.st, acct.Sqid); n != 1 {
+ t.Fatalf("LinkedCustomerCount = %d, want 1", n)
+ }
+
+ // The promise holds the only slot.
+ status, out, _ = createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "cafe", "ref": "4813"})
+ if status != http.StatusConflict || out["error"] != fmt.Sprintf(platformCopy["create.cap"], 1) {
+ t.Fatalf("second create = %d %v, want 409 create.cap", status, out)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 1 {
+ t.Fatalf("manifests after the capped create %+v, want still one", ms)
+ }
+
+ // The retry lands on the account the first attempt minted.
+ status, out, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ if status != http.StatusOK || out["created"] != false || customerIn(t, out)["account"] != stranded {
+ t.Fatalf("retry = %d %s, want 200 created false for %s", status, raw, stranded)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 1 {
+ t.Fatalf("manifests after the retry %+v, want one", ms)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints after the retry %+v", p)
+ }
+}
+
+// landThenFailStore lands the first accounts/ Put it is armed for and then
+// reports it failed: an ambiguous write.
+type landThenFailStore struct {
+ release.Store
+ armed atomic.Bool
+}
+
+func (s *landThenFailStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if strings.HasPrefix(key, "accounts/") && s.armed.CompareAndSwap(true, false) {
+ if _, err := s.Store.Put(ctx, key, body, ifMatch); err != nil {
+ return "", err
+ }
+ return "", errors.New("injected: the write landed and its answer was lost")
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+func TestCustomerCreateSurvivesAFailedMintPut(t *testing.T) {
+ wrap := &landThenFailStore{}
+ fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, WrapReleases: func(r release.Store) release.Store {
+ wrap.Store = r
+ return wrap
+ }})
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ wrap.armed.Store(true)
+
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ wantPlatformError(t, "create with a lost Put answer", status, out, http.StatusBadGateway, "create.failed")
+ ms := platformManifests(t, fx.rel, acct.Sqid)
+ if len(ms) != 1 {
+ t.Fatalf("manifests after the lost answer %+v, want the one that landed", ms)
+ }
+ landed := ms[0].Sqid
+
+ status, out, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ if (status != http.StatusOK && status != http.StatusCreated) || customerIn(t, out)["account"] != landed {
+ t.Fatalf("retry = %d %s, want the account that landed, %s", status, raw, landed)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 1 {
+ t.Fatalf("manifests after the retry %+v, want one", ms)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints after the retry %+v", p)
+ }
+}
+
+func TestCustomerCreateConvergesAcrossARestart(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5, "free")
+ tok := platformToken(t, fx, acct.ID, "cms")
+ fx.srv.platformMintStep = failStep("finish", false)
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ wantPlatformError(t, "create with a failed finish", status, out, http.StatusBadGateway, "create.failed")
+
+ _, base := restartConsole(t, fx)
+ status, out, raw := getPlatform(t, platformCustomersURL(base, acct.Sqid), tok)
+ if status != http.StatusOK {
+ t.Fatalf("list after the restart = %d %s", status, raw)
+ }
+ cs := customersIn(t, out)
+ if len(cs) != 1 || cs[0]["ref"] != "4812" || cs[0]["plan"] != "free" || cs[0]["plan_source"] != PlanSourcePlatform ||
+ out["count"] != float64(1) {
+ t.Fatalf("list after the restart %s, want one customer 4812 on the platform's plan", raw)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints after the restart %+v", p)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 1 || ms[0].Sqid != cs[0]["account"] {
+ t.Fatalf("manifests %+v, want the one listed", ms)
+ }
+}
+
+func TestCustomerListCountsAMaterializedMintOnceAfterARestart(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 2)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ fx.srv.platformMintStep = failStep("finish", false)
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ wantPlatformError(t, "create with a failed finish", status, out, http.StatusBadGateway, "create.failed")
+
+ srv, base := restartConsole(t, fx)
+ srv.platformMintStep = failStep("finish", false)
+ status, out, raw := getPlatform(t, platformCustomersURL(base, acct.Sqid), tok)
+ if status != http.StatusOK {
+ t.Fatalf("list with the finish failing = %d %s, want the read door to go on", status, raw)
+ }
+ if cs := customersIn(t, out); len(cs) != 1 || cs[0]["ref"] != "4812" || out["count"] != float64(1) {
+ t.Fatalf("list %s, want one customer 4812 counted once", raw)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 1 {
+ t.Fatalf("pending mints %+v, want the unfinished one", p)
+ }
+
+ srv.platformMintStep = nil
+ status, _, raw = createCustomer(t, base, acct.Sqid, tok, map[string]any{"name": "cafe", "ref": "4813"})
+ if status != http.StatusCreated {
+ t.Fatalf("create 4813 under max 2 = %d %s, want 201", status, raw)
+ }
+ if n := linkedCount(t, fx.st, acct.Sqid); n != 2 {
+ t.Fatalf("LinkedCustomerCount = %d, want 2", n)
+ }
+}
+
+// lockedReply is a create's answer, from a goroutine.
+type lockedReply struct {
+ status int
+ out map[string]any
+ raw string
+ err error
+}
+
+// createAcrossALockedChange holds the platform's lifecycle lock, starts a
+// create, waits until the create is about to take the lock, runs change,
+// and releases: the create runs its step 2 after change.
+func createAcrossALockedChange(t *testing.T, fx *consoleFixture, platform, tok string, body map[string]any, change func()) lockedReply {
+ t.Helper()
+ reached := make(chan struct{})
+ var once sync.Once
+ fx.srv.platformMintStep = func(step string) error {
+ if step == "lock" {
+ once.Do(func() { close(reached) })
+ }
+ return nil
+ }
+ defer func() { fx.srv.platformMintStep = nil }()
+ unlock := fx.srv.lockPlatformLifecycle(platform)
+ done := make(chan lockedReply, 1)
+ go func() {
+ status, out, raw, err := callJSON(http.MethodPost, platformCustomersURL(fx.ts.URL, platform), tok, body)
+ done <- lockedReply{status, out, raw, err}
+ }()
+ guard := time.NewTimer(10 * time.Second)
+ defer guard.Stop()
+ select {
+ case <-reached:
+ case <-guard.C:
+ unlock()
+ t.Fatal("the create never reached the platform lock")
+ }
+ change()
+ unlock()
+ select {
+ case got := <-done:
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ return got
+ case <-guard.C:
+ t.Fatal("the create never answered")
+ }
+ return lockedReply{}
+}
+
+func TestCustomerCreateRechecksThePlatformUnderTheLock(t *testing.T) {
+ fx := newConsoleFixture(t)
+ for _, c := range []struct {
+ name string
+ id int64
+ change func(*testing.T, *Account)
+ status int
+ row string
+ }{
+ {"deleted", 501, func(t *testing.T, a *Account) {
+ if err := fx.st.DeleteAccount(a.ID, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }, http.StatusNotFound, ""},
+ {"revoked", 502, func(t *testing.T, a *Account) {
+ if _, err := fx.st.RevokePlatformGrant(context.Background(), a.ID, "ops@keymail.dev", "r", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }, http.StatusForbidden, "door.revoked"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ acct := planAccount(t, fx, c.id)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ got := createAcrossALockedChange(t, fx, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"},
+ func() { c.change(t, acct) })
+ if c.row == "" {
+ if got.status != http.StatusNotFound || got.raw != "404 page not found\n" {
+ t.Fatalf("create on a platform deleted under it = %d %q, want the stdlib 404", got.status, got.raw)
+ }
+ } else {
+ wantPlatformError(t, "create on a platform revoked under it", got.status, got.out, c.status, c.row)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 0 {
+ t.Fatalf("manifests %+v, want none", ms)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints %+v, want none", p)
+ }
+ })
+ }
+}
+
+// TestCustomerCreateReadsTheGrantUnderTheLock: a grant an operator changed
+// while the create waited for the lock is the one the create obeys, for its
+// plans and for its cap.
+func TestCustomerCreateReadsTheGrantUnderTheLock(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5, "free", "personal")
+ tok := platformToken(t, fx, acct.ID, "cms")
+
+ got := createAcrossALockedChange(t, fx, acct.Sqid, tok, map[string]any{"name": "shop", "plan": "personal"},
+ func() { grantPlatformAccount(t, fx, acct.Sqid, 5, "free") })
+ if got.status != http.StatusBadRequest || got.out["error"] != fmt.Sprintf(platformCopy["create.plan"], "free") {
+ t.Fatalf("create on a plan dropped under it = %d %s, want 400 create.plan", got.status, got.raw)
+ }
+
+ if status, _, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop"}); status != http.StatusCreated {
+ t.Fatalf("create = %d %s", status, raw)
+ }
+ got = createAcrossALockedChange(t, fx, acct.Sqid, tok, map[string]any{"name": "cafe"},
+ func() { grantPlatformAccount(t, fx, acct.Sqid, 1, "free") })
+ if got.status != http.StatusConflict || got.out["error"] != fmt.Sprintf(platformCopy["create.cap"], 1) {
+ t.Fatalf("create past a max lowered under it = %d %s, want 409 create.cap", got.status, got.raw)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 1 {
+ t.Fatalf("manifests %+v, want the one good create's", ms)
+ }
+}
+
+func TestCustomerCreateRefusesAPlanOutsideTheGrant(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5, "free")
+ tok := platformToken(t, fx, acct.ID, "cms")
+ for _, plan := range []string{"personal", "gold"} {
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "plan": plan})
+ if status != http.StatusBadRequest || out["error"] != fmt.Sprintf(platformCopy["create.plan"], "free") {
+ t.Errorf("create on plan %s = %d %v, want 400 create.plan", plan, status, out)
+ }
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 0 {
+ t.Fatalf("refused creates wrote %+v", ms)
+ }
+
+ // With no catalog a grant has no plans, a named plan is refused, and a
+ // customer gets no plan row (decision D8).
+ bare := newConsoleFixture(t)
+ other := planAccount(t, bare, 502)
+ grantPlatformAccount(t, bare, other.Sqid, 5)
+ otherTok := platformToken(t, bare, other.ID, "cms")
+ status, out, _ := createCustomer(t, bare.ts.URL, other.Sqid, otherTok, map[string]any{"name": "shop", "plan": "free"})
+ wantPlatformError(t, "a named plan with no catalog", status, out, http.StatusBadRequest, "create.no_catalog_plan")
+ status, out, raw := createCustomer(t, bare.ts.URL, other.Sqid, otherTok, map[string]any{"name": "shop"})
+ if status != http.StatusCreated {
+ t.Fatalf("create with no catalog = %d %s", status, raw)
+ }
+ if c := customerIn(t, out); c["plan"] != nil || c["plan_source"] != nil {
+ t.Fatalf("customer with no catalog %v, want no plan", c)
+ }
+}
+
+func TestCustomerCreateStopsAtMaxCustomers(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 2)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ for _, name := range []string{"shop", "cafe"} {
+ if status, _, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": name}); status != http.StatusCreated {
+ t.Fatalf("create %s = %d %s", name, status, raw)
+ }
+ }
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "bakery"})
+ if status != http.StatusConflict || out["error"] != fmt.Sprintf(platformCopy["create.cap"], 2) {
+ t.Fatalf("third create = %d %v, want 409 create.cap", status, out)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 2 {
+ t.Fatalf("manifests %+v, want two", ms)
+ }
+
+ grantPlatformAccount(t, fx, acct.Sqid, 1)
+ status, out, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid), tok)
+ if status != http.StatusOK || len(customersIn(t, out)) != 2 || out["count"] != float64(2) || out["max_customers"] != float64(1) {
+ t.Fatalf("list after lowering the grant = %d %s, want both customers still listed", status, raw)
+ }
+}
+
+func TestCustomerCreateRefusesBadNamesAndRefs(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ for _, c := range []struct {
+ body map[string]any
+ id string
+ }{
+ {map[string]any{"name": "Shop!"}, "create.name"},
+ {map[string]any{"name": ""}, "create.name"},
+ {map[string]any{"name": "shop", "ref": "a b"}, "create.ref"},
+ {map[string]any{"name": "shop", "ref": strings.Repeat("a", 65)}, "create.ref"},
+ {map[string]any{"name": "shop", "ref": "é"}, "create.ref"},
+ } {
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, c.body)
+ wantPlatformError(t, fmt.Sprintf("create %v", c.body), status, out, http.StatusBadRequest, c.id)
+ }
+ // The longest ref and every character the grammar allows are taken.
+ ok := strings.Repeat("a", 64-len("AZaz09._:-")) + "AZaz09._:-"
+ if status, _, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": ok}); status != http.StatusCreated {
+ t.Fatalf("create with ref %q = %d %s", ok, status, raw)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 1 {
+ t.Fatalf("manifests %+v, want only the good create's", ms)
+ }
+}
+
+func TestCustomerListAndShowCarryUsage(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ status, out, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ if status != http.StatusCreated {
+ t.Fatalf("create = %d %s", status, raw)
+ }
+ sqid, _ := customerIn(t, out)["account"].(string)
+ cust, err := fx.st.AccountBySqid(sqid)
+ if err != nil || cust == nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ grace := now.Add(time.Hour).Truncate(time.Second)
+ for _, st := range []capState{
+ {AccountID: cust.ID, Cap: capStorage, Period: capPeriod(capStorage, now), Level: levelWarn, Used: 90, Limit: 100, UpdatedAt: now},
+ {AccountID: cust.ID, Cap: capEmail, Period: capPeriod(capEmail, now), Level: levelOver, Used: 120, Limit: 100,
+ FirstOver: now, GraceEnds: grace, UpdatedAt: now},
+ {AccountID: cust.ID, Cap: capBandwidth, Period: "2001-01", Level: levelOver, Used: 9, Limit: 1, UpdatedAt: now},
+ } {
+ if err := fx.st.PutCapState(st); err != nil {
+ t.Fatal(err)
+ }
+ }
+ want := fmt.Sprintf("[map[cap:storage level:warn limit:100 used:90] map[cap:email grace_ends:%s level:over limit:100 used:120]]",
+ grace.UTC().Format(time.RFC3339))
+
+ status, show, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid)+"/"+sqid, tok)
+ if status != http.StatusOK || show["account"] != sqid || fmt.Sprint(show["usage"]) != want {
+ t.Fatalf("show = %d %s, want usage %s", status, raw, want)
+ }
+ status, list, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid), tok)
+ if status != http.StatusOK || list["platform"] != acct.Sqid || list["max_customers"] != float64(5) || list["count"] != float64(1) {
+ t.Fatalf("list = %d %s", status, raw)
+ }
+ if cs := customersIn(t, list); len(cs) != 1 || fmt.Sprint(cs[0]["usage"]) != want {
+ t.Fatalf("list %s, want usage %s", raw, want)
+ }
+ status, byRef, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid)+"?ref=4812", tok)
+ if cs := customersIn(t, byRef); status != http.StatusOK || len(cs) != 1 || cs[0]["account"] != sqid || fmt.Sprint(cs[0]["usage"]) != want {
+ t.Fatalf("list ?ref=4812 = %d %s", status, raw)
+ }
+ status, byRef, raw = getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid)+"?ref=4813", tok)
+ if cs := customersIn(t, byRef); status != http.StatusOK || len(cs) != 0 || byRef["count"] != float64(1) {
+ t.Fatalf("list ?ref=4813 = %d %s, want no customers", status, raw)
+ }
+}
+
+func TestCustomerDoorsHideOtherPlatformsCustomers(t *testing.T) {
+ fx := newConsoleFixture(t)
+ a := planAccount(t, fx, 501)
+ b := planAccount(t, fx, 502)
+ grantPlatformAccount(t, fx, a.Sqid, 5)
+ grantPlatformAccount(t, fx, b.Sqid, 5)
+ tokA := platformToken(t, fx, a.ID, "cms")
+ tokB := platformToken(t, fx, b.ID, "cms")
+ status, out, raw := createCustomer(t, fx.ts.URL, b.Sqid, tokB, map[string]any{"name": "shop"})
+ if status != http.StatusCreated {
+ t.Fatalf("B's create = %d %s", status, raw)
+ }
+ theirs, _ := customerIn(t, out)["account"].(string)
+ if status, _, _ := getPlatform(t, platformCustomersURL(fx.ts.URL, b.Sqid)+"/"+theirs, tokB); status != http.StatusOK {
+ t.Fatalf("B's own show = %d", status)
+ }
+
+ statusTheirs, _, rawTheirs := getPlatform(t, platformCustomersURL(fx.ts.URL, a.Sqid)+"/"+theirs, tokA)
+ statusUnknown, _, rawUnknown := getPlatform(t, platformCustomersURL(fx.ts.URL, a.Sqid)+"/zzzz", tokA)
+ if statusTheirs != http.StatusNotFound || statusUnknown != http.StatusNotFound || rawTheirs != rawUnknown ||
+ rawTheirs != "404 page not found\n" {
+ t.Fatalf("A on B's customer = %d %q, on an unknown sqid = %d %q, want the identical stdlib 404",
+ statusTheirs, rawTheirs, statusUnknown, rawUnknown)
+ }
+ // A's credential speaks for A only.
+ if status, _, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, b.Sqid), tokA); status != http.StatusNotFound || raw != "404 page not found\n" {
+ t.Fatalf("A's credential on B's list = %d %q, want the stdlib 404", status, raw)
+ }
+}
+
+func TestPlatformCredentialRefusedAtOrdinaryDoors(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ for _, c := range []struct {
+ method, u string
+ body any
+ }{
+ // The account's app list (GET /api/cli/apps/<p> alone is no route).
+ {http.MethodGet, fx.ts.URL + "/api/cli/apps/" + acct.Sqid + "/list", nil},
+ {http.MethodGet, fx.ts.URL + "/api/cli/apps", nil},
+ {http.MethodPost, servicesURL(fx, acct.Sqid), map[string]any{"name": "other", "role": "publish"}},
+ } {
+ status, _, raw, err := callJSON(c.method, c.u, tok, c.body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if status != http.StatusForbidden {
+ t.Errorf("platform credential at %s %s = %d %s, want the role gate's 403", c.method, c.u, status, raw)
+ }
+ }
+ if rows, err := fx.st.ServicePrincipals(acct.ID); err != nil || len(rows) != 1 {
+ t.Fatalf("service principals %+v %v, want only cms", rows, err)
+ }
+}
+
+// TestCustomerFinishOverAnIDHeldByAnotherAccountEndsThePromise is the stuck-mint
+// recovery: the bucket gives a pending mint an id this console holds for
+// another account. The manifest the mint wrote is restored to describe that
+// account, the promise is dropped (it can never finish), the other account's
+// row is untouched, and the platform's retry gets a fresh account.
+func TestCustomerFinishOverAnIDHeldByAnotherAccountEndsThePromise(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 1)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ // A console row whose manifest the bucket does not have, at the id the
+ // next mint takes.
+ next, err := domains.NextAccountID(context.Background(), fx.rel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.CreateAccount(next, domains.Sqid(next), "other", "other@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ wantPlatformError(t, "create over a held id", status, out, http.StatusBadGateway, "create.failed")
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints %+v, want the promise ended", p)
+ }
+ if n := linkedCount(t, fx.st, acct.Sqid); n != 0 {
+ t.Fatalf("LinkedCustomerCount = %d, want 0: the ended promise holds no slot", n)
+ }
+ other, err := fx.st.AccountBySqid(domains.Sqid(next))
+ if err != nil || other == nil || other.Name != "other" {
+ t.Fatalf("the other account %+v %v, want it untouched", other, err)
+ }
+ if linked, _, err := fx.st.AccountPlatform(context.Background(), next); err != nil || linked != "" {
+ t.Fatalf("the other account's link %q %v, want none", linked, err)
+ }
+ // The manifest the mint wrote at the held id now describes the account
+ // that holds it, live and unlinked, so the bucket names this platform's
+ // ref nowhere.
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 0 {
+ t.Fatalf("manifests naming the platform %+v, want none", ms)
+ }
+ body, _, err := fx.rel.Get(context.Background(), domains.AccountManifestKey(domains.Sqid(next)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var held domains.AccountManifest
+ if err := json.Unmarshal(body, &held); err != nil || held.ID != next || held.Sqid != domains.Sqid(next) ||
+ held.Name != "other" || held.Platform != "" || held.PlatformRef != "" || held.PlatformMint != "" ||
+ held.Owner != "" || held.Deleted() {
+ t.Fatalf("manifest at the held id %s %v, want the other account's, live and unlinked", body, err)
+ }
+
+ // The retry promises afresh and mints the next free id.
+ status, out, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ if status != http.StatusCreated {
+ t.Fatalf("retry = %d %s, want 201", status, raw)
+ }
+ if got := customerIn(t, out)["account"]; got == domains.Sqid(next) {
+ t.Fatalf("retry answered the held id %v", got)
+ }
+ status, list, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid), tok)
+ if cs := customersIn(t, list); status != http.StatusOK || len(cs) != 1 || cs[0]["ref"] != "4812" || list["count"] != float64(1) {
+ t.Fatalf("list = %d %s, want one customer for 4812", status, raw)
+ }
+}
+
+// TestCustomerFinishWhenTheRefIsHeldFinishesWithoutIt: a pending mint whose ref a
+// live customer took meanwhile (only a manifest written outside this console
+// can do that) is finished without the ref, as materialization would make
+// it, rather than kept for ever.
+func TestCustomerFinishWhenTheRefIsHeldFinishesWithoutIt(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ ctx := context.Background()
+ if err := fx.st.ReservePlatformMint(ctx, PendingMint{MintID: strings.Repeat("ab", 16), Platform: acct.Sqid,
+ Ref: "4812", Name: "shop", By: "service:" + acct.Sqid + "/cms", CreatedAt: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ holder := testAccountID()
+ if _, err := fx.st.EnsureLinkedAccount(holder, domains.Sqid(holder), "held", acct.Sqid, "4812",
+ strings.Repeat("cd", 16), time.Now()); err != nil {
+ t.Fatal(err)
+ }
+
+ status, out, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid), tok)
+ if status != http.StatusOK {
+ t.Fatalf("list = %d %s", status, raw)
+ }
+ cs := customersIn(t, out)
+ refs := map[string]string{}
+ for _, c := range cs {
+ ref, _ := c["ref"].(string)
+ refs[c["name"].(string)] = ref
+ }
+ if len(cs) != 2 || refs["held"] != "4812" || refs["shop"] != "" || out["count"] != float64(2) {
+ t.Fatalf("list %s, want held with 4812 and shop finished without a ref", raw)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints %+v, want none", p)
+ }
+}
+
+// TestCustomerCreateFinishesAPromiseMadeAfterItsGate is create's own
+// finish (step 3): a promise another create left unfinished after this
+// create passed the gate is finished under the lock, so this create lands
+// on that account instead of refusing a ref a promise holds.
+func TestCustomerCreateFinishesAPromiseMadeAfterItsGate(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ reached, release := make(chan struct{}), make(chan struct{})
+ var locks, finishes atomic.Int32
+ fx.srv.platformMintStep = func(step string) error {
+ switch {
+ case step == "lock" && locks.Add(1) == 1:
+ close(reached)
+ <-release
+ case step == "finish" && finishes.Add(1) == 1:
+ return errors.New("injected finish failure")
+ }
+ return nil
+ }
+ type reply struct {
+ status int
+ out map[string]any
+ raw string
+ err error
+ }
+ done := make(chan reply, 1)
+ go func() {
+ status, out, raw, err := callJSON(http.MethodPost, platformCustomersURL(fx.ts.URL, acct.Sqid), tok,
+ map[string]any{"name": "shop", "ref": "4812"})
+ done <- reply{status, out, raw, err}
+ }()
+ guard := time.NewTimer(10 * time.Second)
+ defer guard.Stop()
+ select {
+ case <-reached:
+ case <-guard.C:
+ t.Fatal("the first create never reached the platform lock")
+ }
+ // The second create passes the first's gate and lock, and leaves its
+ // promise unfinished.
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ close(release)
+ wantPlatformError(t, "second create with a failed finish", status, out, http.StatusBadGateway, "create.failed")
+ ms := platformManifests(t, fx.rel, acct.Sqid)
+ if len(ms) != 1 {
+ t.Fatalf("manifests %+v, want the second create's", ms)
+ }
+ var got reply
+ select {
+ case got = <-done:
+ case <-guard.C:
+ t.Fatal("the first create never answered")
+ }
+ if got.err != nil {
+ t.Fatal(got.err)
+ }
+ if got.status != http.StatusOK || got.out["created"] != false || customerIn(t, got.out)["account"] != ms[0].Sqid {
+ t.Fatalf("first create = %d %s, want 200 created false for %s", got.status, got.raw, ms[0].Sqid)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints %+v, want none", p)
+ }
+}
+
+// failOverwriteStore fails the first overwrite (a Put with an etag) of key.
+type failOverwriteStore struct {
+ release.Store
+ key atomic.Value // string
+ fired atomic.Bool
+}
+
+func (s *failOverwriteStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if k, _ := s.key.Load().(string); k == key && ifMatch != "" && s.fired.CompareAndSwap(false, true) {
+ return "", errors.New("injected overwrite failure")
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+// TestCustomerFinishKeepsThePromiseUntilTheManifestIsRestored: when the
+// held id's manifest cannot be restored, the promise is kept (it still
+// holds its slot and ref), and the next platform request ends it.
+func TestCustomerFinishKeepsThePromiseUntilTheManifestIsRestored(t *testing.T) {
+ wrap := &failOverwriteStore{}
+ fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, WrapReleases: func(r release.Store) release.Store {
+ wrap.Store = r
+ return wrap
+ }})
+ acct := planAccount(t, fx, 501)
+ grantPlatformAccount(t, fx, acct.Sqid, 5)
+ tok := platformToken(t, fx, acct.ID, "cms")
+ next, err := domains.NextAccountID(context.Background(), fx.rel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.CreateAccount(next, domains.Sqid(next), "other", "other@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ wrap.key.Store(domains.AccountManifestKey(domains.Sqid(next)))
+
+ status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"})
+ wantPlatformError(t, "create over a held id", status, out, http.StatusBadGateway, "create.failed")
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 1 || linkedCount(t, fx.st, acct.Sqid) != 1 {
+ t.Fatalf("pending mints %+v, want the promise kept while its manifest names the platform", p)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 1 {
+ t.Fatalf("manifests %+v, want the mint's", ms)
+ }
+
+ // The next platform request, a read, ends it.
+ if status, _, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid), tok); status != http.StatusOK {
+ t.Fatalf("list = %d %s", status, raw)
+ }
+ if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 {
+ t.Fatalf("pending mints %+v, want the promise ended", p)
+ }
+ if ms := platformManifests(t, fx.rel, acct.Sqid); len(ms) != 0 {
+ t.Fatalf("manifests naming the platform %+v, want none", ms)
+ }
+}
diff --git a/internal/console/applocks.go b/internal/console/applocks.go
index 7c5e67756..84936dc0b 100644
--- a/internal/console/applocks.go
+++ b/internal/console/applocks.go
@@ -76,6 +76,27 @@ func (s *Server) lockApp(sqid, app string) func() {
}
}
+// lockPlatformLifecycle is the platform lifecycle lock (platform accounts,
+// Astra r1-3, r2-1), keyed by the platform account's sqid. Customer
+// creation takes it from its re-read of the platform to its 201, finishing
+// a platform's pending mints runs under it, and account deletion
+// (handleDeleteAccount) takes it for the account being deleted, so no
+// customer, pending or live, can appear between a deletion's last check and
+// its tombstone. Nothing else takes it, and it is not re-entrant.
+//
+// LOCK ORDER: platform lifecycle, then account/plan (lockAccount,
+// planLock), then the billing hold (holdBilling). Never take this lock
+// while holding either of the others.
+func (s *Server) lockPlatformLifecycle(sqid string) func() {
+ lockEvent("platform", sqid, lockWaiting)
+ unlock := s.platformLocks.lock(sqid)
+ lockEvent("platform", sqid, lockHeld)
+ return func() {
+ lockEvent("platform", sqid, lockReleased)
+ unlock()
+ }
+}
+
// held reports whether key's mutex is held now, by anyone. The serving
// judgement (judgeServing) asserts with it that its caller holds the app
// lock: it cannot say whose hold it sees, but a caller that forgot the
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index d41477ef6..0b0a57f94 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -668,6 +668,9 @@ func (cx *claimCase) offlineMove(t *testing.T, state string) {
// claimSecondSqid is the second account the account-move door moves into.
var claimSecondSqid = domains.Sqid(2)
+// claimCustomerSqid is the census customer claimPlatformCustomer stages.
+var claimCustomerSqid = domains.Sqid(40)
+
func (cx *claimCase) secondAccount(t *testing.T) {
t.Helper()
if err := cx.st.CreateAccount(2, claimSecondSqid, "second", claimFxOwner, time.Now()); err != nil {
@@ -990,6 +993,11 @@ var claimFixtures = map[string]claimFixture{
"route GET /upgrade": claimRead("the pricing page's upgrade entry (plans 6b): redirects to the billing page of the account the caller owns, or the front door; writes nothing"),
"route GET /{$}": claimRead("the front door: redirects or renders sign-in"),
+ // The platform doors' reads (apiplatformcustomers.go): a platform's
+ // customer accounts, their plans and usage; names no app.
+ "route GET /api/cli/platform/{account}/customers": claimRead("a platform's view of its customer accounts with their plans and usage; names no app"),
+ "route GET /api/cli/platform/{account}/customers/{customer}": claimRead("a platform's view of one customer account with its plan and usage; names no app"),
+
// The page and the plain-text key both make the webhook signing key on
// first use (a keys row, as the first webhook send would): deployment
// state, no app's.
@@ -1547,6 +1555,7 @@ var claimFixtures = map[string]claimFixture{
"route POST /api/cli/accounts/{account}/plan": claimNonApp("operator sets an account's plan, packs and sponsored limits; names no app"),
"route PUT /api/cli/accounts/{account}/platform": claimNonApp("operator grants or changes an account's platform grant, writing the grant row; names no app"),
"route POST /api/cli/accounts/{account}/platform/revoke": claimNonApp("operator revokes an account's platform grant, ending its generation and its platform credentials; names no app"),
+ "route POST /api/cli/platform/{account}/customers": claimNonApp("a platform creates a customer account: its pending mint, its manifest, and its account and plan rows; names no app"),
"route POST /api/cli/billing/house": claimNonApp("operator marks or clears an account's house flag, the account whose checkout carries the house coupon, writing the flag row; names no app"),
"route POST /api/cli/billing/problems/{id}/close": claimNonApp("operator closes a billing problem with a note after a fresh provider read; names no app"),
"route POST /api/cli/accounts/{account}/store/decline": claimNonApp("operator declines an account's storage entitlement"),
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index fd868e009..8b3c79ae9 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -1212,6 +1212,30 @@ var claimNonAppProbes = map[string]claimProbe{
return ""
},
},
+ "route POST /api/cli/platform/{account}/customers": {
+ setup: func(t *testing.T, cx *claimCase) {
+ claimPlatformGranted(t, cx)
+ // The bucket knows the second account, so the mint takes the
+ // next free id rather than the platform's own.
+ if err := WriteAccountManifest(context.Background(), cx.srv.cfg.Releases, 2, claimSecondSqid, "second", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ },
+ do: claimAPIReply(http.MethodPost, "/api/cli/platform/"+claimSecondSqid+"/customers", `{"name":"census","ref":"census"}`),
+ status: http.StatusCreated,
+ body: []string{`"created":true`, `"ref":"census"`},
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ ctx := context.Background()
+ c, err := cx.st.LinkedCustomerByRef(ctx, claimSecondSqid, "census")
+ if err != nil || c == nil || c.Name != "census" {
+ return fmt.Sprintf("the second account has no census customer: %+v %v", c, err)
+ }
+ if p, err := cx.st.PendingPlatformMints(ctx, claimSecondSqid); err != nil || len(p) != 0 {
+ return fmt.Sprintf("the census create left pending mints %+v %v", p, err)
+ }
+ return ""
+ },
+ },
"route PUT /api/cli/system/managed-fleets": {
do: claimAPIReply(http.MethodPut, "/api/cli/system/managed-fleets", `{"enabled":false,"ceiling":3}`),
body: []string{`"ceiling":3`},
@@ -1600,6 +1624,18 @@ func claimGettingStartedProbe(action string, kv []string, mark gsMark, want bool
}
}
+// claimPlatformCustomer stages the second account as a platform with one
+// customer account, ref census, for the platform doors' read probes.
+func claimPlatformCustomer(t *testing.T, cx *claimCase) {
+ t.Helper()
+ claimPlatformGranted(t, cx)
+ if err := cx.st.CreateLinkedAccount(context.Background(), NewLinkedAccount{ID: 40, Sqid: claimCustomerSqid,
+ Name: "census", Platform: claimSecondSqid, Ref: "census", MintID: strings.Repeat("c0", 16),
+ By: claimFxOwner}, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+}
+
// claimPlatformGranted stages the second account with an active platform
// grant, for the grant door's read and revoke probes.
func claimPlatformGranted(t *testing.T, cx *claimCase) {
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index 1a85b9de0..2c644f484 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -367,6 +367,10 @@ var claimReadProbes = map[string]claimProbe{
"/api/cli/accounts/bab/plan", `"plan":"free"`),
"route GET /api/cli/accounts/{account}/platform": claimAPIRead(claimPlatformGranted,
"/api/cli/accounts/"+claimSecondSqid+"/platform", `"state":"active"`, `"max_customers":5`),
+ "route GET /api/cli/platform/{account}/customers": claimAPIRead(claimPlatformCustomer,
+ "/api/cli/platform/"+claimSecondSqid+"/customers", `"account":"`+claimCustomerSqid+`"`, `"ref":"census"`),
+ "route GET /api/cli/platform/{account}/customers/{customer}": claimAPIRead(claimPlatformCustomer,
+ "/api/cli/platform/"+claimSecondSqid+"/customers/"+claimCustomerSqid, `"account":"`+claimCustomerSqid+`"`),
"route GET /api/cli/billing/problems": claimAPIRead(claimBillingProblemWorld, "/api/cli/billing/problems", `"reason":"unrecognised"`),
"route GET /api/cli/billing/revenue": claimAPIRead(claimBillingWorld, "/api/cli/billing/revenue", `"accounts":`, `"arr":`),
"route GET /api/cli/billing/payments": claimAPIRead(claimBillingWorld, "/api/cli/billing/payments", `"available":`, `"test_mode":`),
diff --git a/internal/console/links_auth_test.go b/internal/console/links_auth_test.go
index a0cbaf0f8..aa602b3e8 100644
--- a/internal/console/links_auth_test.go
+++ b/internal/console/links_auth_test.go
@@ -486,6 +486,7 @@ var linkWalkFill = map[string]string{
"address": "paul@keymail.dev",
"box": "box1",
"code": "WXYZ-4823",
+ "customer": "bcd",
"decision": "approve",
"domain": "example.com",
"file...": "app.css",
diff --git a/internal/console/platform_copy.go b/internal/console/platform_copy.go
index d7de0c603..bb022aec4 100644
--- a/internal/console/platform_copy.go
+++ b/internal/console/platform_copy.go
@@ -19,7 +19,18 @@ var platformCopy = map[string]string{
"grant.not_platform": "this account isn’t a platform account",
"grant.failed": "could not save the grant. try again",
- "door.rate": "too many requests. wait a minute and try again",
+ "door.not_platform": "this account isn’t a platform account. an operator can make it one with carlos accounts platform",
+ "door.revoked": "this account’s platform access is turned off. ask the operator who granted it",
+ "door.not_owner": "only an owner of this account can manage its customer accounts",
+ "door.rate": "too many requests. wait a minute and try again",
+
+ "create.name": "an account name appears in URLs and --account: 1-63 characters of a-z, 0-9 and hyphen, no leading or trailing hyphen",
+ "create.ref": "a customer reference is 1 to 64 letters, digits, dots, colons, hyphens or underscores",
+ "create.plan": "this platform can put customer accounts on these plans: %s",
+ "create.no_catalog_plan": "this console has no plan catalog, so leave out the plan",
+ "create.cap": "this platform has %d customer accounts, the most its grant allows. ask the operator for more",
+ "create.rate": "too many customer accounts were created today. try again tomorrow, or ask the operator",
+ "create.failed": "could not create the customer account. try again",
"svc.platform_app": "a platform credential works for the whole platform account, so it takes no --app",
"svc.not_platform": "only a platform account can hold a platform credential. an operator grants that with carlos accounts platform",
@@ -27,4 +38,7 @@ var platformCopy = map[string]string{
"audit.grant": "made this a platform account: up to %d customer accounts, plans %s, new ones on %s. reason: %s",
"audit.grant_no_plans": "made this a platform account: up to %d customer accounts. reason: %s",
"audit.revoke": "turned off platform access, %d credentials stopped working. reason: %s",
+
+ "audit.customer_create": "created customer account %s (%s)",
+ "audit.customer_created_by": "created by platform account %s",
}
diff --git a/internal/console/platform_credentials_test.go b/internal/console/platform_credentials_test.go
index 6e26eaa9f..81045e9b6 100644
--- a/internal/console/platform_credentials_test.go
+++ b/internal/console/platform_credentials_test.go
@@ -3,6 +3,7 @@ package console
import (
"context"
"errors"
+ "fmt"
"net/http"
"slices"
"testing"
@@ -123,6 +124,10 @@ func TestServicesDoorMintsAPlatformCredentialOnlyOnAGrantedAccount(t *testing.T)
}
raw, _ := out["token"].(string)
wantPlatformPrincipal(t, fx.st, raw, acct, gen+1)
+ // The credential reaches the platform doors and nothing else.
+ if got := fmt.Sprint(out["doors"]); got != fmt.Sprint(platformDoorPatterns) {
+ t.Fatalf("mint doors %s, want exactly the platform doors %v", got, platformDoorPatterns)
+ }
var platformAccountID, platformGeneration int64
if err := fx.st.db.QueryRowContext(context.Background(), `SELECT platform_account_id, platform_generation
FROM cli_tokens WHERE token_hash = ?`, hashToken(raw)).Scan(&platformAccountID, &platformGeneration); err != nil {
@@ -284,12 +289,13 @@ func TestRevokedPlatformCredentialIsGoneFromManagement(t *testing.T) {
t.Fatalf("mint again = %d %v, want 201", status, out)
}
fresh, _ := out["token"].(string)
- // Until Task 8's customer list door exists, the new token's resolution
- // stands in for its GET /api/cli/platform/<p>/customers 200. Task 8
- // Step 5 puts the GET back (pre-flight C3).
wantPlatformPrincipal(t, fx.st, fresh, acct, gen+1)
- if status := probeStatus(t, fx, acct.Sqid, old); status != http.StatusUnauthorized {
- t.Fatalf("old token after the re-mint = %d, want 401", status)
+ customers := platformCustomersURL(fx.ts.URL, acct.Sqid)
+ if status, out := getJSON(t, customers, fresh); status != http.StatusOK {
+ t.Fatalf("new token at the customer list = %d %v, want 200", status, out)
+ }
+ if status, _ := getJSON(t, customers, old); status != http.StatusUnauthorized {
+ t.Fatalf("old token at the customer list = %d, want 401", status)
}
}
diff --git a/internal/console/platform_seams.go b/internal/console/platform_seams.go
new file mode 100644
index 000000000..5307fbeb6
--- /dev/null
+++ b/internal/console/platform_seams.go
@@ -0,0 +1,30 @@
+package console
+
+// platformSeams is the platform accounts plan's one addition to Server
+// (pre-flight C1): the platform lifecycle lock's table and the plan's test
+// seams, embedded in Server with a single line. Later tasks of the plan add
+// their seams here; nothing else of the plan becomes a Server field. Every
+// field's zero value is ready, so &Server{} literals in tests stay safe.
+//
+// The test seams are unexported func fields, nil in production, the
+// lapseBeforeConverge precedent (plangracepass.go).
+type platformSeams struct {
+ // platformLocks is the platform lifecycle lock's table
+ // (lockPlatformLifecycle, applocks.go), keyed by the platform's sqid.
+ platformLocks keyedLocks
+ // platformMintStep, when set (tests only), is called with "lock" just
+ // before customer create takes the platform lifecycle lock, "mint"
+ // before MintLinkedAccount and "finish" before CreateLinkedAccount
+ // (both in create and when a pending mint is finished). A non-nil error
+ // is treated as that step failing. A test may block in it to
+ // interleave.
+ platformMintStep func(step string) error
+}
+
+// platformStep runs the platformMintStep seam, if one is set.
+func (s *platformSeams) platformStep(step string) error {
+ if s.platformMintStep == nil {
+ return nil
+ }
+ return s.platformMintStep(step)
+}
diff --git a/internal/console/platform_store.go b/internal/console/platform_store.go
index 2c8c0fa6e..1d4f7d414 100644
--- a/internal/console/platform_store.go
+++ b/internal/console/platform_store.go
@@ -29,6 +29,7 @@ import (
"strings"
"time"
+ "github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/svcrole"
)
@@ -99,6 +100,11 @@ var (
// by an account. Mint ids are 128 random bits minted fresh for each
// create, so this is a caller's bug, never a customer's mistake.
errPlatformMintUsed = errors.New("console: that mint id is already in use")
+ // errLinkedIDTaken is CreateLinkedAccount refusing an account id this
+ // console already holds for another account (another sqid or another
+ // platform). The bucket allocated the id because it has no manifest for
+ // that account, so every retry of the same mint id lands on it again.
+ errLinkedIDTaken = errors.New("console: that account id belongs to another account")
)
// dbQuerier is the one method both *sql.DB (and the Store's sqlHandle) and
@@ -165,6 +171,9 @@ func (s *Store) migratePlatformAccounts() error {
`CREATE UNIQUE INDEX IF NOT EXISTS accounts_platform_ref ON accounts (platform, platform_ref)
WHERE platform_ref != '' AND deleted_at = 0;`,
`CREATE INDEX IF NOT EXISTS cli_tokens_platform ON cli_tokens (platform_account_id) WHERE platform_account_id != 0;`,
+ // Every platform door asks whether its platform has pending mints
+ // (platformGate): one indexed query when it has none.
+ `CREATE INDEX IF NOT EXISTS platform_pending_mints_platform ON platform_pending_mints (platform, created_at);`,
} {
if _, err := s.db.ExecContext(ctx, stmt); err != nil {
return err
@@ -467,6 +476,102 @@ func (s *Store) PendingPlatformMints(ctx context.Context, platformSqid string) (
return out, rows.Err()
}
+// DropPendingMint ends a pending mint that can never be finished, without
+// an account: its promise is withdrawn, so it stops holding its ref and its
+// platform's capacity. Only finishPlatformMint calls it, and only for a
+// mint whose id the bucket gave to an id this console holds for another
+// account (errLinkedIDTaken). Dropping an unknown mint is a no-op.
+func (s *Store) DropPendingMint(ctx context.Context, platformSqid, mintID string) error {
+ _, err := s.db.ExecContext(ctx, `DELETE FROM platform_pending_mints WHERE platform = ? AND mint_id = ?`,
+ platformSqid, mintID)
+ return err
+}
+
+// accountManifestRow is the console's row for an account id, deleted or
+// not, as the manifest that describes it: what ensureAccountManifest's
+// backfill writes, plus a tombstone's DeletedAt and the row's own link. ok
+// is false for an id with no row.
+func (s *Store) accountManifestRow(ctx context.Context, id int64) (m domains.AccountManifest, ok bool, err error) {
+ var created, deleted int64
+ err = s.db.QueryRowContext(ctx, `SELECT id, sqid, name, created_at, deleted_at, platform, platform_ref, platform_mint
+ FROM accounts WHERE id = ?`, id).Scan(&m.ID, &m.Sqid, &m.Name, &created, &deleted, &m.Platform, &m.PlatformRef, &m.PlatformMint)
+ if errors.Is(err, sql.ErrNoRows) {
+ return domains.AccountManifest{}, false, nil
+ }
+ if err != nil {
+ return domains.AccountManifest{}, false, err
+ }
+ m.CreatedAt = time.Unix(created, 0).UTC()
+ if deleted != 0 {
+ m.DeletedAt = time.Unix(deleted, 0).UTC()
+ }
+ return m, true, nil
+}
+
+// LinkedCustomerPlans returns every live customer's plan row and cap rows,
+// keyed by account id, with one query each, so a platform's customer list
+// never runs two queries per customer. Cap rows come in capOrder, as
+// CapStatesContext gives them; a customer with none has no entry.
+func (s *Store) LinkedCustomerPlans(ctx context.Context, platformSqid string) (map[int64]AccountPlanRow, map[int64][]capState, error) {
+ planRows := map[int64]AccountPlanRow{}
+ capRows := map[int64][]capState{}
+ if platformSqid == "" {
+ return planRows, capRows, nil
+ }
+ const customers = `SELECT id FROM accounts WHERE platform = ? AND platform != '' AND deleted_at = 0`
+ rows, err := s.db.QueryContext(ctx, `SELECT `+accountPlanColumns+`
+ FROM account_plans p JOIN accounts a ON a.id = p.account_id WHERE p.account_id IN (`+customers+`)`, platformSqid)
+ if err != nil {
+ return nil, nil, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ r, err := scanAccountPlan(rows)
+ if err != nil {
+ return nil, nil, err
+ }
+ planRows[r.AccountID] = *r
+ }
+ if err := rows.Err(); err != nil {
+ return nil, nil, err
+ }
+ rows.Close()
+
+ crows, err := s.db.QueryContext(ctx, `SELECT account_id, cap, period, level, used, cap_limit, first_over,
+ grace_ends, warned_at, reminded_at, notice_at, updated_at FROM plan_cap_state
+ WHERE account_id IN (`+customers+`)`, platformSqid)
+ if err != nil {
+ return nil, nil, err
+ }
+ defer crows.Close()
+ byAccount := map[int64]map[capID]capState{}
+ for crows.Next() {
+ var st capState
+ var first, grace, warned, reminded, notice, updated int64
+ if err := crows.Scan(&st.AccountID, &st.Cap, &st.Period, &st.Level, &st.Used, &st.Limit, &first, &grace,
+ &warned, &reminded, &notice, &updated); err != nil {
+ return nil, nil, err
+ }
+ st.FirstOver, st.GraceEnds, st.WarnedAt = timeOrZero(first), timeOrZero(grace), timeOrZero(warned)
+ st.RemindedAt, st.NoticeAt, st.UpdatedAt = timeOrZero(reminded), timeOrZero(notice), timeOrZero(updated)
+ if byAccount[st.AccountID] == nil {
+ byAccount[st.AccountID] = map[capID]capState{}
+ }
+ byAccount[st.AccountID][st.Cap] = st
+ }
+ if err := crows.Err(); err != nil {
+ return nil, nil, err
+ }
+ for id, byCap := range byAccount {
+ for _, c := range capOrder {
+ if st, ok := byCap[c]; ok {
+ capRows[id] = append(capRows[id], st)
+ }
+ }
+ }
+ return planRows, capRows, nil
+}
+
// CreateLinkedAccount FINISHES a pending mint, in one transaction (Astra
// r1-1). When materialization already made the row (a live account with
// this id, sqid and platform), the row is kept and a platform plan
@@ -476,7 +581,8 @@ func (s *Store) PendingPlatformMints(ctx context.Context, platformSqid string) (
// no-op. A finish over this customer's tombstone (materialized, then
// deleted) drops the pending mint and is ErrAccountGone: a pending mint
// always reaches an end state, and a deleted account is never brought back.
-// An id held by any other account is an error, and the pending mint is kept.
+// An id held by any other account is errLinkedIDTaken, and the pending mint
+// is kept: what ends it is the caller's (finishPlatformMint drops it).
//
// No membership: a customer account has no owner until one claims it. No
// launch sponsorship either: a customer's plan is its platform's (decision
@@ -503,7 +609,7 @@ func (s *Store) CreateLinkedAccount(ctx context.Context, a NewLinkedAccount, now
case err != nil:
return err
case sqid != a.Sqid || platform != a.Platform:
- return errors.New("console: that account id belongs to another account")
+ return errLinkedIDTaken
case deleted != 0:
// This customer was materialized and then deleted before the
// finish. The finish ends here: the promise is dropped (the delete
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index 715be8f3e..84d82dcbb 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -944,6 +944,17 @@ var routeDecls = []routeDecl{
{Pattern: "GET /api/cli/services/{account}", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIServiceList},
{Pattern: "POST /api/cli/services/{account}/{name}/rotate", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIServiceRotate},
{Pattern: "POST /api/cli/services/{account}/{name}/revoke", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIServiceRevoke},
+ // The platform doors (apiplatformcustomers.go, platform accounts spec
+ // §6.1): a platform account creates, lists and shows its customer
+ // accounts. Exactly(Platform): the platform credential is the only
+ // service credential that reaches them, and Admin is out on purpose (an
+ // administrator of an account is not its platform). A person reaches
+ // them too, and platformGate admits an owner only. The segment is
+ // {account}, not the spec's {platform}, so apiPrincipalAccount binds it
+ // unchanged (decision D1).
+ {Pattern: "POST /api/cli/platform/{account}/customers", Kind: kindCLI, Allow: svcrole.Exactly(svcrole.Platform), Handler: (*Server).handlePlatformCustomerCreate},
+ {Pattern: "GET /api/cli/platform/{account}/customers", Kind: kindCLI, Allow: svcrole.Exactly(svcrole.Platform), Handler: (*Server).handlePlatformCustomerList},
+ {Pattern: "GET /api/cli/platform/{account}/customers/{customer}", Kind: kindCLI, Allow: svcrole.Exactly(svcrole.Platform), Handler: (*Server).handlePlatformCustomerShow},
// Placement lives under the apps family, not fleets: its subject is an
// APP, and a target fleet name is only ever the request body's data.
{Pattern: "POST /api/cli/apps/{account}/{app}/place", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIPlace},
diff --git a/internal/console/server.go b/internal/console/server.go
index 9311c0548..0e34b8332 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1023,6 +1023,7 @@ type Config struct {
// Server is the console's http.Handler.
type Server struct {
+ platformSeams // platform accounts' lifecycle lock and test seams (platform_seams.go)
// mailCallerGaps holds caller-class sends not yet recorded (apisubmission.go).
mailCallerGaps mailCallerGapSet
// submissionSwitchHook, when set (tests only), is called by the email
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index b8e2727e4..f63aaca93 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -77,6 +77,8 @@ 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}/platform
+route GET /api/cli/platform/{account}/customers
+route GET /api/cli/platform/{account}/customers/{customer}
route GET /api/cli/accounts/{account}/subdomain
route GET /api/cli/apps
route GET /api/cli/apps/{account}/list
@@ -263,6 +265,7 @@ route POST /api/cli/accounts/{account}/domains/check
route POST /api/cli/accounts/{account}/domains/purchases
route POST /api/cli/accounts/{account}/plan
route POST /api/cli/accounts/{account}/platform/revoke
+route POST /api/cli/platform/{account}/customers
route POST /api/cli/accounts/{account}/store/apply
route POST /api/cli/accounts/{account}/store/approve
route POST /api/cli/accounts/{account}/store/decline