console: refuse platform mint collisions instead of repairing them
Task 8 fix round 1 (rulings A and B). A pending mint finishes only over a row that carries its own mint id. An id this console holds for another account, a ref another live customer holds, or an unreadable manifest leaves the promise pending. It writes no manifest and no row, logs one line for an operator, and the write door answers its own failure row. MintLinkedAccountIfFree asks the console before its create-only write, so a held id gets no manifest. The manifest restore, the dropped promise and the ref-less finish are gone. Customer create validates its body before it finishes earlier promises, so a refused create writes nothing; the gate's finish now runs only on the other doors.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+433
−272
internal/console/apiplatformcustomers.go+108 −109internal/console/apiplatformcustomers_test.go+204 −114internal/console/platform_store.go+38 −43internal/console/platform_store_test.go+31 −2internal/domains/mint.go+23 −4internal/domains/mint_test.go+29 −0
diff --git a/internal/console/apiplatformcustomers.go b/internal/console/apiplatformcustomers.go| index 16c64a808..c2792b5b0 100644 |
| --- a/internal/console/apiplatformcustomers.go |
| +++ b/internal/console/apiplatformcustomers.go |
| @@ -19,12 +19,10 @@ package console |
| import ( |
| "context" |
| - "encoding/json" |
| "errors" |
| "fmt" |
| "log" |
| "net/http" |
| - "os" |
| "slices" |
| "strings" |
| "time" |
| @@ -119,7 +117,8 @@ func (s *Server) platformGate(w http.ResponseWriter, r *http.Request) (platformC |
| return s.platformGateFor(w, r, "") |
| } |
| -// platformGateFor is the gate every platform door runs, in order: |
| +// platformAuthorize is who may use a platform door, in order, writing |
| +// nothing: |
| // |
| // - apiPrincipalAccount: the platform credential's own account, or an |
| // account the person belongs to; anything else is the family's 404; |
| @@ -129,14 +128,10 @@ func (s *Server) platformGate(w http.ResponseWriter, r *http.Request) (platformC |
| // 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) { |
| +// 7); a revoke landing since then is caught here. |
| +// |
| +// failRow is the door's own failure row, for a store error. |
| +func (s *Server) platformAuthorize(w http.ResponseWriter, r *http.Request, failRow string) (platformCaller, bool) { |
| p, acct, ok := s.apiPrincipalAccount(w, r) |
| if !ok { |
| return platformCaller{}, false |
| @@ -180,7 +175,27 @@ func (s *Server) platformGateFor(w http.ResponseWriter, r *http.Request, failRow |
| return platformCaller{}, false |
| } |
| c.Grant = g |
| + return c, true |
| +} |
| +// platformGateFor is the gate every platform door but create runs: |
| +// platformAuthorize, then, 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. |
| +// |
| +// Create runs platformAuthorize alone and finishes under its own hold of |
| +// the lock, after it has validated its body, so a refused create writes |
| +// nothing (Astra P2-4). |
| +func (s *Server) platformGateFor(w http.ResponseWriter, r *http.Request, failRow string) (platformCaller, bool) { |
| + c, ok := s.platformAuthorize(w, r, failRow) |
| + if !ok { |
| + return platformCaller{}, false |
| + } |
| + ctx := r.Context() |
| + acct := c.Platform |
| pending, err := s.store.PendingPlatformMints(ctx, acct.Sqid) |
| if err == nil && len(pending) > 0 { |
| unlock := s.lockPlatformLifecycle(acct.Sqid) |
| @@ -347,7 +362,9 @@ type createPlatformCustomerRequest struct { |
| // 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; |
| +// 1. authorize (platformAuthorize, which writes nothing), then validate |
| +// the body: name, ref, and a plan within the grant. A refusal here |
| +// writes nothing, not even the finish of an earlier promise; |
| // 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 |
| @@ -363,7 +380,9 @@ type createPlatformCustomerRequest struct { |
| // 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") |
| + // platformAuthorize, not the gate: pending mints are finished in step |
| + // 3, after the body is validated, so a refused create writes nothing. |
| + c, ok := s.platformAuthorize(w, r, "create.failed") |
| if !ok { |
| return |
| } |
| @@ -529,53 +548,22 @@ func (s *Server) writePlatformCreated(ctx context.Context, w http.ResponseWriter |
| 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. |
| +// an account: the store dropped it because the customer it would have |
| +// finished was deleted. It holds no capacity and no ref. |
| var errPlatformMintEnded = errors.New("console: the pending customer create ended without an account") |
| +// errPlatformMintHeld is a pending mint this console refuses to finish |
| +// because the bucket and the console disagree about it: the id the bucket |
| +// would give it is held by another account, or its ref by another live |
| +// customer. Nothing is written; the promise stays, holding its slot and |
| +// ref, until an operator repairs the bucket or the database. |
| +var errPlatformMintHeld = errors.New("console: the pending customer create is held until an operator repairs the bucket") |
| + |
| // 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). |
| +// that ended without an account (errPlatformMintEnded) is past 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 { |
| @@ -589,50 +577,78 @@ func (s *Server) finishPendingMints(ctx context.Context, platform *Account) erro |
| 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. |
| +// finishPlatformMint finishes one pending mint, or refuses to and leaves it |
| +// pending. The caller holds the platform lifecycle lock. |
| // |
| -// Every pending mint reaches an end state: |
| +// The mint writes the customer's manifest (MintLinkedAccountIfFree, |
| +// idempotent on the mint id, so the account a first attempt wrote is found |
| +// again rather than minted twice), turns its analytics on, and records it |
| +// (CreateLinkedAccount, which deletes the promise in the same transaction, |
| +// over a row materialization already made if there is one). A finished |
| +// create is audited on both accounts here, so a create finished by a later |
| +// request is audited too. |
| // |
| -// - 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. |
| +// It finishes only an account that is this mint's: a row at the id must |
| +// carry the mint's id (mint identity), and a live customer holding the ref |
| +// must be this mint's account. Anything else means the bucket and the |
| +// console disagree (a manifest missing from the bucket, or one written |
| +// outside this console), and it refuses up front with errPlatformMintHeld: |
| +// no manifest and no row are written, one line for an operator names the |
| +// mint id, the account id and the reason, and the promise stays, holding |
| +// its slot and ref. Repairing silently is how an identity, a deletion or a |
| +// ref gets lost. The cases: |
| +// |
| +// - the id the bucket would give the mint is held by an account in this |
| +// console (live or deleted, any platform): MintLinkedAccountIfFree asks |
| +// before it writes and nothing is written; |
| +// - the ref is held by a live customer that is not this mint's; |
| +// - a manifest already carrying this mint id sits at an id whose row is |
| +// another account's (errLinkedIDTaken from CreateLinkedAccount). |
| +// |
| +// A bucket that cannot be read, or a database or analytics failure, keeps |
| +// the promise too, and the next platform request tries again. The one end |
| +// without an account is this mint's own account deleted before the finish |
| +// (ErrAccountGone): the store has dropped the promise. |
| 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) |
| } |
| + held := func(id int64, reason string) error { |
| + log.Printf("console: platform %s: pending customer create %s held: account %d %s; it stays pending, "+ |
| + "and the platform's writes fail, until an operator repairs the bucket or the console", platform.Sqid, |
| + m.MintID, id, reason) |
| + return fmt.Errorf("%w: mint %s, account %d: %s", errPlatformMintHeld, m.MintID, id, reason) |
| + } |
| + if m.Ref != "" { |
| + holder, holderMint, ok, err := s.store.refHolder(ctx, platform.Sqid, m.Ref) |
| + if err != nil { |
| + log.Printf("console: platform %s: pending customer create %s: ref: %v", platform.Sqid, m.MintID, err) |
| + return nil, err |
| + } |
| + if ok && holderMint != m.MintID { |
| + return nil, held(holder, fmt.Sprintf("holds ref %q and was not made by this create", m.Ref)) |
| + } |
| + } |
| 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) |
| + var heldID int64 |
| + id, sqid, _, err := domains.MintLinkedAccountIfFree(ctx, s.cfg.Releases, m.Name, platform.Sqid, m.Ref, m.MintID, m.CreatedAt, |
| + func(id int64) error { |
| + taken, err := s.store.accountIDHeld(ctx, id) |
| + if err != nil { |
| + return err |
| + } |
| + if taken { |
| + heldID = id |
| + return errLinkedIDTaken |
| + } |
| + return nil |
| + }) |
| + if errors.Is(err, errLinkedIDTaken) { |
| + return nil, held(heldID, "is in this console with no manifest in the bucket, and the bucket gives its id to this create") |
| + } |
| 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 |
| @@ -650,12 +666,6 @@ func (s *Server) finishPlatformMint(ctx context.Context, platform *Account, m Pe |
| 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): |
| @@ -663,20 +673,9 @@ func (s *Server) finishPlatformMint(ctx context.Context, platform *Account, m Pe |
| 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) |
| + return nil, held(id, "is another account in this console, and the manifest carrying this create sits at its id") |
| + case errors.Is(err, ErrPlatformRefTaken): |
| + return nil, held(id, fmt.Sprintf("would take ref %q, which another live customer holds", m.Ref)) |
| 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) |
diff --git a/internal/console/apiplatformcustomers_test.go b/internal/console/apiplatformcustomers_test.go| index 07e7ff69f..510959ad9 100644 |
| --- a/internal/console/apiplatformcustomers_test.go |
| +++ b/internal/console/apiplatformcustomers_test.go |
| @@ -9,6 +9,7 @@ import ( |
| "io" |
| "net/http" |
| "net/http/httptest" |
| + "os" |
| "slices" |
| "strings" |
| "sync" |
| @@ -464,7 +465,10 @@ func TestCustomerCreateSurvivesAFailedFinish(t *testing.T) { |
| t.Fatalf("LinkedCustomerCount = %d, want 1", n) |
| } |
| - // The promise holds the only slot. |
| + // The second create finishes the promise first (its step 3; the seam |
| + // fails only once), so the slot is held by the account the promise |
| + // became, and no new manifest is written. That the unfinished promise |
| + // counts is the LinkedCustomerCount check above. |
| 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) |
| @@ -896,12 +900,15 @@ func TestPlatformCredentialRefusedAtOrdinaryDoors(t *testing.T) { |
| {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) |
| + status, out, 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) |
| + msg, _ := out["error"].(string) |
| + roleRefusal := strings.Contains(msg, `holds role "platform"`) || |
| + strings.Contains(msg, "this door is closed to service credentials") |
| + if status != http.StatusForbidden || !roleRefusal { |
| + t.Errorf("platform credential at %s %s = %d %s, want the role gate's refusal", c.method, c.u, status, raw) |
| } |
| } |
| if rows, err := fx.st.ServicePrincipals(acct.ID); err != nil || len(rows) != 1 { |
| @@ -909,33 +916,59 @@ func TestPlatformCredentialRefusedAtOrdinaryDoors(t *testing.T) { |
| } |
| } |
| -// 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) { |
| +// heldPromise is what a refused finish must leave: one pending mint for |
| +// ref, counted, and no manifest naming the platform anywhere. |
| +func wantHeldPromise(t *testing.T, fx *consoleFixture, platform, ref string, count int) { |
| + t.Helper() |
| + if p := pendingMints(t, fx.st, platform); len(p) != 1 || p[0].Ref != ref { |
| + t.Fatalf("pending mints %+v, want the promise for %s kept", p, ref) |
| + } |
| + if n := linkedCount(t, fx.st, platform); n != count { |
| + t.Fatalf("LinkedCustomerCount = %d, want %d: the held promise keeps its slot", n, count) |
| + } |
| + if ms := platformManifests(t, fx.rel, platform); len(ms) != count-1 { |
| + t.Fatalf("manifests naming the platform %+v, want %d: a held promise writes none", ms, count-1) |
| + } |
| +} |
| + |
| +// heldIDFixture is a platform, its credential, and the id the bucket will |
| +// give the next mint, with no manifest written for it. |
| +func heldIDFixture(t *testing.T) (*consoleFixture, *Account, string, int64) { |
| + t.Helper() |
| fx := newConsoleFixture(t) |
| acct := planAccount(t, fx, 501) |
| - grantPlatformAccount(t, fx, acct.Sqid, 1) |
| + grantPlatformAccount(t, fx, acct.Sqid, 5) |
| 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) |
| + return fx, acct, tok, next |
| +} |
| + |
| +// wantNoManifest fails if the bucket has a manifest at id. |
| +func wantNoManifest(t *testing.T, fx *consoleFixture, id int64) { |
| + t.Helper() |
| + if _, _, err := fx.rel.Get(context.Background(), domains.AccountManifestKey(domains.Sqid(id))); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("manifest at the held id %d: %v, want none written", id, 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) |
| +// TestCustomerFinishRefusesAnIDHeldByAnotherAccount: the bucket would give |
| +// the create an id this console holds for an unlinked account whose |
| +// manifest the bucket lacks. Nothing is written, the promise stays, and |
| +// every retry answers create.failed until an operator repairs it (Task 8 |
| +// fix round 1, ruling A). |
| +func TestCustomerFinishRefusesAnIDHeldByAnotherAccount(t *testing.T) { |
| + fx, acct, tok, next := heldIDFixture(t) |
| + if err := fx.st.CreateAccount(next, domains.Sqid(next), "other", "other@example.com", time.Now()); err != nil { |
| + t.Fatal(err) |
| } |
| - if n := linkedCount(t, fx.st, acct.Sqid); n != 0 { |
| - t.Fatalf("LinkedCustomerCount = %d, want 0: the ended promise holds no slot", n) |
| + for range 2 { |
| + 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") |
| + wantHeldPromise(t, fx, acct.Sqid, "4812", 1) |
| + wantNoManifest(t, fx, next) |
| } |
| other, err := fx.st.AccountBySqid(domains.Sqid(next)) |
| if err != nil || other == nil || other.Name != "other" { |
| @@ -944,42 +977,54 @@ func TestCustomerFinishOverAnIDHeldByAnotherAccountEndsThePromise(t *testing.T) |
| 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) |
| + // A read door goes on. |
| + if status, out, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid), tok); status != http.StatusOK || |
| + len(customersIn(t, out)) != 0 || out["count"] != float64(1) { |
| + t.Fatalf("list = %d %s, want no customers and the promise counted", status, raw) |
| } |
| - body, _, err := fx.rel.Get(context.Background(), domains.AccountManifestKey(domains.Sqid(next))) |
| - if err != nil { |
| +} |
| + |
| +// TestCustomerFinishRefusesAnIDHeldBySamePlatformCustomer is Astra's P1-1: |
| +// an existing customer of the same platform whose manifest is missing, so |
| +// the next mint is given its id. The create must not answer 201 with the |
| +// old customer, nor write a manifest at its id. |
| +func TestCustomerFinishRefusesAnIDHeldBySamePlatformCustomer(t *testing.T) { |
| + fx, acct, tok, next := heldIDFixture(t) |
| + ctx := context.Background() |
| + if err := fx.st.CreateLinkedAccount(ctx, NewLinkedAccount{ID: next, Sqid: domains.Sqid(next), Name: "old", |
| + Platform: acct.Sqid, Ref: "4700", MintID: strings.Repeat("ab", 16), By: "service:" + acct.Sqid + "/cms"}, |
| + time.Now()); 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 status == http.StatusCreated || status == http.StatusOK { |
| + t.Fatalf("create over a same-platform customer's id = %d %s, want no customer answered", status, raw) |
| } |
| - if got := customerIn(t, out)["account"]; got == domains.Sqid(next) { |
| - t.Fatalf("retry answered the held id %v", got) |
| + wantPlatformError(t, "create over a same-platform customer's id", status, out, http.StatusBadGateway, "create.failed") |
| + if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 1 || p[0].Ref != "4812" { |
| + t.Fatalf("pending mints %+v, want the promise for 4812 kept", p) |
| } |
| - 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) |
| + wantNoManifest(t, fx, next) |
| + if old, err := fx.st.LinkedCustomer(ctx, acct.Sqid, domains.Sqid(next)); err != nil || old == nil || old.Ref != "4700" || old.Name != "old" { |
| + t.Fatalf("the old customer %+v %v, want it untouched", old, err) |
| + } |
| + if rows := platformAudit(t, fx, acct.ID, auditPlatformCustomerCreate); len(rows) != 0 { |
| + t.Fatalf("audit %+v, want no create recorded", rows) |
| + } |
| + |
| + // The store holds the same rule: a row at the id finishes the mint only |
| + // when it carries the mint's own id. |
| + err := fx.st.CreateLinkedAccount(ctx, NewLinkedAccount{ID: next, Sqid: domains.Sqid(next), Name: "shop", |
| + Platform: acct.Sqid, Ref: "4812", MintID: pendingMints(t, fx.st, acct.Sqid)[0].MintID}, time.Now()) |
| + if !errors.Is(err, errLinkedIDTaken) { |
| + t.Fatalf("CreateLinkedAccount over a same-platform customer with another mint id = %v, want errLinkedIDTaken", err) |
| } |
| } |
| -// 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) { |
| +// TestCustomerFinishRefusesARefHeldByAnotherCustomer: a pending mint whose |
| +// ref a live customer took meanwhile (only a manifest written outside this |
| +// console can do that) is not finished, and nothing is written. |
| +func TestCustomerFinishRefusesARefHeldByAnotherCustomer(t *testing.T) { |
| fx := newConsoleFixture(t) |
| acct := planAccount(t, fx, 501) |
| grantPlatformAccount(t, fx, acct.Sqid, 5) |
| @@ -994,22 +1039,123 @@ func TestCustomerFinishWhenTheRefIsHeldFinishesWithoutIt(t *testing.T) { |
| strings.Repeat("cd", 16), time.Now()); err != nil { |
| t.Fatal(err) |
| } |
| + before, err := fx.rel.List(ctx, "accounts/") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // The read door goes on; the write door answers its own row. |
| status, out, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid), tok) |
| - if status != http.StatusOK { |
| - t.Fatalf("list = %d %s", status, raw) |
| + if cs := customersIn(t, out); status != http.StatusOK || len(cs) != 1 || cs[0]["name"] != "held" || out["count"] != float64(2) { |
| + t.Fatalf("list = %d %s, want held alone, and the promise counted", status, raw) |
| } |
| - cs := customersIn(t, out) |
| - refs := map[string]string{} |
| - for _, c := range cs { |
| - ref, _ := c["ref"].(string) |
| - refs[c["name"].(string)] = ref |
| + status, out, _ = createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "cafe", "ref": "4813"}) |
| + wantPlatformError(t, "create behind a held promise", status, out, http.StatusBadGateway, "create.failed") |
| + if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 1 || p[0].Ref != "4812" { |
| + t.Fatalf("pending mints %+v, want the 4812 promise kept and no new one", p) |
| + } |
| + if after, err := fx.rel.List(ctx, "accounts/"); err != nil || !slices.Equal(after, before) { |
| + t.Fatalf("bucket accounts/ %v %v, was %v: want nothing written", after, err, before) |
| + } |
| +} |
| + |
| +// unreadableKeyStore fails every Get of one key. |
| +type unreadableKeyStore struct { |
| + release.Store |
| + key string |
| +} |
| + |
| +func (s *unreadableKeyStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == s.key { |
| + return nil, "", errors.New("injected: unreadable") |
| } |
| - 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) |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +// TestCustomerFinishWaitsOutAnUnreadableManifest: a manifest the mint's |
| +// scan cannot read keeps the promise, writes nothing, and the create |
| +// succeeds once it reads again. |
| +func TestCustomerFinishWaitsOutAnUnreadableManifest(t *testing.T) { |
| + wrap := &unreadableKeyStore{} |
| + 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") |
| + ctx := context.Background() |
| + if err := WriteAccountManifest(ctx, fx.rel, acct.ID, acct.Sqid, acct.Name, acct.CreatedAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + wrap.key = domains.AccountManifestKey(acct.Sqid) |
| + |
| + status, out, _ := createCustomer(t, fx.ts.URL, acct.Sqid, tok, map[string]any{"name": "shop", "ref": "4812"}) |
| + wantPlatformError(t, "create over an unreadable manifest", status, out, http.StatusBadGateway, "create.failed") |
| + wantHeldPromise(t, fx, acct.Sqid, "4812", 1) |
| + |
| + wrap.key = "" |
| + 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 { |
| + t.Fatalf("retry = %d %s, want the promise finished and the ref hit", status, raw) |
| } |
| if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 0 { |
| - t.Fatalf("pending mints %+v, want none", p) |
| + t.Fatalf("pending mints %+v", p) |
| + } |
| +} |
| + |
| +// TestCustomerCreateRefusedWritesNothingWithAPendingMint is ruling B (Astra |
| +// P2-4): a create refused for its body writes nothing, not even the finish |
| +// of an earlier promise. |
| +func TestCustomerCreateRefusedWritesNothingWithAPendingMint(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", 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") |
| + ctx := context.Background() |
| + snapshot := func() string { |
| + t.Helper() |
| + keys, err := fx.rel.List(ctx, "accounts/") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var accounts, plans, events int |
| + for q, n := range map[string]*int{ |
| + `SELECT COUNT(*) FROM accounts`: &accounts, |
| + `SELECT COUNT(*) FROM account_plans`: &plans, |
| + `SELECT COUNT(*) FROM audit`: &events, |
| + } { |
| + if err := fx.st.db.QueryRowContext(ctx, q).Scan(n); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return fmt.Sprintf("manifests %v, accounts %d, plans %d, audit rows %d, pending %d", |
| + keys, accounts, plans, events, len(pendingMints(t, fx.st, acct.Sqid))) |
| + } |
| + before := snapshot() |
| + for _, body := range []map[string]any{ |
| + {"name": "Shop!"}, |
| + {"name": "shop", "ref": "a b"}, |
| + {"name": "shop", "plan": "gold"}, |
| + } { |
| + status, _, raw := createCustomer(t, fx.ts.URL, acct.Sqid, tok, body) |
| + if status != http.StatusBadRequest { |
| + t.Fatalf("create %v = %d %s, want 400", body, status, raw) |
| + } |
| + if after := snapshot(); after != before { |
| + t.Fatalf("refused create %v wrote: %s, was %s", body, after, before) |
| + } |
| + } |
| + status, _, raw := rawReq(t, http.MethodPost, platformCustomersURL(fx.ts.URL, acct.Sqid), tok, `{"name":`) |
| + if status != http.StatusBadRequest { |
| + t.Fatalf("malformed create = %d %s", status, raw) |
| + } |
| + if after := snapshot(); after != before { |
| + t.Fatalf("malformed create wrote: %s, was %s", after, before) |
| } |
| } |
| @@ -1078,59 +1224,3 @@ func TestCustomerCreateFinishesAPromiseMadeAfterItsGate(t *testing.T) { |
| 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/platform_store.go b/internal/console/platform_store.go| index 1d4f7d414..807742e34 100644 |
| --- a/internal/console/platform_store.go |
| +++ b/internal/console/platform_store.go |
| @@ -29,7 +29,6 @@ import ( |
| "strings" |
| "time" |
| - "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/svcrole" |
| ) |
| @@ -100,10 +99,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 is an account id this console already holds for an |
| + // account that is not this mint's (another sqid, platform or mint id). |
| + // The bucket allocated the id because it has no manifest for that |
| + // account: the bucket and the console disagree, and an operator repairs |
| + // it. The pending mint stays. |
| errLinkedIDTaken = errors.New("console: that account id belongs to another account") |
| ) |
| @@ -476,36 +476,29 @@ 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 |
| +// accountIDHeld reports whether this console has a row at the account id, |
| +// live or deleted. The bucket allocates ids; a row at an id the bucket |
| +// calls free is an account whose manifest the bucket lacks, and a mint must |
| +// not write a second identity over it. |
| +func (s *Store) accountIDHeld(ctx context.Context, id int64) (bool, error) { |
| + var n int |
| + err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM accounts WHERE id = ?`, id).Scan(&n) |
| + return n > 0, 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) |
| +// refHolder is the live customer of the platform holding ref: its id and |
| +// the mint id its row carries. ok is false when none does. |
| +func (s *Store) refHolder(ctx context.Context, platformSqid, ref string) (id int64, mintID string, ok bool, err error) { |
| + err = s.db.QueryRowContext(ctx, `SELECT id, platform_mint FROM accounts |
| + WHERE platform = ? AND platform != '' AND platform_ref = ? AND platform_ref != '' AND deleted_at = 0`, |
| + platformSqid, ref).Scan(&id, &mintID) |
| if errors.Is(err, sql.ErrNoRows) { |
| - return domains.AccountManifest{}, false, nil |
| + return 0, "", 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 0, "", false, err |
| } |
| - return m, true, nil |
| + return id, mintID, true, nil |
| } |
| // LinkedCustomerPlans returns every live customer's plan row and cap rows, |
| @@ -573,16 +566,18 @@ func (s *Store) LinkedCustomerPlans(ctx context.Context, platformSqid string) (m |
| } |
| // 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 |
| -// replaces only a missing or default-source plan row; otherwise the |
| -// accounts row is inserted with its link, and the plan row written with |
| -// source platform. Then the pending mint is deleted. Finishing twice is a |
| -// 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 errLinkedIDTaken, and the pending mint |
| -// is kept: what ends it is the caller's (finishPlatformMint drops it). |
| +// r1-1). A row already at the id is this mint's account only when it |
| +// carries the same sqid, platform AND mint id (platform_mint, which |
| +// materialization records from the manifest): mint identity, not just the |
| +// link. Such a row, materialized before the finish, is kept and a platform |
| +// plan replaces only a missing or default-source plan row. With no row at |
| +// the id, the accounts row is inserted with its link and the plan row |
| +// written with source platform. Then the pending mint is deleted. |
| +// Finishing twice is a no-op. A finish over this mint's own tombstone |
| +// (materialized, then deleted) drops the pending mint and is |
| +// ErrAccountGone: the account stays deleted. A row at the id with any other |
| +// identity (another sqid, platform or mint id, live or deleted) is |
| +// errLinkedIDTaken, and the pending mint is kept, writing nothing. |
| // |
| // 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 |
| @@ -597,10 +592,10 @@ func (s *Store) CreateLinkedAccount(ctx context.Context, a NewLinkedAccount, now |
| return err |
| } |
| defer tx.Rollback() |
| - var sqid, platform string |
| + var sqid, platform, mint string |
| var deleted int64 |
| - err = tx.QueryRowContext(ctx, `SELECT sqid, platform, deleted_at FROM accounts WHERE id = ?`, a.ID). |
| - Scan(&sqid, &platform, &deleted) |
| + err = tx.QueryRowContext(ctx, `SELECT sqid, platform, platform_mint, deleted_at FROM accounts WHERE id = ?`, a.ID). |
| + Scan(&sqid, &platform, &mint, &deleted) |
| switch { |
| case errors.Is(err, sql.ErrNoRows): |
| if err := insertLinkedAccountTx(ctx, tx, a, now); err != nil { |
| @@ -608,7 +603,7 @@ func (s *Store) CreateLinkedAccount(ctx context.Context, a NewLinkedAccount, now |
| } |
| case err != nil: |
| return err |
| - case sqid != a.Sqid || platform != a.Platform: |
| + case sqid != a.Sqid || platform != a.Platform || mint == "" || mint != a.MintID: |
| return errLinkedIDTaken |
| case deleted != 0: |
| // This customer was materialized and then deleted before the |
diff --git a/internal/console/platform_store_test.go b/internal/console/platform_store_test.go| index 0633d8d80..952aab4ab 100644 |
| --- a/internal/console/platform_store_test.go |
| +++ b/internal/console/platform_store_test.go |
| @@ -740,20 +740,49 @@ func TestDeletingAMaterializedCustomerRetiresItsPendingMint(t *testing.T) { |
| func TestFinishingOverATombstoneDropsTheMint(t *testing.T) { |
| s := openTestStore(t) |
| ctx := context.Background() |
| + // insertPending writes a promise as raw SQL: ReservePlatformMint refuses a |
| + // mint id a row already carries, and DeleteAccount retires the promise of |
| + // the row it deletes, so only a promise that outlived both reaches here. |
| + insertPending := func(mintID, ref string) { |
| + t.Helper() |
| + if _, err := s.db.ExecContext(ctx, `INSERT INTO platform_pending_mints (mint_id, platform, ref, name, by, created_at) |
| + VALUES (?, 'bcd', ?, 'Customer', 'service:bcd/cms', ?)`, mintID, ref, platformNow.Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // This mint's own account, materialized and then deleted: the finish |
| + // drops the promise and the account stays deleted. |
| c := customerOf("bcd", "bdf", "4812", "aa11") |
| - if _, err := s.EnsureLinkedAccount(c.ID, c.Sqid, c.Name, "bcd", "4812", "", platformNow); err != nil { |
| + if _, err := s.EnsureLinkedAccount(c.ID, c.Sqid, c.Name, "bcd", "4812", "aa11", platformNow); err != nil { |
| t.Fatal(err) |
| } |
| if err := s.DeleteAccount(c.ID, platformNow); err != nil { |
| t.Fatal(err) |
| } |
| - reserveMint(t, s, "bcd", "aa11", "4812") |
| + insertPending("aa11", "4812") |
| if err := s.CreateLinkedAccount(ctx, c, platformNow); !errors.Is(err, ErrAccountGone) { |
| t.Fatalf("finish over a tombstone = %v, want ErrAccountGone", err) |
| } |
| if m := pendingMints(t, s, "bcd"); len(m) != 0 { |
| t.Fatalf("pending mints = %+v, want the finished one gone", m) |
| } |
| + |
| + // Another mint's tombstone at the id is not this mint's account: refused, |
| + // and the promise kept (mint identity, Task 8 fix round 1). |
| + d := customerOf("bcd", "bdg", "4813", "bb22") |
| + if _, err := s.EnsureLinkedAccount(d.ID, d.Sqid, d.Name, "bcd", "4813", "cc33", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.DeleteAccount(d.ID, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + insertPending("bb22", "4813") |
| + if err := s.CreateLinkedAccount(ctx, d, platformNow); !errors.Is(err, errLinkedIDTaken) { |
| + t.Fatalf("finish over another mint's tombstone = %v, want errLinkedIDTaken", err) |
| + } |
| + if m := pendingMints(t, s, "bcd"); len(m) != 1 || m[0].MintID != "bb22" { |
| + t.Fatalf("pending mints = %+v, want bb22 kept", m) |
| + } |
| } |
| func TestReservePlatformMintRefusesADuplicate(t *testing.T) { |
diff --git a/internal/domains/mint.go b/internal/domains/mint.go| index b03006ef3..f8cfe6b27 100644 |
| --- a/internal/domains/mint.go |
| +++ b/internal/domains/mint.go |
| @@ -255,7 +255,7 @@ func MintAccount(ctx context.Context, s release.Store, name, owner string, creat |
| if owner != "" && !ValidAddress(owner) { |
| return 0, "", fmt.Errorf("domains: %q is not a keymail address — expected <user>@<host>, e.g. paul@keymail.dev", owner) |
| } |
| - id, sqid, _, err := mint(ctx, s, AccountManifest{Name: name, Owner: owner}, created, nil) |
| + id, sqid, _, err := mint(ctx, s, AccountManifest{Name: name, Owner: owner}, created, nil, nil) |
| return id, sqid, err |
| } |
| @@ -280,13 +280,25 @@ var ErrBadPlatformLink = errors.New("domains: bad platform link") |
| // The link is checked before the first listing, so a refused mint writes |
| // nothing. The ref is the console's to validate, not this function's. |
| func MintLinkedAccount(ctx context.Context, s release.Store, name, platformSqid, ref, mintID string, created time.Time) (id int64, sqid string, existing bool, err error) { |
| + return MintLinkedAccountIfFree(ctx, s, name, platformSqid, ref, mintID, created, nil) |
| +} |
| + |
| +// MintLinkedAccountIfFree is MintLinkedAccount that asks free about the id |
| +// it is about to write, before every create-only write. A non-nil error |
| +// from free is returned as it is and nothing is written. The console uses it |
| +// to refuse an id its own database already holds for an account the bucket |
| +// has no manifest for: writing there would put a second identity on that |
| +// id. A manifest found by its mint id is returned without asking, since |
| +// nothing is written for it. A nil free asks nothing. |
| +func MintLinkedAccountIfFree(ctx context.Context, s release.Store, name, platformSqid, ref, mintID string, created time.Time, |
| + free func(id int64) error) (id int64, sqid string, existing bool, err error) { |
| if !ValidPlatformLink(platformSqid, mintID) { |
| return 0, "", false, fmt.Errorf("%w: platform %q, mint id %q", ErrBadPlatformLink, platformSqid, mintID) |
| } |
| template := AccountManifest{Name: name, Platform: platformSqid, PlatformRef: ref, PlatformMint: mintID} |
| return mint(ctx, s, template, created, func(m AccountManifest) bool { |
| return !m.Deleted() && m.Platform == platformSqid && m.PlatformMint == mintID |
| - }) |
| + }, free) |
| } |
| // ValidPlatformLink is the one check on a customer account's link, shared by |
| @@ -317,8 +329,10 @@ func validMintID(id string) bool { |
| // share. Each attempt scans the bucket once; a manifest match accepts is |
| // returned as it stands with existing == true, otherwise template is written |
| // create-only at the next free id with its ID, Sqid and CreatedAt filled in. |
| -// A nil match never matches. |
| -func mint(ctx context.Context, s release.Store, template AccountManifest, created time.Time, match func(AccountManifest) bool) (int64, string, bool, error) { |
| +// A nil match never matches. free, when not nil, is asked about each id |
| +// before its write; its error ends the mint with nothing written. |
| +func mint(ctx context.Context, s release.Store, template AccountManifest, created time.Time, match func(AccountManifest) bool, |
| + free func(id int64) error) (int64, string, bool, error) { |
| for attempt := 0; attempt < mintAttempts; attempt++ { |
| manifests, err := scanManifests(ctx, s) |
| if err != nil { |
| @@ -332,6 +346,11 @@ func mint(ctx context.Context, s release.Store, template AccountManifest, create |
| } |
| } |
| id := nextID(manifests) |
| + if free != nil { |
| + if err := free(id); err != nil { |
| + return 0, "", false, err |
| + } |
| + } |
| sqid := Sqid(id) |
| m := template |
| m.ID, m.Sqid, m.CreatedAt = id, sqid, created.UTC() |
diff --git a/internal/domains/mint_test.go b/internal/domains/mint_test.go| index 44368c879..ec52bbfe0 100644 |
| --- a/internal/domains/mint_test.go |
| +++ b/internal/domains/mint_test.go |
| @@ -437,6 +437,35 @@ func TestMintLinkedAccountRetryAfterAFailedPut(t *testing.T) { |
| } |
| } |
| +// free refuses the id the mint is about to write: nothing is written, and |
| +// the refusal comes back as it is. A manifest found by its mint id is |
| +// returned without asking. |
| +func TestMintLinkedAccountIfFreeWritesNothingForAHeldID(t *testing.T) { |
| + ctx := t.Context() |
| + s := linkBucket(t) |
| + before := listAccounts(t, s) |
| + held := errors.New("held") |
| + var asked []int64 |
| + _, _, _, err := domains.MintLinkedAccountIfFree(ctx, s, "shop", "bcd", "4812", mintA, time.Unix(1700000000, 0), |
| + func(id int64) error { asked = append(asked, id); return held }) |
| + if !errors.Is(err, held) || len(asked) != 1 || asked[0] != 50 { |
| + t.Fatalf("mint over a held id = %v, asked %v; want the refusal for id 50", err, asked) |
| + } |
| + if after := listAccounts(t, s); len(after) != len(before) { |
| + t.Fatalf("a refused mint wrote: %v, was %v", after, before) |
| + } |
| + |
| + id, _, existing, err := domains.MintLinkedAccountIfFree(ctx, s, "shop", "bcd", "4812", mintA, time.Unix(1700000000, 0), nil) |
| + if err != nil || existing || id != 50 { |
| + t.Fatalf("mint = %d %v %v", id, existing, err) |
| + } |
| + id2, _, existing, err := domains.MintLinkedAccountIfFree(ctx, s, "shop", "bcd", "4812", mintA, time.Unix(1700000000, 0), |
| + func(int64) error { return held }) |
| + if err != nil || !existing || id2 != id { |
| + t.Fatalf("the found manifest = %d %v %v, want %d found without asking", id2, existing, err, id) |
| + } |
| +} |
| + |
| // A link the console could never honour is refused before anything is |
| // listed or written: a refused mint burns no id. |
| func TestMintLinkedAccountRefusesABadLink(t *testing.T) { |