console: platforms rename and re-plan customers; guard platform deletion
PATCH /api/cli/platform/{account}/customers/{customer} renames a customer
(bucket manifest first, then the row, under the customer's account lock)
and moves it to a plan within the grant through the shared plan
transition, so a fall from a paid plan starts a lapse. A plan an operator
set (source operator or sponsored) is refused with update.operator_plan,
checked before any write and again under the lapse lock. Every refusal
comes before the first write; a name or plan the customer already has
writes nothing. applyAccountPlan's write moves into writePlanChange,
shared with applyPlatformPlan.
Platform accounts keep their customers: deletionRefused refuses a linked
account (D11, delete.linked, via the new linkedPlatform) and a platform
with live customers or pending mints (delete.platform_has_customers).
handleDeleteAccount takes the platform lifecycle lock right after the
typed-name check and holds it to the end, so no customer can appear
between the last check and the tombstone. Lock order lifecycle ->
account/plan -> billing: deleteAccountNow takes no account lock (Astra
r2-1, r3-2). lockAccount and holdBilling emit lock events for the order
tests; deleteNowEnter and deleteBeforeTombstone are platformSeams.
The claim census, its fixture and a probe cover the new door.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+1,297
−31
internal/console/apiplatformcustomers.go+184 −4internal/console/apiplatformcustomers_test.go+283 −1internal/console/applocks.go+22 −5internal/console/billinghold.go+9 −1internal/console/claim_invariant_fixtures_test.go+1 −0internal/console/claim_invariant_probes_nonapp_test.go+18 −0internal/console/ownership.go+57 −3internal/console/planlapse.go+25 −15internal/console/platform_copy.go+11 −0internal/console/platform_seams.go+9 −0internal/console/platformlinked.go+28 −0internal/console/platformlinked_test.go+646 −0internal/console/routedecls.go+3 −2internal/console/testdata/claim-routes.txt+1 −0
diff --git a/internal/console/apiplatformcustomers.go b/internal/console/apiplatformcustomers.go| index 2fb235c78..1fa5792b3 100644 |
| --- a/internal/console/apiplatformcustomers.go |
| +++ b/internal/console/apiplatformcustomers.go |
| @@ -1,7 +1,7 @@ |
| package console |
| // The platform doors (platform accounts spec §6.1): a platform account |
| -// creates, lists and shows the customer accounts it runs. |
| +// creates, lists, shows and updates 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 |
| @@ -31,12 +31,15 @@ import ( |
| "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. |
| +// Account-level audit actions for customer creation and update, with app |
| +// accountAuditSubject. A create writes one on the platform account's |
| +// history and one on the customer's; a rename or a plan change writes the |
| +// same row on both. |
| const ( |
| auditPlatformCustomerCreate = "platform-customer-create" |
| auditPlatformCustomerCreated = "platform-customer-created" |
| + auditPlatformCustomerRename = "platform-customer-rename" |
| + auditPlatformCustomerPlan = "platform-customer-plan" |
| ) |
| // maxPlatformRef is the longest customer reference (decision D5). |
| @@ -742,3 +745,180 @@ func (s *Server) finishPlatformMint(ctx context.Context, platform *Account, m Pe |
| fmt.Sprintf(platformCopy["audit.customer_created_by"], platform.Sqid)) |
| return cust, nil |
| } |
| + |
| +// ---- update ------------------------------------------------------------------- |
| + |
| +// errPlanSetByOperator is a platform's plan change refused because the |
| +// customer's plan row is an operator's (source operator or sponsored): |
| +// a platform cannot change a plan an operator set (decision D11). |
| +var errPlanSetByOperator = errors.New("console: an operator set this account's plan") |
| + |
| +type updatePlatformCustomerRequest struct { |
| + Name string `json:"name"` |
| + Plan string `json:"plan"` |
| + Reason string `json:"reason"` |
| +} |
| + |
| +// handlePlatformCustomerUpdate answers PATCH .../customers/{customer}: a |
| +// new name, a new plan within the grant, or both, and the customer's view. |
| +// Every refusal comes before the first write, so a refused update writes |
| +// nothing (Astra r1-4): the write budget (door.rate), the customer (the |
| +// stdlib 404), an empty change (update.empty), the name (create.name), the |
| +// plan (create.plan, or create.no_catalog_plan with no catalog), and an |
| +// operator's plan row (update.operator_plan). Then the rename, bucket |
| +// first, and the plan change through the plan transition. A store or |
| +// bucket failure is 502 update.failed (pre-flight C10). A name or plan the |
| +// customer already has is no change: nothing is written or audited for it. |
| +// |
| +// The gate finishes the platform's pending mints first, as on every door |
| +// but create; a held one is passed over (Task 8, ruling C). The update |
| +// takes no platform lifecycle lock. |
| +func (s *Server) handlePlatformCustomerUpdate(w http.ResponseWriter, r *http.Request) { |
| + c, ok := s.platformGateFor(w, r, "update.failed") |
| + if !ok { |
| + return |
| + } |
| + if !s.allowWrite(c.P, time.Now()) { |
| + jsonError(w, http.StatusTooManyRequests, platformCopy["door.rate"]) |
| + return |
| + } |
| + lc, cust, ok := s.platformCustomer(w, r, c) |
| + if !ok { |
| + return |
| + } |
| + var req updatePlatformCustomerRequest |
| + if !readJSONStrictLimit(w, r, &req, 8<<10) { |
| + return |
| + } |
| + if req.Name == "" && req.Plan == "" { |
| + jsonError(w, http.StatusBadRequest, platformCopy["update.empty"]) |
| + return |
| + } |
| + if req.Name != "" && !domains.ValidAccountName(req.Name) { |
| + jsonError(w, http.StatusBadRequest, platformCopy["create.name"]) |
| + return |
| + } |
| + ctx := r.Context() |
| + replan := false |
| + if req.Plan != "" { |
| + if _, refusal := s.platformCreatePlan(c.Grant, req.Plan); refusal != "" { |
| + jsonError(w, http.StatusBadRequest, refusal) |
| + return |
| + } |
| + row, err := s.store.AccountPlanContext(ctx, cust.ID) |
| + if err != nil { |
| + log.Printf("console: platform %s: update customer %s: read plan: %v", c.Platform.Sqid, cust.Sqid, err) |
| + s.platformDoorFailed(w, c) |
| + return |
| + } |
| + if planSetByOperator(row) { |
| + jsonError(w, http.StatusConflict, platformCopy["update.operator_plan"]) |
| + return |
| + } |
| + replan = !platformPlanIs(row, req.Plan) |
| + } |
| + rename := req.Name != "" && req.Name != lc.Name |
| + if rename && s.cfg.Releases == nil { |
| + log.Printf("console: platform %s: rename customer %s: no deployment bucket", c.Platform.Sqid, cust.Sqid) |
| + s.platformDoorFailed(w, c) |
| + return |
| + } |
| + |
| + if rename { |
| + if err := s.renamePlatformCustomer(ctx, cust, req.Name); err != nil { |
| + s.platformUpdateFailed(w, r, c, cust, "rename", err) |
| + return |
| + } |
| + detail := fmt.Sprintf(platformCopy["audit.customer_rename"], lc.Name, req.Name) |
| + s.audit(c.Platform, accountAuditSubject, c.Actor, auditPlatformCustomerRename, detail) |
| + s.audit(cust, accountAuditSubject, c.Actor, auditPlatformCustomerRename, detail) |
| + cust.Name = req.Name |
| + } |
| + if replan { |
| + reason := strings.TrimSpace(req.Reason) |
| + if reason == "" { |
| + reason = fmt.Sprintf("platform %s", c.Platform.Sqid) |
| + } |
| + if err := s.applyPlatformPlan(ctx, cust, req.Plan, reason, c.Actor, time.Now()); err != nil { |
| + s.platformUpdateFailed(w, r, c, cust, "plan", err) |
| + return |
| + } |
| + detail := fmt.Sprintf(platformCopy["audit.customer_plan"], cust.Name, req.Plan) |
| + s.audit(c.Platform, accountAuditSubject, c.Actor, auditPlatformCustomerPlan, detail) |
| + s.audit(cust, accountAuditSubject, c.Actor, auditPlatformCustomerPlan, detail) |
| + } |
| + |
| + updated, err := s.store.LinkedCustomer(ctx, c.Platform.Sqid, cust.Sqid) |
| + if err != nil || updated == nil { |
| + log.Printf("console: platform %s: updated customer %s but could not read it back: %v", c.Platform.Sqid, cust.Sqid, err) |
| + s.platformDoorFailed(w, c) |
| + return |
| + } |
| + v, err := s.customerView(ctx, *updated, 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) |
| +} |
| + |
| +// platformUpdateFailed answers a failed rename or plan change: the stdlib |
| +// 404 for a customer deleted meanwhile, 409 update.operator_plan for an |
| +// operator's row the transition found under its lock, else 502 |
| +// update.failed. |
| +func (s *Server) platformUpdateFailed(w http.ResponseWriter, r *http.Request, c platformCaller, cust *Account, what string, err error) { |
| + switch { |
| + case errors.Is(err, ErrAccountGone): |
| + http.NotFound(w, r) |
| + case errors.Is(err, errPlanSetByOperator): |
| + jsonError(w, http.StatusConflict, platformCopy["update.operator_plan"]) |
| + default: |
| + log.Printf("console: platform %s: update customer %s: %s: %v", c.Platform.Sqid, cust.Sqid, what, err) |
| + s.platformDoorFailed(w, c) |
| + } |
| +} |
| + |
| +// renamePlatformCustomer renames the customer in the bucket first, where |
| +// account identity lives, then its row, under the customer's account lock |
| +// so two renames cannot leave the manifest and the row disagreeing. The |
| +// lock is taken with no other held (applocks.go's order). |
| +func (s *Server) renamePlatformCustomer(ctx context.Context, cust *Account, name string) error { |
| + defer s.lockAccount(cust.Sqid)() |
| + if err := domains.RenameAccountManifest(ctx, s.cfg.Releases, cust.Sqid, name); err != nil { |
| + return err |
| + } |
| + return s.store.RenameAccount(ctx, cust.ID, name) |
| +} |
| + |
| +// planSetByOperator reports whether the plan row is an operator's: set by |
| +// the operator door, or sponsored. A platform never changes one. |
| +func planSetByOperator(row *AccountPlanRow) bool { |
| + return row != nil && (row.Source == PlanSourceOperator || planRowSponsored(row)) |
| +} |
| + |
| +// platformPlanIs reports whether the row is already plan, set by the |
| +// platform with no packs: writing it again would change nothing but the |
| +// revision, and drop a throttle the grace pass set. |
| +func platformPlanIs(row *AccountPlanRow, plan string) bool { |
| + return row != nil && row.Source == PlanSourcePlatform && row.Plan == plan && len(row.Packs) == 0 |
| +} |
| + |
| +// applyPlatformPlan is a platform's plan change for one of its customers, |
| +// through the transition every plan change shares (transitionAccountPlan), |
| +// so a fall from a paid plan starts a lapse and its grace as an owner's or |
| +// operator's change does. Under the lapse lock it refuses an old row that |
| +// is an operator's (errPlanSetByOperator), writes nothing when the row is |
| +// already this plan from the platform, and otherwise writes the plan with |
| +// source platform (writePlanChange, shared with applyAccountPlan). |
| +func (s *Server) applyPlatformPlan(ctx context.Context, cust *Account, plan, reason, by string, now time.Time) error { |
| + return s.transitionAccountPlan(ctx, cust, now, func(old *AccountPlanRow) (bool, error) { |
| + if planSetByOperator(old) { |
| + return false, errPlanSetByOperator |
| + } |
| + if platformPlanIs(old, plan) { |
| + return false, nil |
| + } |
| + return s.writePlanChange(cust, old, plan, nil, PlanSourcePlatform, nil, reason, by, now) |
| + }) |
| +} |
diff --git a/internal/console/apiplatformcustomers_test.go b/internal/console/apiplatformcustomers_test.go| index ad52064fd..a35b86501 100644 |
| --- a/internal/console/apiplatformcustomers_test.go |
| +++ b/internal/console/apiplatformcustomers_test.go |
| @@ -18,14 +18,16 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/plans" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/svcrole" |
| ) |
| -// platformDoorPatterns is every platform door Task 8 registers. |
| +// platformDoorPatterns is every platform door Tasks 8 and 9 register. |
| var platformDoorPatterns = []string{ |
| "GET /api/cli/platform/{account}/customers", |
| "GET /api/cli/platform/{account}/customers/{customer}", |
| + "PATCH /api/cli/platform/{account}/customers/{customer}", |
| "POST /api/cli/platform/{account}/customers", |
| } |
| @@ -1363,3 +1365,283 @@ func TestCustomerHeldRefRefusalFinishesNothingElse(t *testing.T) { |
| t.Fatalf("pending mints %+v, want A and B both still pending", p) |
| } |
| } |
| + |
| +// ---- customer update (Task 9) ------------------------------------------------ |
| + |
| +func platformCustomerURL(base, platform, customer string) string { |
| + return platformCustomersURL(base, platform) + "/" + customer |
| +} |
| + |
| +func updateCustomer(t *testing.T, base, platform, customer, bearer string, body any) (int, map[string]any, string) { |
| + t.Helper() |
| + status, out, raw, err := callJSON(http.MethodPatch, platformCustomerURL(base, platform, customer), bearer, body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return status, out, raw |
| +} |
| + |
| +// customerWorld is a console with the example catalog, platform account |
| +// 501 granted up to 5 customers on free and personal, its platform |
| +// credential, and one customer, shop with ref 4812, created through the |
| +// door on plan. |
| +func customerWorld(t *testing.T, plan string) (*consoleFixture, *Account, string, *Account) { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + p := planAccount(t, fx, 501) |
| + grantPlatformAccount(t, fx, p.Sqid, 5, "free", "personal") |
| + tok := platformToken(t, fx, p.ID, "cms") |
| + status, out, raw := createCustomer(t, fx.ts.URL, p.Sqid, tok, map[string]any{"name": "shop", "ref": "4812", "plan": plan}) |
| + if status != http.StatusCreated { |
| + t.Fatalf("create = %d %s", status, raw) |
| + } |
| + cust, err := fx.st.AccountBySqid(customerIn(t, out)["account"].(string)) |
| + if err != nil || cust == nil { |
| + t.Fatalf("customer row: %+v %v", cust, err) |
| + } |
| + return fx, p, tok, cust |
| +} |
| + |
| +// customerPlanRow is the account's plan row, which must exist. |
| +func customerPlanRow(t *testing.T, fx *consoleFixture, id int64) AccountPlanRow { |
| + t.Helper() |
| + row, err := fx.st.AccountPlan(id) |
| + if err != nil || row == nil { |
| + t.Fatalf("plan row of %d: %+v %v", id, row, err) |
| + } |
| + return *row |
| +} |
| + |
| +// wantCustomerNamed fails unless the customer's row and its manifest both |
| +// carry name. |
| +func wantCustomerNamed(t *testing.T, fx *consoleFixture, sqid, name string) { |
| + t.Helper() |
| + if a, err := fx.st.AccountBySqid(sqid); err != nil || a == nil || a.Name != name { |
| + t.Fatalf("customer row %+v %v, want name %q", a, err, name) |
| + } |
| + if m := readManifest(t, fx.rel, sqid); m.Name != name { |
| + t.Fatalf("customer manifest name %q, want %q", m.Name, name) |
| + } |
| +} |
| + |
| +func TestCustomerRenameRewritesTheManifest(t *testing.T) { |
| + fx, p, tok, cust := customerWorld(t, "free") |
| + before := readManifest(t, fx.rel, cust.Sqid) |
| + planBefore := customerPlanRow(t, fx, cust.ID) |
| + |
| + status, out, raw := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"name": "shop-2"}) |
| + if status != http.StatusOK || out["account"] != cust.Sqid || out["name"] != "shop-2" || out["ref"] != "4812" || |
| + out["plan"] != "free" { |
| + t.Fatalf("rename = %d %s, want the customer's view named shop-2", status, raw) |
| + } |
| + wantCustomerNamed(t, fx, cust.Sqid, "shop-2") |
| + m := readManifest(t, fx.rel, cust.Sqid) |
| + if m.ID != before.ID || m.Platform != p.Sqid || m.PlatformRef != "4812" || m.PlatformMint != before.PlatformMint || |
| + m.Owner != "" || !m.CreatedAt.Equal(before.CreatedAt) || m.Deleted() { |
| + t.Fatalf("manifest after the rename %+v, was %+v: only the name may change", m, before) |
| + } |
| + if after := customerPlanRow(t, fx, cust.ID); after.Revision != planBefore.Revision { |
| + t.Fatalf("a rename wrote the plan row: revision %d, was %d", after.Revision, planBefore.Revision) |
| + } |
| + actor := "service:" + p.Sqid + "/cms" |
| + want := fmt.Sprintf(platformCopy["audit.customer_rename"], "shop", "shop-2") |
| + for _, id := range []int64{p.ID, cust.ID} { |
| + if rows := platformAudit(t, fx, id, auditPlatformCustomerRename); len(rows) != 1 || rows[0].Detail != want || rows[0].Address != actor { |
| + t.Fatalf("rename audit on %d %+v, want one %q by %s", id, rows, want, actor) |
| + } |
| + } |
| + |
| + // The same name again changes nothing and records nothing. |
| + if status, _, raw := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"name": "shop-2"}); status != http.StatusOK { |
| + t.Fatalf("rename to the same name = %d %s", status, raw) |
| + } |
| + if rows := platformAudit(t, fx, p.ID, auditPlatformCustomerRename); len(rows) != 1 { |
| + t.Fatalf("rename audit %+v, want the first rename only", rows) |
| + } |
| +} |
| + |
| +// TestCustomerUpdateRefusalsWriteNothing: an empty body, a bad name, a plan |
| +// outside the grant and someone else's customer are all refused before |
| +// anything is written. |
| +func TestCustomerUpdateRefusalsWriteNothing(t *testing.T) { |
| + fx, p, tok, cust := customerWorld(t, "free") |
| + planBefore := customerPlanRow(t, fx, cust.ID) |
| + for _, c := range []struct { |
| + what string |
| + body map[string]any |
| + status int |
| + want string |
| + }{ |
| + {"an empty body", map[string]any{}, http.StatusBadRequest, platformCopy["update.empty"]}, |
| + {"a reason alone", map[string]any{"reason": "because"}, http.StatusBadRequest, platformCopy["update.empty"]}, |
| + {"a bad name", map[string]any{"name": "Shop Two"}, http.StatusBadRequest, platformCopy["create.name"]}, |
| + {"a bad name with a good plan", map[string]any{"name": "-shop", "plan": "personal"}, http.StatusBadRequest, platformCopy["create.name"]}, |
| + {"a plan outside the grant", map[string]any{"name": "shop-2", "plan": "team"}, http.StatusBadRequest, |
| + fmt.Sprintf(platformCopy["create.plan"], "free, personal")}, |
| + } { |
| + status, out, raw := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, c.body) |
| + if status != c.status || out["error"] != c.want { |
| + t.Errorf("%s = %d %s, want %d %q", c.what, status, raw, c.status, c.want) |
| + } |
| + } |
| + |
| + // Another platform's customer, and an account that is no customer, are |
| + // the stdlib 404. |
| + other := planAccount(t, fx, 502) |
| + grantPlatformAccount(t, fx, other.Sqid, 5, "free") |
| + otherTok := platformToken(t, fx, other.ID, "cms") |
| + status, out, raw := createCustomer(t, fx.ts.URL, other.Sqid, otherTok, map[string]any{"name": "cafe"}) |
| + if status != http.StatusCreated { |
| + t.Fatalf("other platform's create = %d %s", status, raw) |
| + } |
| + otherCust := customerIn(t, out)["account"].(string) |
| + for _, sqid := range []string{otherCust, other.Sqid, "zzzz"} { |
| + if status, _, raw := updateCustomer(t, fx.ts.URL, p.Sqid, sqid, tok, map[string]any{"name": "taken"}); status != http.StatusNotFound || raw != "404 page not found\n" { |
| + t.Errorf("update of %s through %s = %d %q, want the stdlib 404", sqid, p.Sqid, status, raw) |
| + } |
| + } |
| + |
| + wantCustomerNamed(t, fx, cust.Sqid, "shop") |
| + wantCustomerNamed(t, fx, otherCust, "cafe") |
| + if after := customerPlanRow(t, fx, cust.ID); after.Revision != planBefore.Revision || after.Plan != "free" { |
| + t.Fatalf("plan row %+v, was %+v: refusals write nothing", after, planBefore) |
| + } |
| + for _, action := range []string{auditPlatformCustomerRename, auditPlatformCustomerPlan} { |
| + if rows := platformAudit(t, fx, p.ID, action); len(rows) != 0 { |
| + t.Fatalf("%s audit %+v after refusals, want none", action, rows) |
| + } |
| + } |
| +} |
| + |
| +func TestCustomerPlanChangeGoesThroughTheTransition(t *testing.T) { |
| + fx, p, tok, cust := customerWorld(t, "personal") |
| + // More running things than free covers, so the lapse outlives the |
| + // transition's own re-converge (as TestApplyAccountPlanMarksALapse). |
| + now := time.Now() |
| + for i, app := range []string{"a", "b", "c", "d"} { |
| + lapseApp_(t, fx, cust, app, now.Add(time.Duration(i-10)*time.Hour)) |
| + } |
| + status, out, raw := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"plan": "free", "reason": "downgrade 4812"}) |
| + if status != http.StatusOK || out["plan"] != "free" || out["plan_source"] != PlanSourcePlatform || out["name"] != "shop" { |
| + t.Fatalf("plan change = %d %s", status, raw) |
| + } |
| + actor := "service:" + p.Sqid + "/cms" |
| + row := customerPlanRow(t, fx, cust.ID) |
| + if row.Plan != "free" || row.Source != PlanSourcePlatform || row.Reason != "downgrade 4812" || row.UpdatedBy != actor { |
| + t.Fatalf("plan row %+v, want free from the platform with its reason", row) |
| + } |
| + if row.LapseSince.IsZero() { |
| + t.Fatalf("personal -> free over the free caps left lapse_since unset: %+v", row) |
| + } |
| + want := fmt.Sprintf(platformCopy["audit.customer_plan"], "shop", "free") |
| + for _, id := range []int64{p.ID, cust.ID} { |
| + if rows := platformAudit(t, fx, id, auditPlatformCustomerPlan); len(rows) != 1 || rows[0].Detail != want || rows[0].Address != actor { |
| + t.Fatalf("plan audit on %d %+v, want one %q by %s", id, rows, want, actor) |
| + } |
| + } |
| + |
| + // The same plan again writes nothing: no revision bump (which would |
| + // drop a throttle the grace pass set) and no audit. |
| + if status, _, raw := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"plan": "free"}); status != http.StatusOK { |
| + t.Fatalf("same plan again = %d %s", status, raw) |
| + } |
| + if again := customerPlanRow(t, fx, cust.ID); again.Revision != row.Revision { |
| + t.Fatalf("the same plan again bumped the revision %d -> %d", row.Revision, again.Revision) |
| + } |
| + if rows := platformAudit(t, fx, p.ID, auditPlatformCustomerPlan); len(rows) != 1 { |
| + t.Fatalf("plan audit %+v, want the first change only", rows) |
| + } |
| + |
| + // With no reason the platform is named; paying again ends the lapse in |
| + // the same call. |
| + if status, _, raw := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"plan": "personal"}); status != http.StatusOK { |
| + t.Fatalf("back to personal = %d %s", status, raw) |
| + } |
| + if row := customerPlanRow(t, fx, cust.ID); row.Plan != "personal" || row.Reason != "platform "+p.Sqid || !row.LapseSince.IsZero() { |
| + t.Fatalf("plan row %+v, want personal for reason %q and the lapse ended", row, "platform "+p.Sqid) |
| + } |
| +} |
| + |
| +func TestCustomerPlanChangeStaysInsideTheGrant(t *testing.T) { |
| + fx, p, tok, cust := customerWorld(t, "free") |
| + // The operator narrows the grant to free. |
| + if err := fx.st.PutPlatformGrant(context.Background(), PlatformGrant{AccountID: p.ID, MaxCustomers: 5, |
| + Plans: []string{"free"}, DefaultPlan: "free", Reason: "r", GrantedBy: "ops@keymail.dev"}, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := customerPlanRow(t, fx, cust.ID) |
| + status, out, raw := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"plan": "personal"}) |
| + if want := fmt.Sprintf(platformCopy["create.plan"], "free"); status != http.StatusBadRequest || out["error"] != want { |
| + t.Fatalf("plan dropped from the grant = %d %s, want 400 %q", status, raw, want) |
| + } |
| + if after := customerPlanRow(t, fx, cust.ID); after.Plan != "free" || after.Revision != before.Revision { |
| + t.Fatalf("plan row %+v, was %+v", after, before) |
| + } |
| +} |
| + |
| +func TestCustomerPlanChangeRefusesOperatorRows(t *testing.T) { |
| + fx, p, tok, cust := customerWorld(t, "free") |
| + ctx := context.Background() |
| + if err := fx.srv.applyAccountPlan(ctx, cust, "personal", nil, PlanSourceOperator, nil, "comp", "ops@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := customerPlanRow(t, fx, cust.ID) |
| + status, out, _ := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"name": "shop-2", "plan": "free"}) |
| + wantPlatformError(t, "plan change over an operator row", status, out, http.StatusConflict, "update.operator_plan") |
| + if after := customerPlanRow(t, fx, cust.ID); after.Plan != "personal" || after.Source != PlanSourceOperator || after.Revision != before.Revision { |
| + t.Fatalf("plan row %+v, was %+v: the operator's row is kept", after, before) |
| + } |
| + // The refusal wrote nothing: not even the rename that came with it. |
| + wantCustomerNamed(t, fx, cust.Sqid, "shop") |
| + for _, action := range []string{auditPlatformCustomerRename, auditPlatformCustomerPlan} { |
| + if rows := platformAudit(t, fx, p.ID, action); len(rows) != 0 { |
| + t.Fatalf("%s audit %+v after the refusal, want none", action, rows) |
| + } |
| + } |
| + |
| + // A sponsored row is the operator's too. |
| + if err := fx.srv.applyAccountPlan(ctx, cust, "free", nil, PlanSourceSponsored, &plans.Limits{RunningThings: 9}, |
| + "launch", "ops@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, out, _ = updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"plan": "personal"}) |
| + wantPlatformError(t, "plan change over a sponsored row", status, out, http.StatusConflict, "update.operator_plan") |
| + |
| + // The write itself refuses under the lapse lock, whatever the door |
| + // read before it. |
| + if err := fx.srv.applyPlatformPlan(ctx, cust, "personal", "r", "service:"+p.Sqid+"/cms", time.Now()); !errors.Is(err, errPlanSetByOperator) { |
| + t.Fatalf("applyPlatformPlan over a sponsored row = %v, want errPlanSetByOperator", err) |
| + } |
| + |
| + // The name is still the platform's to change. |
| + if status, _, raw := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"name": "shop-2"}); status != http.StatusOK { |
| + t.Fatalf("rename beside an operator's plan = %d %s", status, raw) |
| + } |
| + wantCustomerNamed(t, fx, cust.Sqid, "shop-2") |
| +} |
| + |
| +// TestCustomerUpdateGoesOnPastAHeldPromise is Task 8's carry-forward |
| +// (ruling C): a promise held because a live customer took its ref fails |
| +// only a create for that ref. The update door's gate passes over it, and |
| +// the promise stays. |
| +func TestCustomerUpdateGoesOnPastAHeldPromise(t *testing.T) { |
| + fx, p, tok, cust := customerWorld(t, "free") |
| + ctx := context.Background() |
| + if err := fx.st.ReservePlatformMint(ctx, PendingMint{MintID: strings.Repeat("ab", 16), Platform: p.Sqid, |
| + Ref: "4900", Name: "held", By: "service:" + p.Sqid + "/cms", CreatedAt: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + holder := testAccountID() |
| + if _, err := fx.st.EnsureLinkedAccount(holder, domains.Sqid(holder), "holder", p.Sqid, "4900", |
| + strings.Repeat("cd", 16), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, out, raw := updateCustomer(t, fx.ts.URL, p.Sqid, cust.Sqid, tok, map[string]any{"name": "shop-2", "plan": "personal"}) |
| + if status != http.StatusOK || out["name"] != "shop-2" || out["plan"] != "personal" { |
| + t.Fatalf("update beside a held promise = %d %s, want 200", status, raw) |
| + } |
| + if pm := pendingMints(t, fx.st, p.Sqid); len(pm) != 1 || pm[0].Ref != "4900" { |
| + t.Fatalf("pending mints %+v, want the held 4900 promise kept", pm) |
| + } |
| +} |
diff --git a/internal/console/applocks.go b/internal/console/applocks.go| index 84936dc0b..976f06f41 100644 |
| --- a/internal/console/applocks.go |
| +++ b/internal/console/applocks.go |
| @@ -57,8 +57,20 @@ func (l *keyedLocks) lock(key string) func() { |
| // restoring one, which is what makes the cap exact (spec §3, §6). |
| // |
| // LOCK ORDER: account before app, never the other way round. Only |
| -// /new-temporary and restoreApp take this lock. |
| -func (s *Server) lockAccount(sqid string) func() { return s.acctLocks.lock(sqid) } |
| +// /new-temporary and restoreApp take this lock. It sits between the |
| +// platform lifecycle lock and the billing hold (lockPlatformLifecycle). |
| +// |
| +// It emits lockEvent("account", sqid, ...) like lockApp, so a test can |
| +// watch the order (platform accounts plan, Task 9). |
| +func (s *Server) lockAccount(sqid string) func() { |
| + lockEvent("account", sqid, lockWaiting) |
| + unlock := s.acctLocks.lock(sqid) |
| + lockEvent("account", sqid, lockHeld) |
| + return func() { |
| + lockEvent("account", sqid, lockReleased) |
| + unlock() |
| + } |
| +} |
| // lockApp is the per-app mutex every lifecycle transition takes: keep, ttl, |
| // restore, trash, the purge door and each step of the expiry pass (spec §5). |
| @@ -84,9 +96,14 @@ func (s *Server) lockApp(sqid, app string) func() { |
| // 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. |
| +// LOCK ORDER (Astra r2-1): platform lifecycle, then account/plan |
| +// (lockAccount, planLock), then the billing hold (holdBilling). Never take |
| +// a lock earlier in this list while holding a later one. Deletion takes |
| +// lifecycle, then billing (retireForDeletion), and no account/plan lock: |
| +// deleteAccountNow and its callees take none. A domain purchase |
| +// (startDomainPurchase) takes account/plan, then billing, and never |
| +// lifecycle. Customer creation takes lifecycle only. |
| +// TestLockOrderLifecycleAccountBilling watches it. |
| func (s *Server) lockPlatformLifecycle(sqid string) func() { |
| lockEvent("platform", sqid, lockWaiting) |
| unlock := s.platformLocks.lock(sqid) |
diff --git a/internal/console/billinghold.go b/internal/console/billinghold.go| index b4498f99b..2fa3eed99 100644 |
| --- a/internal/console/billinghold.go |
| +++ b/internal/console/billinghold.go |
| @@ -82,7 +82,15 @@ func (s *Server) holdBilling(acct *Account) (billingHold, func(), error) { |
| if s.store.planExempt(acct.ID) { |
| return billingHold{}, func() {}, errBillingExempt |
| } |
| - release := s.billing.locks.lock(acct.Sqid) |
| + // The lock-order events (lockEvent, lifetimes.go): the hold is last in |
| + // the order platform lifecycle, account/plan, billing (applocks.go). |
| + lockEvent("billing", acct.Sqid, lockWaiting) |
| + unlock := s.billing.locks.lock(acct.Sqid) |
| + lockEvent("billing", acct.Sqid, lockHeld) |
| + release := func() { |
| + lockEvent("billing", acct.Sqid, lockReleased) |
| + unlock() |
| + } |
| return billingHold{sqid: acct.Sqid}, release, nil |
| } |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 0b0a57f94..5a43aabfb 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1556,6 +1556,7 @@ var claimFixtures = map[string]claimFixture{ |
| "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 PATCH /api/cli/platform/{account}/customers/{customer}": claimNonApp("a platform renames a customer account or changes its plan: its manifest, its account row and its plan row; 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 8b3c79ae9..63df83384 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -1236,6 +1236,24 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| + "route PATCH /api/cli/platform/{account}/customers/{customer}": { |
| + setup: func(t *testing.T, cx *claimCase) { |
| + claimPlatformCustomer(t, cx) |
| + // The customer's manifest, which a rename rewrites first. |
| + if err := WriteAccountManifest(context.Background(), cx.srv.cfg.Releases, 40, claimCustomerSqid, "census", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + do: claimAPIReply(http.MethodPatch, "/api/cli/platform/"+claimSecondSqid+"/customers/"+claimCustomerSqid, `{"name":"census-2"}`), |
| + body: []string{`"name":"census-2"`}, |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + c, err := cx.st.LinkedCustomer(context.Background(), claimSecondSqid, claimCustomerSqid) |
| + if err != nil || c == nil || c.Name != "census-2" { |
| + return fmt.Sprintf("the census customer was not renamed: %+v %v", c, 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`}, |
diff --git a/internal/console/ownership.go b/internal/console/ownership.go| index 614dadff9..c09f0ed23 100644 |
| --- a/internal/console/ownership.go |
| +++ b/internal/console/ownership.go |
| @@ -125,7 +125,23 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther) |
| return |
| } |
| + // The platform lifecycle lock (Astra r1-3, r2-1), for every account, |
| + // held to the end of the request: on both paths below the re-run of |
| + // deletionRefused, the tombstone and DeleteAccount happen while |
| + // customer creation (which takes the same lock) cannot run, so no |
| + // customer, pending or live, appears between the last check and the |
| + // tombstone. A create that was waiting re-reads the platform afterwards |
| + // and finds it gone. Keyed by the account being deleted, so unrelated |
| + // deletions never contend. |
| + defer s.lockPlatformLifecycle(acct.Sqid)() |
| if s.billing != nil { |
| + // LOCK ORDER (applocks.go): platform lifecycle, then account/plan, |
| + // then the billing hold. This branch takes lifecycle (above), then |
| + // the billing hold (retireForDeletion), and no account/plan lock: |
| + // deleteAccountNow and its callees take none, so a domain purchase |
| + // holding the account lock and waiting on billing cannot deadlock |
| + // with it (Astra r3-2). |
| + // |
| // Billing's retirement gate (plans 6b) stands in for the step-up |
| // gate: it runs before the sign-in is asked for, so a refusal never |
| // costs one, and again on the replay. On success the billing hold is |
| @@ -152,18 +168,46 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) { |
| s.deleteAccountNow(w, r, addr, acct) |
| } |
| -// deletionRefused re-checks both refusals that DeleteAccount enforces, before |
| +// deletionRefused re-checks the refusals that DeleteAccount enforces, before |
| // the bucket is touched, and answers whether it refused (the response is |
| // written). They are cheap, and getting them in the wrong order is |
| // expensive: tombstoning an account the store then refuses to delete would |
| // leave a live account marked retired, which the next reconcile pass would |
| // act on by dropping its registry row. |
| +// |
| +// A linked account is refused (decision D11): until slice 2's leave, its |
| +// end is its platform's door. A platform account with customers, live or |
| +// promised (LinkedCustomerCount counts pending mints), is refused too; the |
| +// caller holds the platform lifecycle lock, so none can appear after this |
| +// check. |
| func (s *Server) deletionRefused(w http.ResponseWriter, r *http.Request, acct *Account) bool { |
| - if acct.ID == OpsAccountID { |
| - s.setFlash(w, "err", deletionAdvice(errOpsAccountUndeletable)) |
| + refuse := func(msg string) bool { |
| + s.setFlash(w, "err", msg) |
| http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther) |
| return true |
| } |
| + if acct.ID == OpsAccountID { |
| + return refuse(deletionAdvice(errOpsAccountUndeletable)) |
| + } |
| + ctx := r.Context() |
| + platform, err := s.linkedPlatform(ctx, acct) |
| + if err != nil { |
| + log.Printf("console: delete %s: read its platform link: %v", acct.Sqid, err) |
| + return refuse(deletionAdvice(err)) |
| + } |
| + if platform != nil { |
| + name := platform.Name |
| + if name == "" { |
| + name = platform.Sqid // a platform this console has no live row for |
| + } |
| + return refuse(fmt.Sprintf(platformCopy["delete.linked"], name)) |
| + } |
| + if n, err := s.store.LinkedCustomerCount(ctx, acct.Sqid); err != nil { |
| + log.Printf("console: delete %s: count customer accounts: %v", acct.Sqid, err) |
| + return refuse(deletionAdvice(err)) |
| + } else if n > 0 { |
| + return refuse(fmt.Sprintf(platformCopy["delete.platform_has_customers"], n)) |
| + } |
| if n, err := s.store.AppCount(acct.ID); err != nil || n > 0 { |
| if err != nil { |
| log.Printf("console: count apps for %s: %v", acct.Sqid, err) |
| @@ -180,10 +224,20 @@ func (s *Server) deletionRefused(w http.ResponseWriter, r *http.Request, acct *A |
| // deleteAccountNow is the deletion itself, after every gate: the refusals |
| // again, the bucket's tombstone, then the rows. It answers whether the |
| // account was deleted; either way the response is written. |
| +// |
| +// It takes no lock: its caller holds the platform lifecycle lock and, with |
| +// billing on, the billing hold, and an account/plan lock taken here would |
| +// invert the order (applocks.go; Astra r3-2). |
| func (s *Server) deleteAccountNow(w http.ResponseWriter, r *http.Request, addr string, acct *Account) bool { |
| + if s.deleteNowEnter != nil { |
| + s.deleteNowEnter() |
| + } |
| if s.deletionRefused(w, r, acct) { |
| return false |
| } |
| + if s.deleteBeforeTombstone != nil { |
| + s.deleteBeforeTombstone() |
| + } |
| // The bucket first, and the deletion is abandoned if it will not take. |
| // |
| // This console's rows are not where account identity lives — every console |
diff --git a/internal/console/planlapse.go b/internal/console/planlapse.go| index ead828131..85b634865 100644 |
| --- a/internal/console/planlapse.go |
| +++ b/internal/console/planlapse.go |
| @@ -81,25 +81,35 @@ func paidFall(cat *plans.Catalog, oldPlan string, oldPacks map[string]int, plan |
| func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan string, packs map[string]int, |
| source string, sponsored *plans.Limits, reason, by string, now time.Time) error { |
| return s.transitionAccountPlan(ctx, acct, now, func(old *AccountPlanRow) (bool, error) { |
| - // The fall is judged before the write, while the old row is the |
| - // one the store holds. |
| - fell := s.lapseStarted(old, plan, packs, sponsored) |
| - if _, err := s.store.SetAccountPlan(acct.ID, plan, packs, source, sponsored, reason, by, now); err != nil { |
| - return false, err |
| + return s.writePlanChange(acct, old, plan, packs, source, sponsored, reason, by, now) |
| + }) |
| +} |
| + |
| +// writePlanChange is a plan change's write inside transitionAccountPlan, |
| +// shared by the operator's (applyAccountPlan) and a platform's |
| +// (applyPlatformPlan): it writes the plan and, when the change is a fall |
| +// from a paid assignment, marks the lapse and restarts the lapse caps' |
| +// grace. It reports whether it wrote the plan row. |
| +func (s *Server) writePlanChange(acct *Account, old *AccountPlanRow, plan string, packs map[string]int, |
| + source string, sponsored *plans.Limits, reason, by string, now time.Time) (bool, error) { |
| + // The fall is judged before the write, while the old row is the one the |
| + // store holds. |
| + fell := s.lapseStarted(old, plan, packs, sponsored) |
| + if _, err := s.store.SetAccountPlan(acct.ID, plan, packs, source, sponsored, reason, by, now); err != nil { |
| + return false, err |
| + } |
| + if fell { |
| + if err := s.store.MarkLapse(acct.ID, now); err != nil { |
| + return true, err |
| } |
| - if fell { |
| - if err := s.store.MarkLapse(acct.ID, now); err != nil { |
| + // Each fall gets its own grace: the lapse caps' clocks start afresh. |
| + for _, c := range lapseCaps { |
| + if err := s.store.DeleteCapState(acct.ID, c); err != nil { |
| return true, err |
| } |
| - // Each fall gets its own grace: the lapse caps' clocks start afresh. |
| - for _, c := range lapseCaps { |
| - if err := s.store.DeleteCapState(acct.ID, c); err != nil { |
| - return true, err |
| - } |
| - } |
| } |
| - return true, nil |
| - }) |
| + } |
| + return true, nil |
| } |
| // applyBillingPlan is billing's plan change (plans 6a, Astra finding 5), |
diff --git a/internal/console/platform_copy.go b/internal/console/platform_copy.go| index bb022aec4..e08abce7a 100644 |
| --- a/internal/console/platform_copy.go |
| +++ b/internal/console/platform_copy.go |
| @@ -32,6 +32,10 @@ var platformCopy = map[string]string{ |
| "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", |
| + "update.empty": "nothing to change. pass a new name, a new plan, or both", |
| + "update.operator_plan": "an operator set this account’s plan. ask them to change it", |
| + "update.failed": "could not change 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", |
| @@ -41,4 +45,11 @@ var platformCopy = map[string]string{ |
| "audit.customer_create": "created customer account %s (%s)", |
| "audit.customer_created_by": "created by platform account %s", |
| + "audit.customer_rename": "renamed customer account %s to %s", |
| + "audit.customer_plan": "moved customer account %s to the %s plan", |
| + |
| + // Browser flashes on the account's Delete account (ownership.go), |
| + // sentence case as the rest of the browser copy is. |
| + "delete.platform_has_customers": "This account runs %d customer accounts, so it can’t be deleted.", |
| + "delete.linked": "This account is run by %s. Ask them to delete it.", |
| } |
diff --git a/internal/console/platform_seams.go b/internal/console/platform_seams.go| index 5307fbeb6..9226bbcc9 100644 |
| --- a/internal/console/platform_seams.go |
| +++ b/internal/console/platform_seams.go |
| @@ -19,6 +19,15 @@ type platformSeams struct { |
| // is treated as that step failing. A test may block in it to |
| // interleave. |
| platformMintStep func(step string) error |
| + // deleteNowEnter, when set (tests only), is the first statement of |
| + // deleteAccountNow, before its re-run of deletionRefused: the deletion |
| + // holds the platform lifecycle lock and, with billing on, the billing |
| + // hold, and nothing else (Astra r3-2). |
| + deleteNowEnter func() |
| + // deleteBeforeTombstone, when set (tests only), is called after |
| + // deleteAccountNow's re-run of deletionRefused passed, before the |
| + // bucket's tombstone, under the same locks. |
| + deleteBeforeTombstone func() |
| } |
| // platformStep runs the platformMintStep seam, if one is set. |
diff --git a/internal/console/platformlinked.go b/internal/console/platformlinked.go| new file mode 100644 |
| index 000000000..24283d27c |
| --- /dev/null |
| +++ b/internal/console/platformlinked.go |
| @@ -0,0 +1,28 @@ |
| +package console |
| + |
| +// Linked accounts (platform accounts spec §8): a customer account is run by |
| +// the platform account it is linked to, and the console treats it |
| +// differently where that matters. Until slice 2's leave, a linked account's |
| +// end is its platform's door, never a person's Delete account (decision |
| +// D11). |
| + |
| +import "context" |
| + |
| +// linkedPlatform is the platform account that runs acct, or nil when acct |
| +// is not linked. A link naming a platform this console has no live row for |
| +// is still a link, and every rule for linked accounts still holds: it |
| +// answers an Account carrying only the platform's sqid (ID 0, Name ""). |
| +func (s *Server) linkedPlatform(ctx context.Context, acct *Account) (*Account, error) { |
| + sqid, _, err := s.store.AccountPlatform(ctx, acct.ID) |
| + if err != nil || sqid == "" { |
| + return nil, err |
| + } |
| + platform, err := s.store.AccountBySqid(sqid) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if platform == nil { |
| + return &Account{Sqid: sqid}, nil |
| + } |
| + return platform, nil |
| +} |
diff --git a/internal/console/platformlinked_test.go b/internal/console/platformlinked_test.go| new file mode 100644 |
| index 000000000..161d8c6e9 |
| --- /dev/null |
| +++ b/internal/console/platformlinked_test.go |
| @@ -0,0 +1,646 @@ |
| +package console |
| + |
| +// Platform accounts keep their customers (platform accounts plan, Task 9): |
| +// a platform account is never deleted while it has a live customer or a |
| +// pending mint, a person cannot delete a linked account in the browser |
| +// (decision D11), and deletion and customer creation are serialized by the |
| +// platform lifecycle lock in the order lifecycle -> account/plan -> billing |
| +// hold (Astra r1-3, r2-1, r3-2). |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domainreg" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registrar" |
| + "github.com/carlosframework/platform/internal/registrar/registrartest" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| + "github.com/carlosframework/platform/internal/zonehost/zonehosttest" |
| +) |
| + |
| +// ---- fixtures ----------------------------------------------------------------- |
| + |
| +// lockEv is one lifetimeLockHook event. |
| +type lockEv struct{ kind, key, event string } |
| + |
| +// recordLocks installs lifetimeLockHook for the test, sending every event |
| +// whose key is one of keys (all of them when keys is empty) to the returned |
| +// channel. A full channel fails the test rather than blocking a lock. |
| +func recordLocks(t *testing.T, keys ...string) <-chan lockEv { |
| + t.Helper() |
| + ch := make(chan lockEv, 4096) |
| + var dropped sync.Once |
| + h := func(kind, key, event string) { |
| + if len(keys) > 0 && !slices.Contains(keys, key) { |
| + return |
| + } |
| + select { |
| + case ch <- lockEv{kind, key, event}: |
| + default: |
| + dropped.Do(func() { t.Errorf("lock event channel full: %s %s %s dropped", kind, key, event) }) |
| + } |
| + } |
| + lifetimeLockHook.Store(&h) |
| + t.Cleanup(func() { lifetimeLockHook.Store(nil) }) |
| + return ch |
| +} |
| + |
| +// drainLocks discards every event already recorded. |
| +func drainLocks(ch <-chan lockEv) { |
| + for { |
| + select { |
| + case <-ch: |
| + default: |
| + return |
| + } |
| + } |
| +} |
| + |
| +// waitLock reads events until want arrives, failing at the guard. |
| +func waitLock(t *testing.T, ch <-chan lockEv, guard <-chan time.Time, want lockEv, what string) { |
| + t.Helper() |
| + for { |
| + select { |
| + case ev := <-ch: |
| + if ev == want { |
| + return |
| + } |
| + case <-guard: |
| + t.Fatalf("guard timer: %s never came (%v)", what, want) |
| + } |
| + } |
| +} |
| + |
| +// waitOrGuard waits for ch to close or yield, failing at the guard. |
| +func waitOrGuard[T any](t *testing.T, ch <-chan T, guard <-chan time.Time, what string) T { |
| + t.Helper() |
| + select { |
| + case v := <-ch: |
| + return v |
| + case <-guard: |
| + t.Fatalf("guard timer: %s", what) |
| + } |
| + var zero T |
| + return zero |
| +} |
| + |
| +// seamGate is a test seam that blocks its first caller until released. |
| +// It opens itself when the test ends, so a failing test never leaves a |
| +// request blocked in it (the fixture's server close would wait on it). |
| +type seamGate struct { |
| + once, opened sync.Once |
| + entered chan struct{} |
| + release chan struct{} |
| +} |
| + |
| +func newGate(t *testing.T) *seamGate { |
| + g := &seamGate{entered: make(chan struct{}), release: make(chan struct{})} |
| + t.Cleanup(g.open) |
| + return g |
| +} |
| + |
| +// open releases the blocked caller, once. |
| +func (g *seamGate) open() { g.opened.Do(func() { close(g.release) }) } |
| + |
| +func (g *seamGate) block() { |
| + g.once.Do(func() { |
| + close(g.entered) |
| + <-g.release |
| + }) |
| +} |
| + |
| +// freshOwner signs addr in through a browser and records a fresh sign-in |
| +// proof for the session, so a gated POST runs in one request. It returns |
| +// the browser and its CSRF token (the raw session). |
| +func freshOwner(t *testing.T, fx *consoleFixture, addr, code string) (*http.Client, string) { |
| + t.Helper() |
| + c := newBrowser(t) |
| + fx.setUser(addr) |
| + signUp(t, fx, c, code) |
| + csrf := sessionToken(t, fx, c) |
| + if err := fx.st.RecordStepUp(csrf, addr, time.Now(), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + return c, csrf |
| +} |
| + |
| +// browserDelete is the browser's Delete account straight through |
| +// ServeHTTP with c's cookies. It takes no *testing.T, so a goroutine may |
| +// make it, and it never waits on the test server's connections. |
| +func browserDelete(srv *Server, base string, c *http.Client, csrf, sqid, confirm string) billingReply { |
| + form := url.Values{"csrf": {csrf}, "confirm": {confirm}} |
| + req := httptest.NewRequest(http.MethodPost, base+"/a/"+sqid+"/delete", strings.NewReader(form.Encode())) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + u, _ := url.Parse(base) |
| + for _, ck := range c.Jar.Cookies(u) { |
| + if ck.Name != flashCookie { |
| + req.AddCookie(ck) |
| + } |
| + } |
| + rr := httptest.NewRecorder() |
| + srv.ServeHTTP(rr, req) |
| + out := billingReply{Status: rr.Code, Loc: rr.Header().Get("Location"), Body: rr.Body.String()} |
| + for _, ck := range rr.Result().Cookies() { |
| + if ck.Name == flashCookie && ck.Value != "" { |
| + v, _ := url.QueryUnescape(ck.Value) |
| + out.Flash, out.FlashMsg, _ = strings.Cut(v, "|") |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// wantRefusedDelete is the settings page with the refusal's flash. |
| +func wantRefusedDelete(t *testing.T, r billingReply, sqid, msg string) { |
| + t.Helper() |
| + if r.Status != http.StatusSeeOther || r.Loc != "/a/"+sqid+"/settings" || r.Flash != "err" || r.FlashMsg != msg { |
| + t.Fatalf("delete = %d %q flash %s:%q, want the refusal %q", r.Status, r.Loc, r.Flash, r.FlashMsg, msg) |
| + } |
| +} |
| + |
| +// wantLive fails unless the account's row is live and its manifest is not |
| +// a tombstone. |
| +func wantLive(t *testing.T, fx *consoleFixture, sqid string) { |
| + t.Helper() |
| + if a, err := fx.st.AccountBySqid(sqid); err != nil || a == nil { |
| + t.Fatalf("account %s: %+v %v, want it live", sqid, a, err) |
| + } |
| + if m := readManifest(t, fx.rel, sqid); m.Deleted() { |
| + t.Fatalf("account %s's manifest was tombstoned", sqid) |
| + } |
| +} |
| + |
| +// deletablePlatform is a platform account (planAccount id) with its |
| +// manifest in the bucket, granted up to 5 customers on plans, and its |
| +// platform credential. |
| +func deletablePlatform(t *testing.T, fx *consoleFixture, id int64, plans ...string) (*Account, string) { |
| + t.Helper() |
| + p := planAccount(t, fx, id) |
| + if err := WriteAccountManifest(context.Background(), fx.rel, p.ID, p.Sqid, p.Name, p.CreatedAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + grantPlatformAccount(t, fx, p.Sqid, 5, plans...) |
| + return p, platformToken(t, fx, p.ID, "cms") |
| +} |
| + |
| +// ---- linkedPlatform ------------------------------------------------------------ |
| + |
| +func TestLinkedPlatformNamesThePlatform(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + p, tok := deletablePlatform(t, fx, 501) |
| + ctx := context.Background() |
| + if got, err := fx.srv.linkedPlatform(ctx, p); err != nil || got != nil { |
| + t.Fatalf("linkedPlatform of an unlinked account = %+v %v, want nil", got, err) |
| + } |
| + status, out, raw := createCustomer(t, fx.ts.URL, p.Sqid, tok, map[string]any{"name": "shop"}) |
| + if status != http.StatusCreated { |
| + t.Fatalf("create = %d %s", status, raw) |
| + } |
| + cust, err := fx.st.AccountBySqid(customerIn(t, out)["account"].(string)) |
| + if err != nil || cust == nil { |
| + t.Fatal(cust, err) |
| + } |
| + got, err := fx.srv.linkedPlatform(ctx, cust) |
| + if err != nil || got == nil || got.ID != p.ID || got.Sqid != p.Sqid || got.Name != p.Name { |
| + t.Fatalf("linkedPlatform of the customer = %+v %v, want %+v", got, err, p) |
| + } |
| + |
| + // A link to a platform this console has no live row for is still a |
| + // link: the platform's sqid, nothing else. |
| + orphan := testAccountID() |
| + if _, err := fx.st.EnsureLinkedAccount(orphan, domains.Sqid(orphan), "orphan", "zzzz", "", strings.Repeat("ef", 16), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + o, err := fx.st.AccountBySqid(domains.Sqid(orphan)) |
| + if err != nil || o == nil { |
| + t.Fatal(o, err) |
| + } |
| + if got, err := fx.srv.linkedPlatform(ctx, o); err != nil || got == nil || got.Sqid != "zzzz" || got.ID != 0 || got.Name != "" { |
| + t.Fatalf("linkedPlatform of an orphan = %+v %v, want only the sqid zzzz", got, err) |
| + } |
| +} |
| + |
| +// ---- deletion refusals --------------------------------------------------------- |
| + |
| +func TestPlatformAccountDeletionRefusedWithCustomers(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + p, tok := deletablePlatform(t, fx, 501) |
| + if status, _, raw := createCustomer(t, fx.ts.URL, p.Sqid, tok, map[string]any{"name": "shop"}); status != http.StatusCreated { |
| + t.Fatalf("create = %d %s", status, raw) |
| + } |
| + c, csrf := freshOwner(t, fx, "owner"+p.Sqid+"@example.com", "code-delete-platform") |
| + r := browserDelete(fx.srv, fx.ts.URL, c, csrf, p.Sqid, p.Name) |
| + wantRefusedDelete(t, r, p.Sqid, fmt.Sprintf(platformCopy["delete.platform_has_customers"], 1)) |
| + wantLive(t, fx, p.Sqid) |
| + |
| + // A pending mint alone holds a platform too. |
| + q, _ := deletablePlatform(t, fx, 520) // clear of the ids the bucket mints next |
| + if err := fx.st.ReservePlatformMint(context.Background(), PendingMint{MintID: strings.Repeat("ab", 16), Platform: q.Sqid, |
| + Ref: "4812", Name: "cafe", By: "service:" + q.Sqid + "/cms", CreatedAt: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + c, csrf = freshOwner(t, fx, "owner"+q.Sqid+"@example.com", "code-delete-pending") |
| + r = browserDelete(fx.srv, fx.ts.URL, c, csrf, q.Sqid, q.Name) |
| + wantRefusedDelete(t, r, q.Sqid, fmt.Sprintf(platformCopy["delete.platform_has_customers"], 1)) |
| + wantLive(t, fx, q.Sqid) |
| +} |
| + |
| +func TestLinkedAccountBrowserDeletionRefused(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + p, tok := deletablePlatform(t, fx, 501) |
| + status, out, raw := createCustomer(t, fx.ts.URL, p.Sqid, tok, map[string]any{"name": "shop"}) |
| + 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(cust, err) |
| + } |
| + // A console member who owns the customer (as a claim would make one). |
| + if err := fx.st.AddMember(cust.ID, "claimer@example.com", RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + c, csrf := freshOwner(t, fx, "claimer@example.com", "code-delete-linked") |
| + r := browserDelete(fx.srv, fx.ts.URL, c, csrf, sqid, "shop") |
| + wantRefusedDelete(t, r, sqid, fmt.Sprintf(platformCopy["delete.linked"], p.Name)) |
| + wantLive(t, fx, sqid) |
| +} |
| + |
| +// ---- deletion and creation, serialized (Astra r1-3) ---------------------------- |
| + |
| +// TestPlatformDeletionWaitsForAnInFlightCreate: creation first. The create |
| +// holds the platform lifecycle lock with its pending mint written; the |
| +// owner's delete waits for it, then sees the customer and refuses. |
| +func TestPlatformDeletionWaitsForAnInFlightCreate(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + p, tok := deletablePlatform(t, fx, 501) |
| + c, csrf := freshOwner(t, fx, "owner"+p.Sqid+"@example.com", "code-wait-create") |
| + events := recordLocks(t, p.Sqid) |
| + g := newGate(t) |
| + fx.srv.platformMintStep = func(step string) error { |
| + if step == "mint" { |
| + g.block() |
| + } |
| + return nil |
| + } |
| + guard := time.NewTimer(10 * time.Second) |
| + defer guard.Stop() |
| + |
| + type reply struct { |
| + status int |
| + raw string |
| + err error |
| + } |
| + created := make(chan reply, 1) |
| + go func() { |
| + status, _, raw, err := callJSON(http.MethodPost, platformCustomersURL(fx.ts.URL, p.Sqid), tok, map[string]any{"name": "shop", "ref": "4812"}) |
| + created <- reply{status, raw, err} |
| + }() |
| + waitOrGuard(t, g.entered, guard.C, "the create never reached its mint") |
| + if pm := pendingMints(t, fx.st, p.Sqid); len(pm) != 1 { |
| + t.Fatalf("pending mints %+v, want the in-flight create's", pm) |
| + } |
| + drainLocks(events) // the create's own |
| + |
| + deleted := make(chan billingReply, 1) |
| + go func() { deleted <- browserDelete(fx.srv, fx.ts.URL, c, csrf, p.Sqid, p.Name) }() |
| + waitLock(t, events, guard.C, lockEv{"platform", p.Sqid, lockWaiting}, "the delete waiting on the platform lock") |
| + select { |
| + case r := <-deleted: |
| + t.Fatalf("the delete answered %+v while the create held the platform lock", r) |
| + default: |
| + } |
| + g.open() |
| + |
| + if r := waitOrGuard(t, created, guard.C, "the create never answered"); r.err != nil || r.status != http.StatusCreated { |
| + t.Fatalf("create = %d %s %v, want 201", r.status, r.raw, r.err) |
| + } |
| + r := waitOrGuard(t, deleted, guard.C, "the delete never answered") |
| + wantRefusedDelete(t, r, p.Sqid, fmt.Sprintf(platformCopy["delete.platform_has_customers"], 1)) |
| + wantLive(t, fx, p.Sqid) |
| + |
| + // A fresh start reaps nothing: the platform and its customer stay. |
| + if _, err := MaterializeAccounts(context.Background(), fx.rel, fx.st); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantLive(t, fx, p.Sqid) |
| + customers, err := fx.st.LinkedCustomers(context.Background(), p.Sqid) |
| + if err != nil || len(customers) != 1 || customers[0].Ref != "4812" { |
| + t.Fatalf("customers after materialize %+v %v, want shop", customers, err) |
| + } |
| + wantLive(t, fx, customers[0].Sqid) |
| +} |
| + |
| +// TestCreateWaitsForAnInFlightPlatformDeletion: deletion first. The |
| +// deletion holds the lock with its checks passed; a create waits for it and |
| +// then finds the platform gone, writing nothing. |
| +func TestCreateWaitsForAnInFlightPlatformDeletion(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + p, tok := deletablePlatform(t, fx, 501) |
| + c, csrf := freshOwner(t, fx, "owner"+p.Sqid+"@example.com", "code-wait-delete") |
| + events := recordLocks(t, p.Sqid) |
| + g := newGate(t) |
| + fx.srv.deleteBeforeTombstone = g.block |
| + guard := time.NewTimer(10 * time.Second) |
| + defer guard.Stop() |
| + |
| + deleted := make(chan billingReply, 1) |
| + go func() { deleted <- browserDelete(fx.srv, fx.ts.URL, c, csrf, p.Sqid, p.Name) }() |
| + waitOrGuard(t, g.entered, guard.C, "the delete never reached its tombstone") |
| + drainLocks(events) // the delete's own |
| + |
| + type reply struct { |
| + status int |
| + raw string |
| + err error |
| + } |
| + created := make(chan reply, 1) |
| + go func() { |
| + status, _, raw, err := callJSON(http.MethodPost, platformCustomersURL(fx.ts.URL, p.Sqid), tok, map[string]any{"name": "shop", "ref": "4812"}) |
| + created <- reply{status, raw, err} |
| + }() |
| + waitLock(t, events, guard.C, lockEv{"platform", p.Sqid, lockWaiting}, "the create waiting on the platform lock") |
| + if pm := pendingMints(t, fx.st, p.Sqid); len(pm) != 0 { |
| + t.Fatalf("pending mints %+v while the delete held the lock, want none", pm) |
| + } |
| + g.open() |
| + |
| + r := waitOrGuard(t, deleted, guard.C, "the delete never answered") |
| + if r.Status != http.StatusSeeOther || r.Flash != "ok" || !strings.HasPrefix(r.FlashMsg, "Deleted") { |
| + t.Fatalf("delete = %+v, want deleted", r) |
| + } |
| + if a, _ := fx.st.AccountBySqid(p.Sqid); a != nil { |
| + t.Fatal("the platform survived its deletion") |
| + } |
| + if m := readManifest(t, fx.rel, p.Sqid); !m.Deleted() { |
| + t.Fatal("the platform's manifest was not tombstoned") |
| + } |
| + cr := waitOrGuard(t, created, guard.C, "the create never answered") |
| + if cr.err != nil || cr.status != http.StatusNotFound || cr.raw != "404 page not found\n" { |
| + t.Fatalf("create after the deletion = %d %q %v, want the stdlib 404", cr.status, cr.raw, cr.err) |
| + } |
| + if ms := platformManifests(t, fx.rel, p.Sqid); len(ms) != 0 { |
| + t.Fatalf("customer manifests %+v, want none", ms) |
| + } |
| + if pm := pendingMints(t, fx.st, p.Sqid); len(pm) != 0 { |
| + t.Fatalf("pending mints %+v, want none", pm) |
| + } |
| +} |
| + |
| +// ---- lock order (Astra r2-1, r3-2) --------------------------------------------- |
| + |
| +// buyWorld is a billing-on console with plans on, the domain-buy tests' |
| +// fake billing and registrar, and an EMPTY account 501 that deletion can |
| +// retire: its manifest is in the bucket, renewal is stopped (synced), and |
| +// its owner is signed in with a fresh sign-in proof. |
| +func buyWorld(t *testing.T) *opsFixture { |
| + t.Helper() |
| + previousPage := pageDomainPurchase |
| + pageDomainPurchase = func(context.Context, string, string, string) error { return nil } |
| + t.Cleanup(func() { pageDomainPurchase = previousPage }) |
| + reg := registrartest.New() |
| + reg.BalanceMoney = registrar.Money{Currency: "usd", Minor: 100000} |
| + reg.Available["shop.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + zone := zonehosttest.New("ns1.carloku.test", "ns2.carloku.test", "ns3.carloku.test", "ns4.carloku.test") |
| + bf := newBillingFixtureWith(t, consoleFixtureOptions{WithKey: true, Tweak: func(c *Config) { |
| + c.Registrar, c.ZoneHost = reg, zone |
| + c.EdgeIPs = []string{"192.0.2.10"} |
| + c.DomainCatalog = &domainreg.Catalog{Version: "test", DailyCap: 3, TLDs: map[string]domainreg.TLD{"com": { |
| + Register: map[string]int64{"usd": 1500}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}}} |
| + }}) |
| + if bf.srv.cfg.PlanCatalog == nil { |
| + t.Fatal("the billing fixture has no plan catalog: planLock would take nothing") |
| + } |
| + bf.srv.billing.ready.Store(true) |
| + bf.srv.consoleMail = &fakeConsoleMail{ready: true} |
| + bf.srv.sendFederated = nil |
| + o := &opsFixture{billingFixture: bf} |
| + o.wire() |
| + sub := bf.personalSub("sub_1", "active", nil) |
| + sub.CancelAtPeriodEnd = true // renewal stopped, so retirement does not refuse |
| + bf.put(sub) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.deletable(t) |
| + o.signInOwner(t) |
| + o.stepUp(t) |
| + o.reset() |
| + return o |
| +} |
| + |
| +// createAppThroughCLI is `carlos apps create` on the account, through the |
| +// CLI door (handleAPICreateApp takes planLock). |
| +func createAppThroughCLI(t *testing.T, fx *consoleFixture, acct *Account, app string) { |
| + t.Helper() |
| + tok := serviceToken(t, fx.st, acct.ID, "ci-"+app, "", svcrole.Publish) |
| + status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+acct.Sqid+"/new", map[string]any{"name": app}, tok) |
| + if status/100 != 2 { |
| + t.Fatalf("CLI create %s/%s = %d %v", acct.Sqid, app, status, out) |
| + } |
| + if has, err := fx.st.HasAppIn(acct.ID, app); err != nil || !has { |
| + t.Fatalf("app %s after the CLI create: %v %v", app, has, err) |
| + } |
| +} |
| + |
| +// attachBuyRegistry gives the buy world's app its route, as the purchase |
| +// tests do. |
| +func attachBuyRegistry(t *testing.T, o *opsFixture, app string) { |
| + t.Helper() |
| + o.srv.cfg.Registry = attachRegistry(t, registry.Route{Host: "app.example.test", Account: o.acct.Sqid, App: app, |
| + Kind: "static", Status: "ready", Channel: "canary/live"}) |
| +} |
| + |
| +type purchaseResult struct { |
| + p *DomainPurchase |
| + ref *doorRefusal |
| +} |
| + |
| +// TestDeletionAndDomainPurchaseDoNotDeadlock is the reviewer's interleaving |
| +// (Astra r2-1, r3-2): a deletion holding the lifecycle lock and the billing |
| +// hold, a purchase holding the account lock and waiting on the billing |
| +// hold. The deletion takes no account lock, so it refuses (the account now |
| +// holds an app) and releases the billing hold, and the purchase finishes. |
| +func TestDeletionAndDomainPurchaseDoNotDeadlock(t *testing.T) { |
| + for i := range 20 { |
| + t.Run(fmt.Sprint(i), func(t *testing.T) { deletionMeetsPurchase(t) }) |
| + if t.Failed() { |
| + return |
| + } |
| + } |
| +} |
| + |
| +func deletionMeetsPurchase(t *testing.T) { |
| + o := buyWorld(t) |
| + sqid := o.acct.Sqid |
| + events := recordLocks(t, sqid) |
| + g := newGate(t) |
| + o.srv.deleteNowEnter = g.block |
| + guard := time.NewTimer(10 * time.Second) |
| + defer guard.Stop() |
| + |
| + // 1. The deletion passes its first checks (the account is empty) and |
| + // blocks holding the lifecycle lock and the billing hold. |
| + deleted := make(chan billingReply, 1) |
| + go func() { deleted <- browserDelete(o.srv, o.ts.URL, o.owner, o.csrf, sqid, o.acct.Name) }() |
| + waitOrGuard(t, g.entered, guard.C, "step 1: the deletion never reached deleteAccountNow") |
| + drainLocks(events) |
| + |
| + // 2. An app is created through the CLI door: planLock is the account |
| + // lock, which the deletion does not hold. |
| + createAppThroughCLI(t, o.consoleFixture, o.acct, "kass") |
| + attachBuyRegistry(t, o, "kass") |
| + drainLocks(events) |
| + |
| + // 3. A domain purchase for that app takes the account lock and waits on |
| + // the billing hold. |
| + bought := make(chan purchaseResult, 1) |
| + go func() { |
| + p, _, ref := startQuotedPurchase(o.srv, context.Background(), o.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + bought <- purchaseResult{p, ref} |
| + }() |
| + waitLock(t, events, guard.C, lockEv{"account", sqid, lockHeld}, "step 3: the purchase holding the account lock") |
| + waitLock(t, events, guard.C, lockEv{"billing", sqid, lockWaiting}, "step 3: the purchase waiting on the billing hold") |
| + |
| + // 4. Released, the deletion's re-check sees the app and refuses without |
| + // ever waiting on the account lock; its deferred release frees the |
| + // billing hold. |
| + g.open() |
| + var r billingReply |
| + for done := false; !done; { |
| + select { |
| + case ev := <-events: |
| + if ev.kind == "account" && ev.event == lockWaiting { |
| + t.Fatalf("step 4: the deletion waited on the account lock (%v)", ev) |
| + } |
| + case r = <-deleted: |
| + done = true |
| + case <-guard.C: |
| + t.Fatal("guard timer: step 4: the deletion never answered (deadlock)") |
| + } |
| + } |
| + wantRefusedDelete(t, r, sqid, deletionAdvice(fmt.Errorf("console: still holds %d app(s)", 1))) |
| + wantLive(t, o.consoleFixture, sqid) |
| + if o.retiring(t) { |
| + t.Fatal("step 4: a refused deletion left the account retiring") |
| + } |
| + |
| + // 5. The purchase takes the billing hold and finishes with the fake |
| + // billing's answer. |
| + res := waitOrGuard(t, bought, guard.C, "step 5: the purchase never finished (deadlock)") |
| + if res.ref != nil || res.p == nil || res.p.State != PurchaseAwaitingPayment { |
| + t.Fatalf("step 5: purchase = %+v %+v, want a checkout awaiting payment", res.p, res.ref) |
| + } |
| +} |
| + |
| +// lockOrderChecker follows platform, account and billing holds per key and |
| +// fails on a wait for a lock earlier in the order while a later one is |
| +// held on the same key. It records each nesting it sees, so a test can |
| +// show it watched the pairs it meant to. |
| +type lockOrderChecker struct { |
| + t *testing.T |
| + mu sync.Mutex |
| + held map[string]map[string]int // key -> kind -> holds |
| + nesting map[string]bool // "outer>inner key" |
| +} |
| + |
| +var lockRank = map[string]int{"platform": 0, "account": 1, "billing": 2} |
| + |
| +func (c *lockOrderChecker) see(kind, key, event string) { |
| + rank, ok := lockRank[kind] |
| + if !ok { |
| + return |
| + } |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + h := c.held[key] |
| + if h == nil { |
| + h = map[string]int{} |
| + c.held[key] = h |
| + } |
| + switch event { |
| + case lockWaiting: |
| + for other, n := range h { |
| + if n > 0 && lockRank[other] > rank { |
| + c.t.Errorf("lock order: waiting on %s %s while holding %s (order is platform, account, billing)", kind, key, other) |
| + } |
| + } |
| + case lockHeld: |
| + for other, n := range h { |
| + if n > 0 { |
| + c.nesting[other+">"+kind+" "+key] = true |
| + } |
| + } |
| + h[kind]++ |
| + case lockReleased: |
| + h[kind]-- |
| + } |
| +} |
| + |
| +func TestLockOrderLifecycleAccountBilling(t *testing.T) { |
| + o := buyWorld(t) |
| + checker := &lockOrderChecker{t: t, held: map[string]map[string]int{}, nesting: map[string]bool{}} |
| + h := checker.see |
| + lifetimeLockHook.Store(&h) |
| + t.Cleanup(func() { lifetimeLockHook.Store(nil) }) |
| + ctx := context.Background() |
| + |
| + // A customer create: the lifecycle lock alone. |
| + p, ptok := deletablePlatform(t, o.consoleFixture, 502, "free") |
| + if status, _, raw := createCustomer(t, o.ts.URL, p.Sqid, ptok, map[string]any{"name": "shop", "ref": "4812"}); status != http.StatusCreated { |
| + t.Fatalf("customer create = %d %s", status, raw) |
| + } |
| + |
| + // A platform delete with billing on: lifecycle, then the billing hold. |
| + q, _ := deletablePlatform(t, o.consoleFixture, 520, "free") // clear of the ids the bucket mints next |
| + qc, qcsrf := freshOwner(t, o.consoleFixture, "owner"+q.Sqid+"@example.com", "code-order-q") |
| + if r := browserDelete(o.srv, o.ts.URL, qc, qcsrf, q.Sqid, q.Name); r.Flash != "ok" { |
| + t.Fatalf("billing-on platform delete = %+v, want deleted", r) |
| + } |
| + |
| + // An app create on a plan-capped account, then a domain purchase: the |
| + // account lock, then the billing hold. |
| + createAppThroughCLI(t, o.consoleFixture, o.acct, "kass") |
| + attachBuyRegistry(t, o, "kass") |
| + if p, _, ref := startQuotedPurchase(o.srv, ctx, o.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test"); ref != nil || p == nil { |
| + t.Fatalf("purchase = %+v %+v", p, ref) |
| + } |
| + |
| + // A platform delete with billing off: the lifecycle lock alone. |
| + fx := newConsoleFixture(t) |
| + r, _ := deletablePlatform(t, fx, 504) |
| + rc, rcsrf := freshOwner(t, fx, "owner"+r.Sqid+"@example.com", "code-order-r") |
| + if d := browserDelete(fx.srv, fx.ts.URL, rc, rcsrf, r.Sqid, r.Name); d.Flash != "ok" { |
| + t.Fatalf("billing-off platform delete = %+v, want deleted", d) |
| + } |
| + |
| + checker.mu.Lock() |
| + defer checker.mu.Unlock() |
| + for _, want := range []string{"platform>billing " + q.Sqid, "account>billing " + o.acct.Sqid} { |
| + if !checker.nesting[want] { |
| + t.Errorf("never saw %s; saw %v", want, checker.nesting) |
| + } |
| + } |
| + for key, kinds := range checker.held { |
| + for kind, n := range kinds { |
| + if n != 0 { |
| + t.Errorf("%s %s left with %d holds", kind, key, n) |
| + } |
| + } |
| + } |
| + for _, key := range []string{p.Sqid, q.Sqid, r.Sqid} { |
| + if _, ok := checker.held[key]["platform"]; !ok { |
| + t.Errorf("never saw the platform lock on %s", key) |
| + } |
| + } |
| +} |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index 84d82dcbb..ea82cbf93 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -945,8 +945,8 @@ var routeDecls = []routeDecl{ |
| {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 |
| + // §6.1): a platform account creates, lists, shows and updates 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 |
| @@ -955,6 +955,7 @@ var routeDecls = []routeDecl{ |
| {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}, |
| + {Pattern: "PATCH /api/cli/platform/{account}/customers/{customer}", Kind: kindCLI, Allow: svcrole.Exactly(svcrole.Platform), Handler: (*Server).handlePlatformCustomerUpdate}, |
| // 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/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index f63aaca93..c14199680 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -190,6 +190,7 @@ route GET /static/{hash}/{file...} |
| route GET /upgrade |
| route GET /{$} |
| route PATCH /api/cli/apps/{account}/{app}/instances/{host} |
| +route PATCH /api/cli/platform/{account}/customers/{customer} |
| route POST /a/{sqid}/analytics/setting |
| route POST /a/{sqid}/apps/new |
| route POST /a/{sqid}/apps/new/region |