console: platform grants, pending mints and customer links
The console store for platform accounts (plan Task 4): platform_grants with a generation that every revoke advances, platform_pending_mints for promised customer creates, and the link columns on accounts and cli_tokens. RevokePlatformGrant ends the generation and sweeps the platform's credentials revoked in one transaction, counting only those still unexpired (pre-flight C13). LinkedCustomerCount counts a pending mint that materialization already made once (pre-flight C15). DeleteAccount refuses a platform with a live customer or a pending mint. migrate's feature calls move to migrateFeatures, an ordered list, with migratePlatformAccounts last. EnsureAccount and EnsureLinkedAccount share ensureAccount. The two new tables are classified for the claim SQL gate.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+1,317
−79
internal/console/accountplans.go+3 −0internal/console/ownership.go+17 −0internal/console/platform_store.go+563 −0internal/console/platform_store_test.go+639 −0internal/console/store.go+92 −79internal/console/store_gate.go+3 −0
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go| index c490cff5e..5ce485eb2 100644 |
| --- a/internal/console/accountplans.go |
| +++ b/internal/console/accountplans.go |
| @@ -20,6 +20,9 @@ const ( |
| PlanSourceOperator = "operator" |
| PlanSourceSponsored = "sponsored" |
| PlanSourceBilling = "billing" |
| + // PlanSourcePlatform is a customer account's plan, set by its platform |
| + // account (platform_store.go) from the plans the platform was granted. |
| + PlanSourcePlatform = "platform" |
| ) |
| // ErrAccountGone refuses a plan write for an account that does not exist or |
diff --git a/internal/console/ownership.go b/internal/console/ownership.go| index a2f9d46c1..9f71832d8 100644 |
| --- a/internal/console/ownership.go |
| +++ b/internal/console/ownership.go |
| @@ -785,6 +785,9 @@ func (s *Store) TransferOwnership(accountID int64, from, to string, now time.Tim |
| // "never seen", which is the only way materialization's birth-only adoption |
| // rule stays safe. An account id is spent once; there is no un-deleting one. |
| // |
| +// A platform account with a live customer account or a pending mint is |
| +// refused with ErrPlatformHasCustomers (platform_store.go). |
| +// |
| // Audit rows are deliberately left behind: they are the record of what was |
| // done, and a deletion is not a reason to lose it. |
| func (s *Store) DeleteAccount(accountID int64, now time.Time) error { |
| @@ -803,6 +806,20 @@ func (s *Store) DeleteAccount(accountID int64, now time.Time) error { |
| if apps > 0 { |
| return fmt.Errorf("console: this account still holds %d app(s)", apps) |
| } |
| + // A platform account is never deleted while it has a live customer or a |
| + // promised one (a pending mint): either would be left linked to nothing. |
| + // DeleteAccount takes no ctx; the new query uses the Context form anyway. |
| + var customers int |
| + if err := tx.QueryRowContext(context.Background(), `SELECT |
| + (SELECT COUNT(*) FROM accounts c JOIN accounts p ON c.platform = p.sqid |
| + WHERE p.id = ? AND p.sqid != '' AND c.deleted_at = 0) |
| + + (SELECT COUNT(*) FROM platform_pending_mints m JOIN accounts p ON m.platform = p.sqid |
| + WHERE p.id = ? AND p.sqid != '')`, accountID, accountID).Scan(&customers); err != nil { |
| + return err |
| + } |
| + if customers > 0 { |
| + return ErrPlatformHasCustomers |
| + } |
| for _, stmt := range []string{ |
| `DELETE FROM app_stars WHERE account_id = ?`, |
| `DELETE FROM getting_started_marks WHERE account_id = ?`, |
diff --git a/internal/console/platform_store.go b/internal/console/platform_store.go| new file mode 100644 |
| index 000000000..94c6d91bd |
| --- /dev/null |
| +++ b/internal/console/platform_store.go |
| @@ -0,0 +1,563 @@ |
| +package console |
| + |
| +// Platform accounts' console record (spec 2026-11-19-platform-accounts-design.md). |
| +// |
| +// An operator grants an account the platform role (platform_grants). The |
| +// platform then creates customer accounts linked to it: an accounts row |
| +// whose platform column holds the platform's sqid and whose platform_ref is |
| +// the platform's own reference for the customer. A customer create is |
| +// promised before the bucket is touched (platform_pending_mints) and the |
| +// promise is finished in one transaction (CreateLinkedAccount), so a |
| +// promised customer uses capacity and holds its reference from the moment |
| +// it is promised until it exists. |
| +// |
| +// A grant has a generation. Every credential minted under the grant records |
| +// the generation it was minted in (cli_tokens.platform_generation), and is |
| +// valid only while that generation is the active one (PlatformGenerationLive). |
| +// Revoking a grant ends its generation and sweeps the platform's credentials |
| +// revoked in the same transaction; a re-grant runs under the next generation. |
| +// |
| +// The link column holds the platform's sqid, not its id, so materialization |
| +// never depends on the order accounts are listed in. |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +// A platform grant's states. |
| +const ( |
| + PlatformGrantActive = "active" |
| + PlatformGrantRevoked = "revoked" |
| +) |
| + |
| +// PlatformGrant is an account's platform role, as an operator granted it. |
| +type PlatformGrant struct { |
| + AccountID int64 |
| + State string |
| + Generation int64 // starts at 1; every revoke adds 1 (Astra r1-2) |
| + MaxCustomers int |
| + Plans []string // sorted, deduped; nil with no catalog |
| + DefaultPlan string // "" with no catalog |
| + Reason string |
| + GrantedBy string |
| + GrantedAt time.Time |
| + RevokedBy string |
| + RevokeReason string |
| + RevokedAt time.Time |
| +} |
| + |
| +// LinkedCustomer is one live customer account of a platform. |
| +type LinkedCustomer struct { |
| + ID int64 |
| + Sqid string |
| + Name string |
| + Ref string |
| + CreatedAt time.Time |
| + Owners int // owner memberships; > 0 means claimed |
| +} |
| + |
| +// PendingMint is a customer create the console has promised and not finished (Astra r1-1). |
| +type PendingMint struct { |
| + MintID string // 32 hex, crypto/rand |
| + Platform string |
| + Ref string |
| + Name string |
| + Plan string |
| + PlanReason string |
| + By string |
| + CreatedAt time.Time |
| +} |
| + |
| +// NewLinkedAccount is a customer account CreateLinkedAccount records. Plan |
| +// "" writes no plan row. |
| +type NewLinkedAccount struct { |
| + ID int64 |
| + Sqid string |
| + Name string |
| + Platform string |
| + Ref string |
| + MintID string |
| + Plan string |
| + PlanReason string |
| + By string |
| +} |
| + |
| +var ( |
| + // ErrNotPlatform is an account with no grant row, or one not active. |
| + ErrNotPlatform = errors.New("console: this account is not a platform account") |
| + ErrPlatformHasCustomers = errors.New("console: this platform account still has customer accounts") |
| + ErrPlatformRefTaken = errors.New("console: that reference already names a customer account") |
| +) |
| + |
| +// dbQuerier is the one method both *sql.DB (and the Store's sqlHandle) and |
| +// *sql.Tx have that PlatformGenerationLive needs, so a request's resolution |
| +// and a mint's transaction ask the identical question. |
| +type dbQuerier interface { |
| + QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row |
| +} |
| + |
| +// migratePlatformAccounts creates the platform tables and the link columns. |
| +// Additive and idempotent, called last from Store.migrateFeatures: it alters |
| +// accounts and cli_tokens, which earlier steps create. Migration runs at |
| +// start with no request ctx. |
| +func (s *Store) migratePlatformAccounts() error { |
| + ctx := context.Background() |
| + for _, stmt := range []string{ |
| + `CREATE TABLE IF NOT EXISTS platform_grants ( |
| + account_id INTEGER PRIMARY KEY, |
| + state TEXT NOT NULL, |
| + max_customers INTEGER NOT NULL, |
| + plans TEXT NOT NULL DEFAULT '[]', |
| + default_plan TEXT NOT NULL DEFAULT '', |
| + reason TEXT NOT NULL, |
| + granted_by TEXT NOT NULL, |
| + granted_at INTEGER NOT NULL, |
| + revoked_by TEXT NOT NULL DEFAULT '', |
| + revoked_at INTEGER NOT NULL DEFAULT 0, |
| + revoke_reason TEXT NOT NULL DEFAULT '', |
| + updated_at INTEGER NOT NULL, |
| + generation INTEGER NOT NULL DEFAULT 1 |
| +);`, |
| + `CREATE TABLE IF NOT EXISTS platform_pending_mints ( |
| + mint_id TEXT PRIMARY KEY, |
| + platform TEXT NOT NULL, |
| + ref TEXT NOT NULL DEFAULT '', |
| + name TEXT NOT NULL, |
| + plan TEXT NOT NULL DEFAULT '', |
| + plan_reason TEXT NOT NULL DEFAULT '', |
| + by TEXT NOT NULL, |
| + created_at INTEGER NOT NULL |
| +);`, |
| + `CREATE UNIQUE INDEX IF NOT EXISTS platform_pending_mints_ref ON platform_pending_mints (platform, ref) WHERE ref != '';`, |
| + } { |
| + if _, err := s.db.ExecContext(ctx, stmt); err != nil { |
| + return err |
| + } |
| + } |
| + // Every column defaults to an unlinked account's or an ordinary |
| + // credential's value, so every row written before this reads back as |
| + // exactly what it was. |
| + for _, stmt := range []string{ |
| + `ALTER TABLE accounts ADD COLUMN platform TEXT NOT NULL DEFAULT ''`, // the platform account's sqid |
| + `ALTER TABLE accounts ADD COLUMN platform_ref TEXT NOT NULL DEFAULT ''`, // the platform's reference for the customer |
| + `ALTER TABLE accounts ADD COLUMN platform_mint TEXT NOT NULL DEFAULT ''`, // the manifest's platform_mint (pre-flight C15) |
| + `ALTER TABLE cli_tokens ADD COLUMN platform_account_id INTEGER NOT NULL DEFAULT 0`, |
| + `ALTER TABLE cli_tokens ADD COLUMN platform_generation INTEGER NOT NULL DEFAULT 0`, // Astra r1-2 |
| + } { |
| + if _, err := s.db.ExecContext(ctx, stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| + return err |
| + } |
| + } |
| + for _, stmt := range []string{ |
| + `CREATE INDEX IF NOT EXISTS accounts_platform ON accounts (platform) WHERE platform != '';`, |
| + `CREATE UNIQUE INDEX IF NOT EXISTS accounts_platform_ref ON accounts (platform, platform_ref) |
| + WHERE platform_ref != '' AND deleted_at = 0;`, |
| + `CREATE INDEX IF NOT EXISTS cli_tokens_platform ON cli_tokens (platform_account_id) WHERE platform_account_id != 0;`, |
| + } { |
| + if _, err := s.db.ExecContext(ctx, stmt); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// PlatformGrant is the account's grant, or nil, nil when it has none. |
| +func (s *Store) PlatformGrant(ctx context.Context, accountID int64) (*PlatformGrant, error) { |
| + var g PlatformGrant |
| + var plans string |
| + var granted, revoked int64 |
| + err := s.db.QueryRowContext(ctx, `SELECT account_id, state, generation, max_customers, plans, default_plan, |
| + reason, granted_by, granted_at, revoked_by, revoke_reason, revoked_at |
| + FROM platform_grants WHERE account_id = ?`, accountID).Scan(&g.AccountID, &g.State, &g.Generation, |
| + &g.MaxCustomers, &plans, &g.DefaultPlan, &g.Reason, &g.GrantedBy, &granted, &g.RevokedBy, |
| + &g.RevokeReason, &revoked) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + if err := json.Unmarshal([]byte(plans), &g.Plans); err != nil { |
| + return nil, err |
| + } |
| + if len(g.Plans) == 0 { |
| + g.Plans = nil |
| + } |
| + g.GrantedAt = time.Unix(granted, 0) |
| + if revoked != 0 { |
| + g.RevokedAt = time.Unix(revoked, 0) |
| + } |
| + return &g, nil |
| +} |
| + |
| +// PutPlatformGrant grants the account the platform role, or changes its |
| +// grant: the row is active from now, granted by g.GrantedBy at now, and any |
| +// revoke fields are cleared. g's State, Generation and time fields are not |
| +// read. It never changes the generation, so a re-grant after a revoke runs |
| +// under the generation the revoke moved to. Plans are stored sorted and |
| +// deduped. A deleted or unknown account is ErrAccountGone. Who may hold a |
| +// grant (never ops, never a customer account) is the caller's check. |
| +func (s *Store) PutPlatformGrant(ctx context.Context, g PlatformGrant, now time.Time) error { |
| + plans := slices.Compact(slices.Sorted(slices.Values(g.Plans))) |
| + if plans == nil { |
| + plans = []string{} |
| + } |
| + pj, err := json.Marshal(plans) |
| + if err != nil { |
| + return err |
| + } |
| + res, err := s.db.ExecContext(ctx, `INSERT INTO platform_grants |
| + (account_id, state, max_customers, plans, default_plan, reason, granted_by, granted_at, updated_at) |
| + SELECT ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM accounts WHERE id = ? AND deleted_at = 0) |
| + ON CONFLICT(account_id) DO UPDATE SET state = excluded.state, max_customers = excluded.max_customers, |
| + plans = excluded.plans, default_plan = excluded.default_plan, reason = excluded.reason, |
| + granted_by = excluded.granted_by, granted_at = excluded.granted_at, updated_at = excluded.updated_at, |
| + revoked_by = '', revoked_at = 0, revoke_reason = ''`, |
| + g.AccountID, PlatformGrantActive, g.MaxCustomers, string(pj), g.DefaultPlan, g.Reason, g.GrantedBy, |
| + now.Unix(), now.Unix(), g.AccountID) |
| + if err != nil { |
| + return err |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n == 0 { |
| + if err == nil { |
| + err = ErrAccountGone |
| + } |
| + return err |
| + } |
| + return nil |
| +} |
| + |
| +// RevokePlatformGrant ends the account's grant and its generation, in one |
| +// transaction: the grant is revoked, its generation moves on, and every |
| +// credential of the platform (its platform-role service credentials and |
| +// every per-customer credential minted under it) is marked revoked. |
| +// |
| +// Two rules, two jobs. The generation is authorization: every resolution |
| +// and every mint asks PlatformGenerationLive, so a mint in flight across |
| +// the revoke is refused even though its row did not exist when the sweep |
| +// ran. The sweep is bookkeeping: listing, rotation and name reservation |
| +// read revoked_at, and must agree with authentication (Astra r1-2, r2-2). |
| +// |
| +// credentials counts the rows that were still working, so "N credentials |
| +// stopped working" counts what did: expired rows are revoked too but not |
| +// counted (pre-flight C13). An account with no active grant is |
| +// ErrNotPlatform. |
| +func (s *Store) RevokePlatformGrant(ctx context.Context, accountID int64, by, reason string, now time.Time) (credentials int, err error) { |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return 0, err |
| + } |
| + defer tx.Rollback() |
| + res, err := tx.ExecContext(ctx, `UPDATE platform_grants SET state = ?, generation = generation + 1, |
| + revoked_by = ?, revoked_at = ?, revoke_reason = ?, updated_at = ? |
| + WHERE account_id = ? AND state = ?`, |
| + PlatformGrantRevoked, by, now.Unix(), reason, now.Unix(), accountID, PlatformGrantActive) |
| + if err != nil { |
| + return 0, err |
| + } |
| + if n, err := res.RowsAffected(); err != nil { |
| + return 0, err |
| + } else if n == 0 { |
| + return 0, ErrNotPlatform |
| + } |
| + // kind 'platform' is a per-customer credential (bound to the customer's |
| + // account_id, its platform in platform_account_id); a platform-role |
| + // service credential is bound to the platform's own account_id. |
| + const platformCreds = `revoked_at = 0 AND ((kind = 'platform' AND platform_account_id = ?) |
| + OR (kind = ? AND role = ? AND account_id = ?))` |
| + args := []any{accountID, cliKindService, string(svcrole.Platform), accountID} |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM cli_tokens WHERE `+platformCreds+` |
| + AND (expires_at = 0 OR expires_at > ?)`, append(args, now.Unix())...).Scan(&credentials); err != nil { |
| + return 0, err |
| + } |
| + if _, err := tx.ExecContext(ctx, `UPDATE cli_tokens SET revoked_at = ? WHERE `+platformCreds, |
| + append([]any{now.Unix()}, args...)...); err != nil { |
| + return 0, err |
| + } |
| + return credentials, tx.Commit() |
| +} |
| + |
| +// PlatformGenerationLive is the one check that a credential minted under a |
| +// platform's grant generation still works (Astra r1-2): the grant is active, |
| +// at exactly that generation, and the platform account is live. It answers |
| +// the platform's sqid. q is the pool or a transaction, so the resolver and |
| +// the mint transactions ask the identical question. Any error is "not live". |
| +func (s *Store) PlatformGenerationLive(ctx context.Context, q dbQuerier, platformAccountID, generation int64) (platformSqid string, ok bool) { |
| + err := q.QueryRowContext(ctx, `SELECT p.sqid FROM platform_grants g JOIN accounts p ON p.id = g.account_id |
| + WHERE g.account_id = ? AND g.state = ? AND g.generation = ? AND p.deleted_at = 0`, |
| + platformAccountID, PlatformGrantActive, generation).Scan(&platformSqid) |
| + if err != nil || platformSqid == "" { |
| + return "", false |
| + } |
| + return platformSqid, true |
| +} |
| + |
| +// AccountPlatform is the account's link: its platform's sqid and the |
| +// platform's reference for it. Both are "" for an unlinked or unknown |
| +// account. |
| +func (s *Store) AccountPlatform(ctx context.Context, accountID int64) (platformSqid, ref string, err error) { |
| + err = s.db.QueryRowContext(ctx, `SELECT platform, platform_ref FROM accounts WHERE id = ?`, |
| + accountID).Scan(&platformSqid, &ref) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return "", "", nil |
| + } |
| + return platformSqid, ref, err |
| +} |
| + |
| +// linkedCustomerSelect reads LinkedCustomer rows: live accounts of one |
| +// platform, with their owner count. Callers add their own conditions. |
| +const linkedCustomerSelect = `SELECT a.id, a.sqid, a.name, a.platform_ref, a.created_at, |
| + (SELECT COUNT(*) FROM memberships m WHERE m.account_id = a.id AND m.role = ?) |
| + FROM accounts a WHERE a.platform = ? AND a.platform != '' AND a.deleted_at = 0` |
| + |
| +func scanLinkedCustomer(sc interface{ Scan(...any) error }) (*LinkedCustomer, error) { |
| + var c LinkedCustomer |
| + var created int64 |
| + if err := sc.Scan(&c.ID, &c.Sqid, &c.Name, &c.Ref, &created, &c.Owners); err != nil { |
| + return nil, err |
| + } |
| + c.CreatedAt = time.Unix(created, 0) |
| + return &c, nil |
| +} |
| + |
| +// LinkedCustomers lists the platform's live customer accounts, by id. |
| +func (s *Store) LinkedCustomers(ctx context.Context, platformSqid string) ([]LinkedCustomer, error) { |
| + rows, err := s.db.QueryContext(ctx, linkedCustomerSelect+` ORDER BY a.id`, RoleOwner, platformSqid) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []LinkedCustomer |
| + for rows.Next() { |
| + c, err := scanLinkedCustomer(rows) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, *c) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// LinkedCustomer is the platform's live customer with this sqid, or nil when |
| +// there is none: unknown, deleted, unlinked, or another platform's. |
| +func (s *Store) LinkedCustomer(ctx context.Context, platformSqid, customerSqid string) (*LinkedCustomer, error) { |
| + return s.linkedCustomerWhere(ctx, ` AND a.sqid = ?`, platformSqid, customerSqid) |
| +} |
| + |
| +// LinkedCustomerByRef is the platform's live customer with this reference, |
| +// or nil. An empty ref names nobody. |
| +func (s *Store) LinkedCustomerByRef(ctx context.Context, platformSqid, ref string) (*LinkedCustomer, error) { |
| + if ref == "" { |
| + return nil, nil |
| + } |
| + return s.linkedCustomerWhere(ctx, ` AND a.platform_ref = ?`, platformSqid, ref) |
| +} |
| + |
| +func (s *Store) linkedCustomerWhere(ctx context.Context, cond, platformSqid, value string) (*LinkedCustomer, error) { |
| + c, err := scanLinkedCustomer(s.db.QueryRowContext(ctx, linkedCustomerSelect+cond, RoleOwner, platformSqid, value)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + return c, err |
| +} |
| + |
| +// LinkedCustomerCount is how many customers count against the platform's |
| +// max_customers: its live customer accounts plus the customers it has been |
| +// promised and not given (Astra r1-1). A pending mint whose account |
| +// materialization already made (a live row carrying its mint id) is that |
| +// account, so it counts once (pre-flight C15). |
| +func (s *Store) LinkedCustomerCount(ctx context.Context, platformSqid string) (int, error) { |
| + if platformSqid == "" { |
| + return 0, nil |
| + } |
| + var n int |
| + err := s.db.QueryRowContext(ctx, `SELECT |
| + (SELECT COUNT(*) FROM accounts WHERE platform = ? AND deleted_at = 0) |
| + + (SELECT COUNT(*) FROM platform_pending_mints m WHERE m.platform = ? AND NOT EXISTS |
| + (SELECT 1 FROM accounts a WHERE a.platform = m.platform AND a.platform_mint = m.mint_id AND a.deleted_at = 0))`, |
| + platformSqid, platformSqid).Scan(&n) |
| + return n, err |
| +} |
| + |
| +// ReservePlatformMint records a promised customer create before the bucket |
| +// is touched. A non-empty ref already held by a live customer of the |
| +// platform, or by another of its pending mints, is ErrPlatformRefTaken; the |
| +// partial unique index on pending refs backs the check. |
| +func (s *Store) ReservePlatformMint(ctx context.Context, m PendingMint) error { |
| + if m.MintID == "" || m.Platform == "" { |
| + return errors.New("console: a pending mint needs a mint id and a platform") |
| + } |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if m.Ref != "" { |
| + var held int |
| + if err := tx.QueryRowContext(ctx, `SELECT |
| + (SELECT COUNT(*) FROM accounts WHERE platform = ? AND platform_ref = ? AND deleted_at = 0) |
| + + (SELECT COUNT(*) FROM platform_pending_mints WHERE platform = ? AND ref = ?)`, |
| + m.Platform, m.Ref, m.Platform, m.Ref).Scan(&held); err != nil { |
| + return err |
| + } |
| + if held > 0 { |
| + return ErrPlatformRefTaken |
| + } |
| + } |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO platform_pending_mints |
| + (mint_id, platform, ref, name, plan, plan_reason, by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, |
| + m.MintID, m.Platform, m.Ref, m.Name, m.Plan, m.PlanReason, m.By, m.CreatedAt.Unix()); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// PendingPlatformMints lists the platform's unfinished customer creates, |
| +// oldest first. |
| +func (s *Store) PendingPlatformMints(ctx context.Context, platformSqid string) ([]PendingMint, error) { |
| + rows, err := s.db.QueryContext(ctx, `SELECT mint_id, platform, ref, name, plan, plan_reason, by, created_at |
| + FROM platform_pending_mints WHERE platform = ? ORDER BY created_at, mint_id`, platformSqid) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []PendingMint |
| + for rows.Next() { |
| + var m PendingMint |
| + var created int64 |
| + if err := rows.Scan(&m.MintID, &m.Platform, &m.Ref, &m.Name, &m.Plan, &m.PlanReason, &m.By, &created); err != nil { |
| + return nil, err |
| + } |
| + m.CreatedAt = time.Unix(created, 0) |
| + out = append(out, m) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// 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. An id held by any other account is an error, and the pending |
| +// mint is kept. |
| +// |
| +// 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 |
| +// D9). A ref a live customer of the platform already holds is |
| +// ErrPlatformRefTaken. |
| +func (s *Store) CreateLinkedAccount(ctx context.Context, a NewLinkedAccount, now time.Time) error { |
| + if a.Platform == "" { |
| + return errors.New("console: a linked account needs a platform") |
| + } |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + var sqid, platform string |
| + var deleted int64 |
| + err = tx.QueryRowContext(ctx, `SELECT sqid, platform, deleted_at FROM accounts WHERE id = ?`, a.ID). |
| + Scan(&sqid, &platform, &deleted) |
| + switch { |
| + case errors.Is(err, sql.ErrNoRows): |
| + if err := insertLinkedAccountTx(ctx, tx, a, now); err != nil { |
| + return err |
| + } |
| + case err != nil: |
| + return err |
| + case sqid != a.Sqid || platform != a.Platform || deleted != 0: |
| + return errors.New("console: that account id belongs to another account") |
| + default: |
| + // Materialized first (or finished before): only a default plan |
| + // gives way to the platform's. |
| + var source string |
| + err := tx.QueryRowContext(ctx, `SELECT source FROM account_plans WHERE account_id = ?`, a.ID).Scan(&source) |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + if errors.Is(err, sql.ErrNoRows) || source == PlanSourceDefault { |
| + if err := setPlatformPlanTx(ctx, tx, a, now); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM platform_pending_mints WHERE mint_id = ?`, a.MintID); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// insertLinkedAccountTx is CreateLinkedAccount's new row and its plan. |
| +func insertLinkedAccountTx(ctx context.Context, tx *sql.Tx, a NewLinkedAccount, now time.Time) error { |
| + if a.Ref != "" { |
| + var held int |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM accounts |
| + WHERE platform = ? AND platform_ref = ? AND deleted_at = 0`, a.Platform, a.Ref).Scan(&held); err != nil { |
| + return err |
| + } |
| + if held > 0 { |
| + return ErrPlatformRefTaken |
| + } |
| + } |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO accounts |
| + (id, sqid, name, created_at, platform, platform_ref, platform_mint) VALUES (?, ?, ?, ?, ?, ?, ?)`, |
| + a.ID, a.Sqid, a.Name, now.Unix(), a.Platform, a.Ref, a.MintID); err != nil { |
| + return err |
| + } |
| + return setPlatformPlanTx(ctx, tx, a, now) |
| +} |
| + |
| +// setPlatformPlanTx writes the customer's plan row, source platform, through |
| +// the shared plan write (accountPlanUpsertSQL). Plan "" writes nothing. |
| +func setPlatformPlanTx(ctx context.Context, tx *sql.Tx, a NewLinkedAccount, now time.Time) error { |
| + if a.Plan == "" { |
| + return nil |
| + } |
| + args, err := accountPlanUpsertArgs(a.ID, a.Plan, nil, PlanSourcePlatform, nil, a.PlanReason, a.By, now) |
| + if err != nil { |
| + return err |
| + } |
| + var rev int64 |
| + err = tx.QueryRowContext(ctx, accountPlanUpsertSQL, args...).Scan(&rev) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return ErrAccountGone |
| + } |
| + return err |
| +} |
| + |
| +// EnsureLinkedAccount is EnsureAccount for a customer account materialized |
| +// from its manifest: the same birth-only INSERT OR IGNORE, with the link |
| +// (platform sqid, ref, and the manifest's platform_mint, pre-flight C15) |
| +// kept on the row. A ref a live customer of the same platform already holds |
| +// is dropped to "" so the birth still happens. No launch sponsorship: a |
| +// customer's plan is its platform's. |
| +func (s *Store) EnsureLinkedAccount(id int64, sqid, name, platformSqid, ref, mintID string, created time.Time) (added bool, err error) { |
| + return s.ensureAccount(id, sqid, name, accountLink{platform: platformSqid, ref: ref, mint: mintID}, created) |
| +} |
| + |
| +// RenameAccount sets a live account's name. A deleted or unknown account is |
| +// ErrAccountGone. |
| +func (s *Store) RenameAccount(ctx context.Context, accountID int64, name string) error { |
| + res, err := s.db.ExecContext(ctx, `UPDATE accounts SET name = ? WHERE id = ? AND deleted_at = 0`, name, accountID) |
| + if err != nil { |
| + return err |
| + } |
| + n, err := res.RowsAffected() |
| + if err != nil { |
| + return err |
| + } |
| + if n == 0 { |
| + return ErrAccountGone |
| + } |
| + return nil |
| +} |
diff --git a/internal/console/platform_store_test.go b/internal/console/platform_store_test.go| new file mode 100644 |
| index 000000000..93f640fb8 |
| --- /dev/null |
| +++ b/internal/console/platform_store_test.go |
| @@ -0,0 +1,639 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "path/filepath" |
| + "reflect" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// platformNow is the platform store tests' clock, in whole seconds so the |
| +// stored times read back equal. |
| +var platformNow = time.Unix(1_700_000_000, 0) |
| + |
| +// newPlatform records a platform account with sqid and an owner, and returns |
| +// its id. |
| +func newPlatform(t *testing.T, s *Store, sqid string) int64 { |
| + t.Helper() |
| + id := testAccountID() |
| + if err := s.CreateAccount(id, sqid, "Platform "+sqid, "owner-"+sqid+"@example.com", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + return id |
| +} |
| + |
| +// grantPlatform gives the account an active grant with no catalog. |
| +func grantPlatform(t *testing.T, s *Store, id int64) { |
| + t.Helper() |
| + if err := s.PutPlatformGrant(context.Background(), PlatformGrant{AccountID: id, MaxCustomers: 10, |
| + Reason: "contract", GrantedBy: "operator@example.com"}, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// reserveMint promises a customer of platform under mintID. |
| +func reserveMint(t *testing.T, s *Store, platform, mintID, ref string) { |
| + t.Helper() |
| + if err := s.ReservePlatformMint(context.Background(), PendingMint{MintID: mintID, Platform: platform, Ref: ref, |
| + Name: "Customer " + ref, By: "service:" + platform + "/cms", CreatedAt: platformNow}); err != nil { |
| + t.Fatalf("ReservePlatformMint(%s, %q): %v", mintID, ref, err) |
| + } |
| +} |
| + |
| +// linkedCount is LinkedCustomerCount, failing the test on error. |
| +func linkedCount(t *testing.T, s *Store, platform string) int { |
| + t.Helper() |
| + n, err := s.LinkedCustomerCount(context.Background(), platform) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// pendingMints is PendingPlatformMints, failing the test on error. |
| +func pendingMints(t *testing.T, s *Store, platform string) []PendingMint { |
| + t.Helper() |
| + m, err := s.PendingPlatformMints(context.Background(), platform) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return m |
| +} |
| + |
| +// customerOf is a NewLinkedAccount for platform, finishing mintID. |
| +func customerOf(platform, sqid, ref, mintID string) NewLinkedAccount { |
| + return NewLinkedAccount{ID: testAccountID(), Sqid: sqid, Name: "Customer " + sqid, Platform: platform, |
| + Ref: ref, MintID: mintID, Plan: "personal", PlanReason: "platform " + platform, By: "service:" + platform + "/cms"} |
| +} |
| + |
| +func TestPlatformGrantRoundTrip(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + p := newPlatform(t, s, "bcd") |
| + if g, err := s.PlatformGrant(ctx, p); err != nil || g != nil { |
| + t.Fatalf("PlatformGrant before any grant = %+v, %v; want nil, nil", g, err) |
| + } |
| + put := PlatformGrant{AccountID: p, MaxCustomers: 50, Plans: []string{"team", "personal", "team"}, |
| + DefaultPlan: "personal", Reason: "signed the reseller contract", GrantedBy: "operator@example.com"} |
| + if err := s.PutPlatformGrant(ctx, put, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := PlatformGrant{AccountID: p, State: PlatformGrantActive, Generation: 1, MaxCustomers: 50, |
| + Plans: []string{"personal", "team"}, DefaultPlan: "personal", Reason: "signed the reseller contract", |
| + GrantedBy: "operator@example.com", GrantedAt: platformNow} |
| + g, err := s.PlatformGrant(ctx, p) |
| + if err != nil || g == nil || !reflect.DeepEqual(*g, want) { |
| + t.Fatalf("PlatformGrant = %+v, %v; want %+v", g, err, want) |
| + } |
| + |
| + // A revoke, then a re-grant: active again, the revoke fields cleared, |
| + // and the generation the revoke moved to (Put never changes it). |
| + if _, err := s.RevokePlatformGrant(ctx, p, "operator@example.com", "contract ended", platformNow.Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + later := platformNow.Add(2 * time.Hour) |
| + if err := s.PutPlatformGrant(ctx, PlatformGrant{AccountID: p, MaxCustomers: 5, Reason: "renewed", |
| + GrantedBy: "other@example.com"}, later); err != nil { |
| + t.Fatal(err) |
| + } |
| + want = PlatformGrant{AccountID: p, State: PlatformGrantActive, Generation: 2, MaxCustomers: 5, |
| + Reason: "renewed", GrantedBy: "other@example.com", GrantedAt: later} |
| + g, err = s.PlatformGrant(ctx, p) |
| + if err != nil || g == nil || !reflect.DeepEqual(*g, want) { |
| + t.Fatalf("PlatformGrant after re-grant = %+v, %v; want %+v", g, err, want) |
| + } |
| + // A second Put on an active grant keeps the generation too. |
| + if err := s.PutPlatformGrant(ctx, PlatformGrant{AccountID: p, MaxCustomers: 6, Reason: "more", |
| + GrantedBy: "other@example.com"}, later); err != nil { |
| + t.Fatal(err) |
| + } |
| + if g, err := s.PlatformGrant(ctx, p); err != nil || g.Generation != 2 || g.MaxCustomers != 6 { |
| + t.Fatalf("PlatformGrant after a second Put = %+v, %v; want generation 2, max 6", g, err) |
| + } |
| +} |
| + |
| +// insertToken writes a cli_tokens row with the columns the revoke sweep reads. |
| +func insertToken(t *testing.T, s *Store, hash, kind, role string, accountID, platformID int64, expires time.Time) { |
| + t.Helper() |
| + var exp int64 |
| + if !expires.IsZero() { |
| + exp = expires.Unix() |
| + } |
| + if _, err := s.db.ExecContext(context.Background(), `INSERT INTO cli_tokens |
| + (token_hash, address, created_at, expires_at, kind, account_id, role, name, platform_account_id, platform_generation) |
| + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`, hash, "svc@example.com", platformNow.Unix(), exp, kind, accountID, role, |
| + hash, platformID); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func tokenRevokedAt(t *testing.T, s *Store, hash string) int64 { |
| + t.Helper() |
| + var at int64 |
| + if err := s.db.QueryRowContext(context.Background(), `SELECT revoked_at FROM cli_tokens WHERE token_hash = ?`, |
| + hash).Scan(&at); err != nil { |
| + t.Fatal(err) |
| + } |
| + return at |
| +} |
| + |
| +func TestRevokePlatformGrantEndsItsGeneration(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + p := newPlatform(t, s, "bcd") |
| + q := newPlatform(t, s, "bcf") |
| + grantPlatform(t, s, p) |
| + grantPlatform(t, s, q) |
| + cust := testAccountID() |
| + revokeAt := platformNow.Add(time.Hour) |
| + insertToken(t, s, "per-customer-1", "platform", "publish", cust, p, revokeAt.Add(time.Hour)) |
| + insertToken(t, s, "per-customer-2", "platform", "deploy", cust, p, revokeAt.Add(time.Minute)) |
| + insertToken(t, s, "platform-cred", cliKindService, "platform", p, 0, time.Time{}) |
| + insertToken(t, s, "publish-cred", cliKindService, "publish", p, 0, time.Time{}) |
| + insertToken(t, s, "other-platform", "platform", "publish", cust, q, revokeAt.Add(time.Hour)) |
| + insertToken(t, s, "expired", "platform", "publish", cust, p, revokeAt.Add(-time.Minute)) |
| + |
| + if sqid, ok := s.PlatformGenerationLive(ctx, s.db, p, 1); !ok || sqid != "bcd" { |
| + t.Fatalf("PlatformGenerationLive(P, 1) before revoke = %q, %v; want bcd, true", sqid, ok) |
| + } |
| + n, err := s.RevokePlatformGrant(ctx, p, "operator@example.com", "contract ended", revokeAt) |
| + if err != nil || n != 3 { |
| + t.Fatalf("RevokePlatformGrant = %d, %v; want 3 (the expired row is not counted)", n, err) |
| + } |
| + g, err := s.PlatformGrant(ctx, p) |
| + if err != nil || g.State != PlatformGrantRevoked || g.Generation != 2 || g.RevokedBy != "operator@example.com" || |
| + g.RevokeReason != "contract ended" || !g.RevokedAt.Equal(revokeAt) { |
| + t.Fatalf("grant after revoke = %+v, %v", g, err) |
| + } |
| + for _, h := range []string{"per-customer-1", "per-customer-2", "platform-cred", "expired"} { |
| + if tokenRevokedAt(t, s, h) != revokeAt.Unix() { |
| + t.Errorf("%s not revoked by the sweep", h) |
| + } |
| + } |
| + for _, h := range []string{"publish-cred", "other-platform"} { |
| + if tokenRevokedAt(t, s, h) != 0 { |
| + t.Errorf("%s revoked; the sweep must not reach it", h) |
| + } |
| + } |
| + if _, ok := s.PlatformGenerationLive(ctx, s.db, p, 1); ok { |
| + t.Fatal("generation 1 still live after the revoke") |
| + } |
| + if _, ok := s.PlatformGenerationLive(ctx, s.db, p, 2); ok { |
| + t.Fatal("generation 2 live while the grant is revoked") |
| + } |
| + if _, ok := s.PlatformGenerationLive(ctx, s.db, q, 1); !ok { |
| + t.Fatal("the other platform's generation ended with this one") |
| + } |
| + // Revoking again finds no active grant, and nothing has one at all. |
| + if _, err := s.RevokePlatformGrant(ctx, p, "operator@example.com", "again", revokeAt); !errors.Is(err, ErrNotPlatform) { |
| + t.Fatalf("second revoke = %v, want ErrNotPlatform", err) |
| + } |
| + if _, err := s.RevokePlatformGrant(ctx, cust, "operator@example.com", "none", revokeAt); !errors.Is(err, ErrNotPlatform) { |
| + t.Fatalf("revoke with no grant = %v, want ErrNotPlatform", err) |
| + } |
| + |
| + grantPlatform(t, s, p) |
| + if sqid, ok := s.PlatformGenerationLive(ctx, s.db, p, 2); !ok || sqid != "bcd" { |
| + t.Fatalf("PlatformGenerationLive(P, 2) after re-grant = %q, %v; want bcd, true", sqid, ok) |
| + } |
| + if _, ok := s.PlatformGenerationLive(ctx, s.db, p, 1); ok { |
| + t.Fatal("generation 1 live again after the re-grant") |
| + } |
| + // The same question inside a transaction. |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer tx.Rollback() |
| + if _, ok := s.PlatformGenerationLive(ctx, tx, p, 2); !ok { |
| + t.Fatal("PlatformGenerationLive on a transaction disagrees with the pool") |
| + } |
| +} |
| + |
| +func TestPlatformGenerationLiveRefusesADeletedPlatform(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + p := newPlatform(t, s, "bcd") |
| + grantPlatform(t, s, p) |
| + if err := s.DeleteAccount(p, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := s.PlatformGenerationLive(ctx, s.db, p, 1); ok { |
| + t.Fatal("a deleted platform's generation is live") |
| + } |
| +} |
| + |
| +func TestPendingMintsCountAndHoldTheirRef(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + newPlatform(t, s, "bcd") |
| + reserveMint(t, s, "bcd", "aa11", "4812") |
| + if n := linkedCount(t, s, "bcd"); n != 1 { |
| + t.Fatalf("count with one pending mint = %d, want 1", n) |
| + } |
| + if err := s.ReservePlatformMint(ctx, PendingMint{MintID: "bb22", Platform: "bcd", Ref: "4812", Name: "Again", |
| + By: "service:bcd/cms", CreatedAt: platformNow}); !errors.Is(err, ErrPlatformRefTaken) { |
| + t.Fatalf("second reservation of ref 4812 = %v, want ErrPlatformRefTaken", err) |
| + } |
| + // Another platform's ref space is its own. |
| + reserveMint(t, s, "bcf", "cc33", "4812") |
| + |
| + c := customerOf("bcd", "bdf", "4812", "aa11") |
| + if err := s.CreateLinkedAccount(ctx, c, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := linkedCount(t, s, "bcd"); n != 1 { |
| + t.Fatalf("count after finishing = %d, want 1", n) |
| + } |
| + if m := pendingMints(t, s, "bcd"); len(m) != 0 { |
| + t.Fatalf("pending mints after finishing = %+v, want none", m) |
| + } |
| + // A live customer holds its ref too. |
| + if err := s.ReservePlatformMint(ctx, PendingMint{MintID: "dd44", Platform: "bcd", Ref: "4812", Name: "Again", |
| + By: "service:bcd/cms", CreatedAt: platformNow}); !errors.Is(err, ErrPlatformRefTaken) { |
| + t.Fatalf("reservation of a live customer's ref = %v, want ErrPlatformRefTaken", err) |
| + } |
| + // Finishing twice is a no-op. |
| + before, _ := s.AccountPlan(c.ID) |
| + if err := s.CreateLinkedAccount(ctx, c, platformNow.Add(time.Hour)); err != nil { |
| + t.Fatalf("finishing twice = %v, want nil", err) |
| + } |
| + after, _ := s.AccountPlan(c.ID) |
| + if n := linkedCount(t, s, "bcd"); n != 1 || before.Revision != after.Revision || !after.UpdatedAt.Equal(before.UpdatedAt) { |
| + t.Fatalf("finishing twice changed something: count %d, plan %+v -> %+v", n, before, after) |
| + } |
| + // Ref-less mints never collide with each other. |
| + reserveMint(t, s, "bcd", "ee55", "") |
| + reserveMint(t, s, "bcd", "ff66", "") |
| + if m := pendingMints(t, s, "bcd"); len(m) != 2 || m[0].MintID != "ee55" || m[1].MintID != "ff66" { |
| + t.Fatalf("pending mints = %+v, want ee55 then ff66", m) |
| + } |
| + if n := linkedCount(t, s, "bcd"); n != 3 { |
| + t.Fatalf("count = %d, want 3", n) |
| + } |
| +} |
| + |
| +func TestPendingPlatformMintsRoundTrip(t *testing.T) { |
| + s := openTestStore(t) |
| + m := PendingMint{MintID: "0123456789abcdef0123456789abcdef", Platform: "bcd", Ref: "4812", Name: "Shop", |
| + Plan: "personal", PlanReason: "platform bcd", By: "service:bcd/cms", CreatedAt: platformNow} |
| + if err := s.ReservePlatformMint(context.Background(), m); err != nil { |
| + t.Fatal(err) |
| + } |
| + older := m |
| + older.MintID, older.Ref, older.CreatedAt = "ffff", "", platformNow.Add(-time.Minute) |
| + if err := s.ReservePlatformMint(context.Background(), older); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := pendingMints(t, s, "bcd"); !reflect.DeepEqual(got, []PendingMint{older, m}) { |
| + t.Fatalf("PendingPlatformMints = %+v, want %+v oldest first", got, []PendingMint{older, m}) |
| + } |
| + if got := pendingMints(t, s, ""); len(got) != 0 { |
| + t.Fatalf("PendingPlatformMints(\"\") = %+v, want none", got) |
| + } |
| +} |
| + |
| +func TestCreateLinkedAccountFinishesOverAMaterializedRow(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + newPlatform(t, s, "bcd") |
| + reserveMint(t, s, "bcd", "aa11", "4812") |
| + c := customerOf("bcd", "bdf", "4812", "aa11") |
| + if added, err := s.EnsureLinkedAccount(c.ID, c.Sqid, c.Name, "bcd", "4812", "aa11", platformNow); err != nil || !added { |
| + t.Fatalf("EnsureLinkedAccount = %v, %v", added, err) |
| + } |
| + if _, err := s.EnsureDefaultPlans("free", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row, err := s.AccountPlan(c.ID); err != nil || row == nil || row.Source != PlanSourceDefault { |
| + t.Fatalf("materialized plan row = %+v, %v; want the default row", row, err) |
| + } |
| + if err := s.CreateLinkedAccount(ctx, c, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err := s.AccountPlan(c.ID) |
| + if err != nil || row == nil || row.Source != PlanSourcePlatform || row.Plan != "personal" { |
| + t.Fatalf("plan row after finishing = %+v, %v; want platform personal", row, err) |
| + } |
| + if m := pendingMints(t, s, "bcd"); len(m) != 0 { |
| + t.Fatalf("pending mints = %+v, want none", m) |
| + } |
| + if list, err := s.LinkedCustomers(ctx, "bcd"); err != nil || len(list) != 1 || list[0].ID != c.ID { |
| + t.Fatalf("LinkedCustomers = %+v, %v; want only %d", list, err, c.ID) |
| + } |
| + |
| + // A plan the platform did not set (an operator's) is never replaced. |
| + reserveMint(t, s, "bcd", "bb22", "4813") |
| + d := customerOf("bcd", "bdg", "4813", "bb22") |
| + if _, err := s.EnsureLinkedAccount(d.ID, d.Sqid, d.Name, "bcd", "4813", "bb22", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.SetAccountPlan(d.ID, "team", nil, PlanSourceOperator, nil, "deal", "operator@example.com", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.CreateLinkedAccount(ctx, d, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row, err := s.AccountPlan(d.ID); err != nil || row.Source != PlanSourceOperator || row.Plan != "team" { |
| + t.Fatalf("operator plan after finishing = %+v, %v; want it kept", row, err) |
| + } |
| + |
| + // An id that belongs to another account is refused, and the promise kept. |
| + reserveMint(t, s, "bcd", "cc33", "4814") |
| + clash := customerOf("bcd", "bdh", "4814", "cc33") |
| + clash.ID = d.ID |
| + if err := s.CreateLinkedAccount(ctx, clash, platformNow); err == nil { |
| + t.Fatal("CreateLinkedAccount over another account's id succeeded") |
| + } |
| + if m := pendingMints(t, s, "bcd"); len(m) != 1 || m[0].MintID != "cc33" { |
| + t.Fatalf("pending mints after a refused finish = %+v, want cc33 kept", m) |
| + } |
| +} |
| + |
| +func TestLinkedCustomerCountSkipsAMaterializedPendingMint(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + newPlatform(t, s, "bcd") |
| + reserveMint(t, s, "bcd", "aa11", "4812") |
| + if n := linkedCount(t, s, "bcd"); n != 1 { |
| + t.Fatalf("count = %d, want 1", n) |
| + } |
| + c := customerOf("bcd", "bdf", "4812", "aa11") |
| + if _, err := s.EnsureLinkedAccount(c.ID, c.Sqid, c.Name, "bcd", "4812", "aa11", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := linkedCount(t, s, "bcd"); n != 1 { |
| + t.Fatalf("count after the restart birth = %d, want 1", n) |
| + } |
| + if err := s.CreateLinkedAccount(ctx, c, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n, m := linkedCount(t, s, "bcd"), pendingMints(t, s, "bcd"); n != 1 || len(m) != 0 { |
| + t.Fatalf("after finishing: count %d, pending %+v; want 1, none", n, m) |
| + } |
| + |
| + // A ref-less mint materialized the same way also counts once. |
| + reserveMint(t, s, "bcd", "bb22", "") |
| + d := customerOf("bcd", "bdg", "", "bb22") |
| + if _, err := s.EnsureLinkedAccount(d.ID, d.Sqid, d.Name, "bcd", "", "bb22", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := linkedCount(t, s, "bcd"); n != 2 { |
| + t.Fatalf("count with a materialized ref-less mint = %d, want 2", n) |
| + } |
| +} |
| + |
| +func TestCreateLinkedAccountHasNoMembersAndAPlatformPlan(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + newPlatform(t, s, "bcd") |
| + // The launch sponsorship rule is recorded, and every account below is |
| + // created before its cutoff: an ordinary insert would be sponsored. |
| + if _, err := SettleLaunchSponsorship(s, sponsorCatalog(t, sponsorCutoffAt), planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + reserveMint(t, s, "bcd", "aa11", "4812") |
| + c := customerOf("bcd", "bdf", "4812", "aa11") |
| + if err := s.CreateLinkedAccount(ctx, c, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m, err := s.Members(c.ID); err != nil || len(m) != 0 { |
| + t.Fatalf("Members = %+v, %v; want none", m, err) |
| + } |
| + if p, ref, err := s.AccountPlatform(ctx, c.ID); err != nil || p != "bcd" || ref != "4812" { |
| + t.Fatalf("AccountPlatform = %q, %q, %v; want bcd, 4812", p, ref, err) |
| + } |
| + row, err := s.AccountPlan(c.ID) |
| + if err != nil || row == nil || row.Source != PlanSourcePlatform || row.Plan != "personal" || |
| + row.UpdatedBy != "service:bcd/cms" || row.Reason != "platform bcd" || row.Sponsored != nil { |
| + t.Fatalf("AccountPlan = %+v, %v", row, err) |
| + } |
| + // With no plan, no row at all: the launch rule wrote nothing either. |
| + reserveMint(t, s, "bcd", "bb22", "4813") |
| + d := customerOf("bcd", "bdg", "4813", "bb22") |
| + d.Plan, d.PlanReason = "", "" |
| + if err := s.CreateLinkedAccount(ctx, d, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row, err := s.AccountPlan(d.ID); err != nil || row != nil { |
| + t.Fatalf("AccountPlan with no plan = %+v, %v; want nil", row, err) |
| + } |
| + // Nor does a materialized birth get sponsored. |
| + e := testAccountID() |
| + if _, err := s.EnsureLinkedAccount(e, "bdh", "Born", "bcd", "4814", "cc33", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row, err := s.AccountPlan(e); err != nil || row != nil { |
| + t.Fatalf("AccountPlan of a materialized customer = %+v, %v; want nil", row, err) |
| + } |
| + // An unlinked account still is. |
| + if _, err := s.EnsureAccount(testAccountID(), "bdj", "Ordinary", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if a, err := s.AccountBySqid("bdj"); err != nil || a == nil { |
| + t.Fatal(a, err) |
| + } else if row, err := s.AccountPlan(a.ID); err != nil || row == nil || row.Source != PlanSourceSponsored { |
| + t.Fatalf("an unlinked birth's plan = %+v, %v; want sponsored", row, err) |
| + } |
| + // An unlinked account reads as unlinked; an unknown one too. |
| + if p, ref, err := s.AccountPlatform(ctx, OpsAccountID); err != nil || p != "" || ref != "" { |
| + t.Fatalf("AccountPlatform(ops) = %q, %q, %v", p, ref, err) |
| + } |
| + if p, ref, err := s.AccountPlatform(ctx, 999_999); err != nil || p != "" || ref != "" { |
| + t.Fatalf("AccountPlatform(unknown) = %q, %q, %v", p, ref, err) |
| + } |
| +} |
| + |
| +func TestLinkedCustomerRefIsUniquePerPlatform(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + newPlatform(t, s, "bcd") |
| + newPlatform(t, s, "bcf") |
| + first := customerOf("bcd", "bdf", "4812", "") |
| + if err := s.CreateLinkedAccount(ctx, first, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.CreateLinkedAccount(ctx, customerOf("bcd", "bdg", "4812", ""), platformNow); err == nil { |
| + t.Fatal("a second customer with ref 4812 on bcd was created") |
| + } |
| + if err := s.CreateLinkedAccount(ctx, customerOf("bcf", "bdh", "4812", ""), platformNow); err != nil { |
| + t.Fatalf("ref 4812 on another platform: %v", err) |
| + } |
| + if err := s.DeleteAccount(first.ID, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + again := customerOf("bcd", "bdj", "4812", "") |
| + if err := s.CreateLinkedAccount(ctx, again, platformNow); err != nil { |
| + t.Fatalf("ref 4812 after its customer was deleted: %v", err) |
| + } |
| + if c, err := s.LinkedCustomerByRef(ctx, "bcd", "4812"); err != nil || c == nil || c.ID != again.ID { |
| + t.Fatalf("LinkedCustomerByRef = %+v, %v; want %d", c, err, again.ID) |
| + } |
| + if c, err := s.LinkedCustomerByRef(ctx, "bcd", ""); err != nil || c != nil { |
| + t.Fatalf("LinkedCustomerByRef(\"\") = %+v, %v; want nil", c, err) |
| + } |
| +} |
| + |
| +func TestLinkedCustomersListsOnlyThisPlatformsLiveAccounts(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + newPlatform(t, s, "bcd") |
| + newPlatform(t, s, "bcf") |
| + a := customerOf("bcd", "bdf", "4812", "") |
| + b := customerOf("bcd", "bdg", "", "") |
| + gone := customerOf("bcd", "bdh", "4813", "") |
| + other := customerOf("bcf", "bdj", "4812", "") |
| + for _, c := range []NewLinkedAccount{a, b, gone, other} { |
| + if err := s.CreateLinkedAccount(ctx, c, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := s.DeleteAccount(gone.ID, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + // b is claimed: it has an owner. |
| + if err := s.AddMember(b.ID, "claimer@example.com", RoleOwner, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + list, err := s.LinkedCustomers(ctx, "bcd") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []LinkedCustomer{ |
| + {ID: a.ID, Sqid: "bdf", Name: a.Name, Ref: "4812", CreatedAt: platformNow}, |
| + {ID: b.ID, Sqid: "bdg", Name: b.Name, CreatedAt: platformNow, Owners: 1}, |
| + } |
| + if !reflect.DeepEqual(list, want) { |
| + t.Fatalf("LinkedCustomers = %+v, want %+v", list, want) |
| + } |
| + if n := linkedCount(t, s, "bcd"); n != 2 { |
| + t.Fatalf("LinkedCustomerCount = %d, want 2", n) |
| + } |
| + if c, err := s.LinkedCustomer(ctx, "bcd", "bdg"); err != nil || c == nil || !reflect.DeepEqual(*c, want[1]) { |
| + t.Fatalf("LinkedCustomer(bcd, bdg) = %+v, %v", c, err) |
| + } |
| + for _, q := range [][2]string{{"bcf", "bdf"}, {"bcd", "bdj"}, {"bcd", "bdh"}, {"bcd", "bcd"}, {"", "bcd"}} { |
| + if c, err := s.LinkedCustomer(ctx, q[0], q[1]); err != nil || c != nil { |
| + t.Errorf("LinkedCustomer(%s, %s) = %+v, %v; want nil", q[0], q[1], c, err) |
| + } |
| + } |
| + // "" names no platform: it must not list every unlinked account. |
| + if list, err := s.LinkedCustomers(ctx, ""); err != nil || len(list) != 0 { |
| + t.Fatalf("LinkedCustomers(\"\") = %+v, %v; want none", list, err) |
| + } |
| + if n := linkedCount(t, s, ""); n != 0 { |
| + t.Fatalf("LinkedCustomerCount(\"\") = %d, want 0", n) |
| + } |
| +} |
| + |
| +func TestEnsureLinkedAccountDropsAConflictingRef(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + first, second := testAccountID(), testAccountID() |
| + if added, err := s.EnsureLinkedAccount(first, "bdf", "One", "bcd", "4812", "aa11", platformNow); err != nil || !added { |
| + t.Fatalf("first birth = %v, %v", added, err) |
| + } |
| + if added, err := s.EnsureLinkedAccount(second, "bdg", "Two", "bcd", "4812", "bb22", platformNow); err != nil || !added { |
| + t.Fatalf("second birth = %v, %v; want added", added, err) |
| + } |
| + if p, ref, err := s.AccountPlatform(ctx, second); err != nil || p != "bcd" || ref != "" { |
| + t.Fatalf("second birth's link = %q, %q, %v; want bcd and no ref", p, ref, err) |
| + } |
| + if p, ref, err := s.AccountPlatform(ctx, first); err != nil || p != "bcd" || ref != "4812" { |
| + t.Fatalf("first birth's link = %q, %q, %v; want bcd, 4812", p, ref, err) |
| + } |
| + // A repeat is not a birth. |
| + if added, err := s.EnsureLinkedAccount(second, "bdg", "Two", "bcd", "4812", "bb22", platformNow); err != nil || added { |
| + t.Fatalf("repeat = %v, %v; want not added", added, err) |
| + } |
| +} |
| + |
| +func TestDeleteAccountRefusesAPlatformWithCustomers(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + p := newPlatform(t, s, "bcd") |
| + c := customerOf("bcd", "bdf", "4812", "") |
| + if err := s.CreateLinkedAccount(ctx, c, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.DeleteAccount(p, platformNow); !errors.Is(err, ErrPlatformHasCustomers) { |
| + t.Fatalf("delete with a live customer = %v, want ErrPlatformHasCustomers", err) |
| + } |
| + if err := s.DeleteAccount(c.ID, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + reserveMint(t, s, "bcd", "aa11", "") |
| + if err := s.DeleteAccount(p, platformNow); !errors.Is(err, ErrPlatformHasCustomers) { |
| + t.Fatalf("delete with a pending mint alone = %v, want ErrPlatformHasCustomers", err) |
| + } |
| + if a, err := s.AccountByID(p); err != nil || a == nil { |
| + t.Fatalf("the refused platform = %+v, %v; want it live", a, err) |
| + } |
| + if _, err := s.db.ExecContext(ctx, `DELETE FROM platform_pending_mints WHERE mint_id = 'aa11'`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.DeleteAccount(p, platformNow); err != nil { |
| + t.Fatalf("delete with nothing left = %v", err) |
| + } |
| +} |
| + |
| +func TestRenameAccount(t *testing.T) { |
| + s := openTestStore(t) |
| + ctx := context.Background() |
| + p := newPlatform(t, s, "bcd") |
| + if err := s.RenameAccount(ctx, p, "Shop platform"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if a, err := s.AccountByID(p); err != nil || a.Name != "Shop platform" { |
| + t.Fatalf("after rename = %+v, %v", a, err) |
| + } |
| + if err := s.DeleteAccount(p, platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.RenameAccount(ctx, p, "Gone"); !errors.Is(err, ErrAccountGone) { |
| + t.Fatalf("rename of a deleted account = %v, want ErrAccountGone", err) |
| + } |
| +} |
| + |
| +func TestMigrateIsIdempotentWithPlatformTables(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "console.db") |
| + s, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := newPlatform(t, s, "bcd") |
| + grantPlatform(t, s, p) |
| + reserveMint(t, s, "bcd", "aa11", "4812") |
| + if err := s.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + s, err = Open(path) |
| + if err != nil { |
| + t.Fatalf("reopen: %v", err) |
| + } |
| + defer s.Close() |
| + if g, err := s.PlatformGrant(context.Background(), p); err != nil || g == nil || g.State != PlatformGrantActive { |
| + t.Fatalf("grant after reopen = %+v, %v", g, err) |
| + } |
| + if n := linkedCount(t, s, "bcd"); n != 1 { |
| + t.Fatalf("count after reopen = %d, want 1", n) |
| + } |
| +} |
| + |
| +// The new tables are classified for the host-claim SQL gate, and the |
| +// customer writes pass it. |
| +func TestPlatformTablesUnderTheGate(t *testing.T) { |
| + s := openGatedStore(t) |
| + ctx := context.Background() |
| + p := newPlatform(t, s, "bcd") |
| + grantPlatform(t, s, p) |
| + reserveMint(t, s, "bcd", "aa11", "4812") |
| + if err := s.CreateLinkedAccount(ctx, customerOf("bcd", "bdf", "4812", "aa11"), platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.RevokePlatformGrant(ctx, p, "operator@example.com", "ended", platformNow); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/console/store.go b/internal/console/store.go| index 40a2bb177..b01611f9d 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -716,81 +716,63 @@ func (s *Store) migrate() error { |
| if err := s.backfillAppLifetimes(); err != nil { |
| return err |
| } |
| - // CLI identity's own tables (authstore.go), kept out of the list above so |
| - // the feature is one file to read and one file to remove. |
| - if err := s.migrateCLIAuth(); err != nil { |
| - return err |
| - } |
| - // Linked deployments' own table (links_store.go), for the same reason. |
| - if err := s.migrateLinks(); err != nil { |
| - return err |
| - } |
| - // The apps row's HA pool (store_hapool.go), for the same reason; an |
| - // ALTER after migrateAppsKey, like migrateLinks' linked_link_id. |
| - if err := s.migrateAppHAPool(); err != nil { |
| - return err |
| - } |
| - // Passkey step-up's own tables (stepup.go), for the same reason. |
| - if err := s.migrateStepUp(); err != nil { |
| - return err |
| - } |
| - // Email sign-in's challenge table (emailsignin_store.go), for the same reason. |
| - if err := s.migrateEmailSignin(); err != nil { |
| - return err |
| - } |
| - // Pending-change quorum's own tables (pending.go), for the same reason. |
| - if err := s.migratePendingChanges(); err != nil { |
| - return err |
| - } |
| - // Door keys' own tables (doorkeys_store.go), for the same reason. |
| - if err := s.migrateDoorKeys(); err != nil { |
| - return err |
| - } |
| - // Plans 4a's cap state (plangrace_store.go), for the same reason. |
| - if err := s.migratePlanGrace(); err != nil { |
| - return err |
| - } |
| - // The app policy's revision and recorded content (apppolicy_store.go), |
| - // for the same reason. |
| - if err := s.migrateAppPolicy(); err != nil { |
| - return err |
| - } |
| - // Plans 4d's lapse items (planlapse_store.go), for the same reason. |
| - if err := s.migratePlanLapse(); err != nil { |
| - return err |
| - } |
| - // The app list's personal stars (applist.go), for the same reason. |
| - if err := s.migrateAppStars(); err != nil { |
| - return err |
| - } |
| - // The Getting started checklist's personal marks (gettingstarted_store.go). |
| - if err := s.migrateGettingStarted(); err != nil { |
| - return err |
| - } |
| - // Plans 6b's seat count on the plan row (planmembers.go). |
| - if err := s.migratePlanSeats(); err != nil { |
| - return err |
| - } |
| - // Plans 6a's billing state (billingstore.go), for the same reason. |
| - if err := s.migrateBilling(); err != nil { |
| - return err |
| - } |
| - // The operator pages' column and indexes (opstore.go), for the same reason. |
| - if err := s.migrateOperatorPages(); err != nil { |
| - return err |
| - } |
| - // Managed fleet reservations are separate from app and billing state. |
| - if err := s.migrateManaged(); err != nil { |
| - return err |
| - } |
| - // The alert engine's tables (alertstore.go), for the same reason. |
| - if err := s.migrateAlerts(); err != nil { |
| - return err |
| - } |
| - if err := s.migrateDemo(); err != nil { |
| - return err |
| + return s.migrateFeatures() |
| +} |
| + |
| +// migrateFeatures runs each feature's own migration, in this order, after |
| +// the shared tables above: the features' tables and columns kept out of |
| +// migrate's lists so each feature is one file to read and one file to remove. |
| +func (s *Store) migrateFeatures() error { |
| + for _, step := range []func() error{ |
| + // CLI identity's own tables (authstore.go), kept out of the list above so |
| + // the feature is one file to read and one file to remove. |
| + s.migrateCLIAuth, |
| + // Linked deployments' own table (links_store.go), for the same reason. |
| + s.migrateLinks, |
| + // The apps row's HA pool (store_hapool.go), for the same reason; an |
| + // ALTER after migrateAppsKey, like migrateLinks' linked_link_id. |
| + s.migrateAppHAPool, |
| + // Passkey step-up's own tables (stepup.go), for the same reason. |
| + s.migrateStepUp, |
| + // Email sign-in's challenge table (emailsignin_store.go), for the same reason. |
| + s.migrateEmailSignin, |
| + // Pending-change quorum's own tables (pending.go), for the same reason. |
| + s.migratePendingChanges, |
| + // Door keys' own tables (doorkeys_store.go), for the same reason. |
| + s.migrateDoorKeys, |
| + // Plans 4a's cap state (plangrace_store.go), for the same reason. |
| + s.migratePlanGrace, |
| + // The app policy's revision and recorded content (apppolicy_store.go), |
| + // for the same reason. |
| + s.migrateAppPolicy, |
| + // Plans 4d's lapse items (planlapse_store.go), for the same reason. |
| + s.migratePlanLapse, |
| + // The app list's personal stars (applist.go), for the same reason. |
| + s.migrateAppStars, |
| + // The Getting started checklist's personal marks (gettingstarted_store.go). |
| + s.migrateGettingStarted, |
| + // Plans 6b's seat count on the plan row (planmembers.go). |
| + s.migratePlanSeats, |
| + // Plans 6a's billing state (billingstore.go), for the same reason. |
| + s.migrateBilling, |
| + // The operator pages' column and indexes (opstore.go), for the same reason. |
| + s.migrateOperatorPages, |
| + // Managed fleet reservations are separate from app and billing state. |
| + s.migrateManaged, |
| + // The alert engine's tables (alertstore.go), for the same reason. |
| + s.migrateAlerts, |
| + s.migrateDemo, |
| + s.migrateDomains, |
| + // Platform grants, pending customer mints and customer links |
| + // (platform_store.go). Last: it alters accounts and cli_tokens, which |
| + // migrate and migrateCLIAuth create. |
| + s.migratePlatformAccounts, |
| + } { |
| + if err := step(); err != nil { |
| + return err |
| + } |
| } |
| - return s.migrateDomains() |
| + return nil |
| } |
| // migratePlanSeats adds account_plans.seats (plans 6b): the paid seat count |
| @@ -1283,13 +1265,42 @@ func (s *Store) CreateAccount(id int64, sqid, name, ownerAddress string, now tim |
| // by whichever process, is never visible without the sponsored row it is |
| // owed. |
| func (s *Store) EnsureAccount(id int64, sqid, name string, created time.Time) (added bool, err error) { |
| - tx, err := s.db.Begin() |
| + return s.ensureAccount(id, sqid, name, accountLink{}, created) |
| +} |
| + |
| +// accountLink is a customer account's link to its platform account |
| +// (platform_store.go): the platform's sqid, the platform's reference for |
| +// the customer, and the pending mint the account was born from. The zero |
| +// value is an ordinary, unlinked account. |
| +type accountLink struct{ platform, ref, mint string } |
| + |
| +// ensureAccount is EnsureAccount and EnsureLinkedAccount: one INSERT OR |
| +// IGNORE in a transaction. A linked birth whose ref a live customer of the |
| +// same platform already holds is born with no ref, so the unique index |
| +// (accounts_platform_ref) can never turn a birth into an ignored insert. |
| +// An unlinked birth gets the launch sponsorship's rule; a linked one does |
| +// not, because a customer's plan is its platform's (decision D9). |
| +func (s *Store) ensureAccount(id int64, sqid, name string, link accountLink, created time.Time) (bool, error) { |
| + // Materialization, its one caller, runs at start with no request ctx. |
| + ctx := context.Background() |
| + tx, err := s.db.BeginTx(ctx, nil) |
| if err != nil { |
| return false, err |
| } |
| defer tx.Rollback() |
| - res, err := tx.Exec(`INSERT OR IGNORE INTO accounts (id, sqid, name, created_at) VALUES (?, ?, ?, ?)`, |
| - id, sqid, name, created.Unix()) |
| + if link.platform != "" && link.ref != "" { |
| + var held int |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM accounts |
| + WHERE platform = ? AND platform_ref = ? AND deleted_at = 0`, link.platform, link.ref).Scan(&held); err != nil { |
| + return false, err |
| + } |
| + if held > 0 { |
| + link.ref = "" |
| + } |
| + } |
| + res, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO accounts |
| + (id, sqid, name, created_at, platform, platform_ref, platform_mint) VALUES (?, ?, ?, ?, ?, ?, ?)`, |
| + id, sqid, name, created.Unix(), link.platform, link.ref, link.mint) |
| if err != nil { |
| return false, err |
| } |
| @@ -1297,8 +1308,10 @@ func (s *Store) EnsureAccount(id int64, sqid, name string, created time.Time) (a |
| if err != nil || n == 0 { |
| return false, err |
| } |
| - if err := s.sponsorOnInsertTx(tx, id, created); err != nil { |
| - return false, err |
| + if link.platform == "" { |
| + if err := s.sponsorOnInsertTx(tx, id, created); err != nil { |
| + return false, err |
| + } |
| } |
| return true, tx.Commit() |
| } |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index f9032badb..4ce46c6b3 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -274,6 +274,9 @@ var claimSQLTables = map[string]claimSQLTable{ |
| "email_challenges": {NonApp: "emailed sign-in and step-up links and codes in flight, keyed by id hash; carries no app column"}, |
| "pending_actions": {NonApp: "replay-by-token actions, keyed by token hash; carries no app column and re-enters the ordinary handlers"}, |
| + "platform_grants": {NonApp: "an account's platform grant and its generation, keyed by account; names no app"}, |
| + "platform_pending_mints": {NonApp: "customer account creates a platform has been promised, keyed by mint id and platform sqid; names no app"}, |
| + |
| "domain_contacts": {NonApp: "registrant contact details and handle, keyed by account; names no app"}, |
| "domain_registrations": {NonApp: "domain ownership and renewal records, keyed by domain and account; names no app"}, |