plan: platform accounts slice 1, Astra round 1 fixes
All five round 1 findings accepted after checking each citation: pending mints and an idempotent bucket mint (r1-1), a grant generation checked at mint and resolution (r1-2), deletion and creation on one lock (r1-3), a host door that writes nothing of its own (r1-4), and a witness that creates the app in both customers first (r1-5).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+219
−71
docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md+219 −71
Intent
Attributed to this commit: 3.78 g CO₂e (439,196 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-platform-accounts, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md b/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md| index 23953892c..b37294b5a 100644 |
| --- a/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md |
| +++ b/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md |
| @@ -10,6 +10,18 @@ |
| **Spec:** `docs/superpowers/specs/2026-11-19-platform-accounts-design.md` (approved by Paul 2026-11-19). Executors read both. Its file:line refs were taken at `ed6ae029`; every ref below was re-checked at `06603e71`. |
| +## Review log |
| + |
| +Round 1 (Astra, findings `docs/superpowers/plans/ASTRA-FINDINGS-platform-accounts-1-r1.md`, reviewed at `2871ba18`): NOT READY, four P1 and one P2. Each citation was re-read in the code before acting; all five are accepted. The plan marks every change "(Astra r1-N)". |
| + |
| +- **r1-1 (P1), one live account per platform reference; pending creates use capacity.** Confirmed: `NextAccountID` (`mint.go:141-193`) counts a stranded manifest, so a retry after a failed row insert minted a second account, and Task 4's ref-drop on birth then kept both. Fix, one invariant in two halves: the console records a **pending mint** (its own random mint id, the ref, the name, the plan) in SQLite before the bucket write, and counts pending mints against `max_customers`; the bucket half is that `MintLinkedAccount` is **idempotent on the mint id**, which it writes into the manifest (`platform_mint`) and finds again in the scan it already does. Any later platform request finishes pending mints first, under the platform lock, so a retry, a ref-less create or a console restart all converge on the one account. Tasks 2, 4, 8. |
| +- **r1-2 (P1), re-granting must not restore authority issued before a revoke.** Confirmed: the bearer resolves once before the handler (`authcli.go:503`), so a mint could insert after the revoke's row sweep. Fix: the grant carries a **generation** that every revoke increments. Every platform-role and per-customer credential row records the generation it was minted under; resolution accepts a row only while its generation is the grant's current active one, and the mint checks the same thing inside its insert transaction. The row sweep is dropped: the generation check is the one place this is enforced. Tasks 4, 7, 10. |
| +- **r1-3 (P1), a platform with customers cannot be retired.** Confirmed: `deleteAccountNow` (`ownership.go:183-223`) checks, tombstones, then deletes, and a tombstoned live account is reaped at start (`materialize.go:125-138`). Fix: deletion and customer creation serialize on the same `s.lockAccount(platform sqid)`; `deleteAccountNow` takes it before its re-check, and customer create re-reads the platform and its grant after taking it. Pending mints count as customers in the deletion check. Tasks 8, 9. |
| +- **r1-4 (P1), refused service requests must not write control-plane policy.** Confirmed: `writeEnableManifest` writes, audits and bumps the serial (`apiinstances.go:3841-3857`) and the service control-plane refusal comes later, in the create handler (`:1597`); the create also takes `beginCopiesMutation` itself (`:2626`). Fix: the platform-host door **writes no manifest at all**. Reconcile already serves a record whose app has no manifest (`provision/reconcile.go:1628-1636`: "the manifest only governs the API door"; absent is "no seed", "no policy"), so the door hands the create handler an in-memory default manifest through a request-context value that only `instanceManifest` reads. Every write is then the create handler's own, after its own refusals and under its own locks. Task 12. |
| +- **r1-5 (P2), the witness must tell refusal from absence.** Confirmed: `apiAccountAppSaying` 404s a missing app (`apicli.go:95-101`), so probing `c2/site` when only `c1` has `site` proves nothing. Fix: both customers get `site`, each through its own credential, each shown working before the cross-account reads and writes are asserted. Tasks 10, 14. |
| + |
| +Declined: none. |
| + |
| ## Global Constraints |
| House rules (from the brief, verbatim where they are rules): |
| @@ -29,9 +41,12 @@ From the spec and AGENTS.md: |
| - Wire shapes are additive: a manifest written before this change parses unchanged, and an unlinked manifest marshals byte-identical to today (`platform`, `platform_ref` are `omitempty`). |
| - The platform role is never combined with other roles, never app-bound, and reachable only through `svcrole.Exactly(svcrole.Platform)`. Admin service credentials do NOT reach platform doors (spec §12 suggestion, adopted). |
| - Per-customer credentials: kind `platform`; role Publish (account-wide, no app) or Deploy (one app, rungs required); expiry default 1 h, at most 24 h, at least 1 minute; checked on every request against a live link and an active grant. |
| -- Revoking a grant refuses the platform credential and every per-customer credential from the next request, read doors included. Links stay; sites keep serving. |
| +- Revoking a grant refuses the platform credential and every per-customer credential from the next request, read doors included. Links stay; sites keep serving. A credential is valid only under the grant generation it was minted in, and re-granting starts a new generation (Astra r1-2). |
| - The ops account (`OpsAccountID`, `domains.ReservedAccountID`) and any linked account can never hold a grant. |
| -- A platform account is never deleted while it has a live linked customer. |
| +- A platform account is never deleted while it has a live linked customer or a pending mint; deletion and customer creation take the same account lock (Astra r1-3). |
| +- One live account per (platform, ref), and a pending mint uses capacity until it is finished (Astra r1-1). |
| +- A refused request writes nothing: no manifest, no audit row, no serial bump (Astra r1-4). |
| +- Test seams are unexported `Server` func fields, nil in production, the `lapseBeforeConverge` precedent (`plangracepass.go:177`). |
| - Linked accounts never get a Stripe customer: `holdBilling` refuses them, domain purchase refuses them, and they do not count towards anyone's free-account cap. |
| - Ordinary security gate order holds (AGENTS.md): session, CSRF, owner (byte-identical 404), `requireFreshAuth` last. A caller who cannot see an account gets the stdlib `404 page not found`. |
| - Files: no Go file past 3,000 code lines and no function past 300 grows (`make code-health`). Do not add code to `internal/console/server.go`, `apimode.go`, or the bodies of `(*Store).migrate`, `runDeploy` or `handleAPIInstanceCreate`. New code goes in the new files named in each task. |
| @@ -41,7 +56,7 @@ From the spec and AGENTS.md: |
| ## Review Focus |
| 1. **Retried creates.** A platform's server retries `customers create` with the same `ref` after a timeout, sometimes concurrently. Expect exactly one account and the same sqid in every answer (Task 8, `TestCustomerCreateConcurrentSameRefMakesOneAccount`). |
| -2. **A mint that lands in the bucket and not in the console.** The manifest write succeeds and the row insert fails. Expect the next console start to materialize it as a linked, ownerless customer that lists, counts against `max_customers`, and can be deleted (Task 5, `TestMaterializeAdoptsAStrandedLinkedMint`). |
| +2. **A mint that lands in the bucket and not in the console.** The manifest write succeeds and the row insert fails. Expect a retry, or the next console start, to converge on that one account with its ref, counted against `max_customers` throughout (Task 8, `TestCustomerCreateSurvivesAFailedFinish`; Task 5, `TestMaterializeAdoptsAStrandedLinkedMint`) (Astra r1-1). |
| 3. **The expiry boundary.** A per-customer credential at exactly `expires_at` works; one second later it is refused like an unknown token (Task 10, `TestCustomerCredentialExpiryBoundary`). |
| 4. **A grant that shrinks.** The operator lowers `max_customers` below the current count or drops a plan customers are on. Expect existing customers untouched, new creates refused with the cap sentence, and a PATCH onto a dropped plan refused (Task 8 `TestCustomerCreateStopsAtMaxCustomers`, Task 9 `TestCustomerPlanChangeStaysInsideTheGrant`). |
| 5. **The platform credential at an ordinary door.** A platform credential sent to `apps list`, `deploy` or `services` on its own platform account gets the role refusal, never a widening (Task 8, `TestPlatformCredentialRefusedAtOrdinaryDoors`). |
| @@ -144,8 +159,8 @@ git commit -m "plan: platform accounts slice 1, CLI UX pass" |
| **Interfaces:** |
| - Produces: |
| - - `AccountManifest.Platform string \`json:"platform,omitempty"\`` (the platform account's sqid) and `AccountManifest.PlatformRef string \`json:"platform_ref,omitempty"\``. |
| - - `func MintLinkedAccount(ctx context.Context, s release.Store, name, platformSqid, ref string, created time.Time) (int64, string, error)`: `MintAccount`'s loop with no owner and the two link fields in the same create-only write. |
| + - `AccountManifest.Platform string \`json:"platform,omitempty"\`` (the platform account's sqid), `AccountManifest.PlatformRef string \`json:"platform_ref,omitempty"\`` and `AccountManifest.PlatformMint string \`json:"platform_mint,omitempty"\`` (the console's pending-mint id, 32 hex; Astra r1-1). |
| + - `func MintLinkedAccount(ctx context.Context, s release.Store, name, platformSqid, ref, mintID string, created time.Time) (id int64, sqid string, existing bool, err error)`: `MintAccount`'s loop with no owner and the three link fields in the same create-only write. **Idempotent on `mintID` (Astra r1-1):** before allocating, the scan that already reads every manifest body looks for a live manifest with `Platform == platformSqid && PlatformMint == mintID`; if there is one it is returned with `existing == true` and nothing is written. So a retry after a failed or ambiguous Put, or after a failure further on, finds the account its first attempt made instead of minting another. |
| - `func RenameAccountManifest(ctx context.Context, s release.Store, sqid, name string) error`: CAS read-modify-write with one retry (`TombstoneAccount`'s shape), every other field kept. |
| - `var ErrBadPlatformLink = errors.New(...)`. |
| @@ -154,21 +169,30 @@ git commit -m "plan: platform accounts slice 1, CLI UX pass" |
| ```go |
| func TestMintLinkedAccountWritesTheLinkInTheCreateOnlyWrite(t *testing.T) { |
| // DirStore with ops (id 1) and bcd's manifest present. |
| - id, sqid, err := MintLinkedAccount(ctx, s, "shop", "bcd", "4812", now) |
| - // err == nil; manifest at AccountManifestKey(sqid) decodes to |
| - // Platform "bcd", PlatformRef "4812", Owner "", ID id, Name "shop". |
| + id, sqid, existing, err := MintLinkedAccount(ctx, s, "shop", "bcd", "4812", mintA, now) |
| + // err == nil, existing == false; manifest at AccountManifestKey(sqid) decodes to |
| + // Platform "bcd", PlatformRef "4812", PlatformMint mintA, Owner "", ID id, Name "shop". |
| +} |
| +func TestMintLinkedAccountIsIdempotentOnItsMintID(t *testing.T) { // (Astra r1-1) |
| + // second call with mintA (any name): same id and sqid, existing == true, s.List unchanged; |
| + // a different mint id mints the next id; a tombstoned manifest carrying mintA is not a match. |
| +} |
| +func TestMintLinkedAccountRetryAfterAFailedPut(t *testing.T) { // (Astra r1-1) |
| + // store wrapper whose first Put lands the object and then returns an error (the ambiguous case): |
| + // first call errors; the retry with the same mint id returns that object (existing == true); |
| + // exactly one manifest carries mintA. |
| } |
| func TestMintLinkedAccountRefusesABadLink(t *testing.T) { |
| - // platformSqid "" , "not a sqid!", Sqid(ReservedAccountID): errors.Is(err, ErrBadPlatformLink) |
| - // and s.List(ctx, "accounts/") is unchanged (nothing written). |
| + // platformSqid "" , "not a sqid!", Sqid(ReservedAccountID), or mintID not 32 hex: |
| + // errors.Is(err, ErrBadPlatformLink) and s.List(ctx, "accounts/") is unchanged (nothing written). |
| } |
| func TestUnlinkedManifestIsByteIdentical(t *testing.T) { |
| - // json.Marshal(AccountManifest{ID:2,Sqid:"bab",Name:"a",CreatedAt:t0}) has no "platform" key; |
| - // a manifest body without the keys unmarshals with Platform == "" && PlatformRef == "". |
| + // json.Marshal(AccountManifest{ID:2,Sqid:"bab",Name:"a",CreatedAt:t0}) has none of the three keys; |
| + // a manifest body without the keys unmarshals with all three "". |
| } |
| func TestRenameAccountManifestKeepsEveryField(t *testing.T) { |
| // linked manifest renamed "shop" -> "shop-2": Name changed; ID, Sqid, CreatedAt, Owner, |
| - // Platform, PlatformRef unchanged. A missing manifest is an error wrapping os.ErrNotExist. |
| + // Platform, PlatformRef, PlatformMint unchanged. A missing manifest is an error wrapping os.ErrNotExist. |
| } |
| func TestTombstoneKeepsThePlatformLink(t *testing.T) { |
| // TombstoneAccount on a linked manifest: Deleted() true, Owner "", Platform still "bcd". |
| @@ -180,7 +204,7 @@ func TestTombstoneKeepsThePlatformLink(t *testing.T) { |
| Run: `go test ./internal/domains/ -run 'TestMintLinkedAccount|TestUnlinkedManifestIsByteIdentical|TestRenameAccountManifest|TestTombstoneKeepsThePlatformLink' -count=1` |
| Expected: FAIL (undefined: MintLinkedAccount). |
| -- [ ] **Step 3: Implement.** Refactor `MintAccount`'s body into an unexported `mint(ctx, s, AccountManifest template, created)` that both call, so the create-only loop exists once. `MintLinkedAccount` validates before the first listing: `ValidSqid(platformSqid)` and `platformSqid != Sqid(ReservedAccountID)`, else `ErrBadPlatformLink`. The ref is validated by the console (Task 8), not here. `TombstoneAccount` needs no change: it round-trips the struct, so it keeps the new fields; the test pins that. |
| +- [ ] **Step 3: Implement.** Split `NextAccountID`'s body into an unexported `scanManifests(ctx, s) ([]AccountManifest, error)` (same concurrency, same "unreadable is not free" rule; an unparseable body still claims nothing) and keep `NextAccountID` as max-plus-one over it. Refactor `MintAccount`'s loop into an unexported `mint(ctx, s, template AccountManifest, created, match func(AccountManifest) bool)` that both call: each attempt scans once, returns a `match` hit with `existing == true`, otherwise writes create-only at max+1 (with `skipReservedIDs`). `MintAccount` passes a nil `match`. `MintLinkedAccount` validates before the first listing: `ValidSqid(platformSqid)`, `platformSqid != Sqid(ReservedAccountID)` and a 32-hex `mintID`, else `ErrBadPlatformLink`. The ref is validated by the console (Task 8), not here. `TombstoneAccount` needs no change: it round-trips the struct, so it keeps the new fields; the test pins that. |
| - [ ] **Step 4: Run the tests to verify they pass** (same command). Expected: PASS. |
| @@ -243,6 +267,7 @@ const (PlatformGrantActive = "active"; PlatformGrantRevoked = "revoked") |
| 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 |
| @@ -264,17 +289,29 @@ var ( |
| func (s *Store) migratePlatformAccounts() error |
| func (s *Store) PlatformGrant(ctx context.Context, accountID int64) (*PlatformGrant, error) // nil, nil: none |
| func (s *Store) PutPlatformGrant(ctx context.Context, g PlatformGrant, now time.Time) error // upsert, state active, revoke fields cleared |
| -func (s *Store) RevokePlatformGrant(ctx context.Context, accountID int64, by, reason string, now time.Time) (credentials int, err error) |
| +func (s *Store) RevokePlatformGrant(ctx context.Context, accountID int64, by, reason string, now time.Time) (credentials int, err error) // credentials: live rows of the ending generation, counted, not swept |
| func (s *Store) AccountPlatform(ctx context.Context, accountID int64) (platformSqid, ref string, err error) // "" when unlinked or unknown |
| func (s *Store) LinkedCustomers(ctx context.Context, platformSqid string) ([]LinkedCustomer, error) // live only, by id |
| func (s *Store) LinkedCustomer(ctx context.Context, platformSqid, customerSqid string) (*LinkedCustomer, error) // nil when not this platform's |
| func (s *Store) LinkedCustomerByRef(ctx context.Context, platformSqid, ref string) (*LinkedCustomer, error) |
| -func (s *Store) LinkedCustomerCount(ctx context.Context, platformSqid string) (int, error) |
| +func (s *Store) LinkedCustomerCount(ctx context.Context, platformSqid string) (int, error) // live customers PLUS pending mints (Astra r1-1) |
| +// PendingMint is a customer create the console has promised and not finished (Astra r1-1). |
| +type PendingMint struct { |
| + MintID, Platform, Ref, Name, Plan, PlanReason, By string // MintID: 32 hex, crypto/rand |
| + CreatedAt time.Time |
| +} |
| +func (s *Store) ReservePlatformMint(ctx context.Context, m PendingMint) error // ErrPlatformRefTaken when ref is held by a live customer or another pending mint |
| +func (s *Store) PendingPlatformMints(ctx context.Context, platformSqid string) ([]PendingMint, error) // oldest first |
| +var ErrPlatformRefTaken = errors.New("console: that reference already names a customer account") |
| type NewLinkedAccount struct { |
| - ID int64; Sqid, Name, Platform, Ref string |
| + ID int64; Sqid, Name, Platform, Ref, MintID string |
| Plan, PlanReason, By string // Plan "" writes no plan row |
| } |
| +// CreateLinkedAccount FINISHES a pending mint: one transaction that inserts the row and plan row |
| +// (or, when materialization already made the row for this sqid and platform, sets a platform plan |
| +// row in place of a default one) and deletes the pending mint. Finishing twice is a no-op. |
| func (s *Store) CreateLinkedAccount(ctx context.Context, a NewLinkedAccount, now time.Time) error |
| +func (s *Store) PlatformGenerationLive(ctx context.Context, q dbQuerier, platformAccountID, generation int64) (platformSqid string, ok bool) // the one check (Astra r1-2) |
| func (s *Store) EnsureLinkedAccount(id int64, sqid, name, platformSqid, ref string, created time.Time) (added bool, err error) |
| func (s *Store) RenameAccount(ctx context.Context, accountID int64, name string) error |
| func (s *Store) DeleteUnclaimedCustomer(ctx context.Context, customerID int64, platformSqid string, now time.Time) error |
| @@ -288,10 +325,17 @@ CREATE TABLE IF NOT EXISTS platform_grants ( |
| 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); |
| + 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 != ''; |
| ALTER TABLE accounts ADD COLUMN platform TEXT NOT NULL DEFAULT ''; -- platform account sqid |
| ALTER TABLE accounts ADD COLUMN platform_ref TEXT NOT NULL DEFAULT ''; |
| 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 |
| 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; |
| @@ -303,11 +347,20 @@ The link column holds the platform's sqid, not its id, so materialization (Task |
| - [ ] **Step 1: Write the failing tests** (`platform_store_test.go`, using `Open` on `t.TempDir()` like `store_test.go`) |
| ```go |
| -func TestPlatformGrantRoundTrip(t *testing.T) // Put, read back every field; second Put re-grants (state active, revoke fields "") |
| -func TestRevokePlatformGrantRevokesItsCredentials(t *testing.T) { |
| - // rows: kind 'platform' platform_account_id=P (2 rows), kind 'service' role 'platform' account_id=P (1), |
| - // kind 'service' role 'publish' account_id=P (1), kind 'platform' platform_account_id=Q (1). |
| - // RevokePlatformGrant(P) returns 3; only those three have revoked_at != 0; grant state "revoked". |
| +func TestPlatformGrantRoundTrip(t *testing.T) // Put, read back every field; second Put re-grants (state active, revoke fields "", generation unchanged) |
| +func TestRevokePlatformGrantEndsItsGeneration(t *testing.T) { // (Astra r1-2) |
| + // grant gen 1; rows of gen 1: kind 'platform' platform_account_id=P (2), kind 'service' role 'platform' account_id=P (1); |
| + // RevokePlatformGrant(P) returns 3, generation 2, state "revoked", no cli_tokens row changed. |
| + // PlatformGenerationLive(P, 1) false; PutPlatformGrant again: (P, 2) true, (P, 1) still false. |
| +} |
| +func TestPendingMintsCountAndHoldTheirRef(t *testing.T) { // (Astra r1-1) |
| + // ReservePlatformMint(ref 4812): LinkedCustomerCount 1 with no account row; a second reservation or a |
| + // live customer with ref 4812 -> ErrPlatformRefTaken; CreateLinkedAccount(MintID) -> count still 1, |
| + // PendingPlatformMints empty; CreateLinkedAccount again with the same MintID -> nil, nothing changes. |
| +} |
| +func TestCreateLinkedAccountFinishesOverAMaterializedRow(t *testing.T) { // (Astra r1-1) |
| + // EnsureLinkedAccount made the row (default plan row from EnsureDefaultPlans); CreateLinkedAccount with the |
| + // same sqid and platform: plan row now source platform, pending mint gone, still one account. |
| } |
| func TestCreateLinkedAccountHasNoMembersAndAPlatformPlan(t *testing.T) { |
| // Members(id) empty; AccountPlatform == ("bcd", "4812"); AccountPlan(id).Source == PlanSourcePlatform, |
| @@ -316,24 +369,26 @@ func TestCreateLinkedAccountHasNoMembersAndAPlatformPlan(t *testing.T) { |
| func TestLinkedCustomerRefIsUniquePerPlatform(t *testing.T) // same ref on bcd twice: second CreateLinkedAccount errors; same ref on bcf is fine; after DeleteUnclaimedCustomer the ref is free again |
| func TestLinkedCustomersListsOnlyThisPlatformsLiveAccounts(t *testing.T) |
| func TestEnsureLinkedAccountDropsAConflictingRef(t *testing.T) // a second birth with a taken ref is added with Ref "" |
| -func TestDeleteAccountRefusesAPlatformWithCustomers(t *testing.T) // errors.Is(err, ErrPlatformHasCustomers); after the customer is deleted it succeeds |
| +func TestDeleteAccountRefusesAPlatformWithCustomers(t *testing.T) // errors.Is(err, ErrPlatformHasCustomers) for a live customer and for a pending mint alone (Astra r1-3); after both are gone it succeeds |
| func TestDeleteUnclaimedCustomerRefusals(t *testing.T) { |
| // owner membership -> ErrCustomerClaimed; an app row -> ErrCustomerHasApps; |
| - // wrong platform sqid -> ErrAccountGone; success marks deleted_at, revokes kind 'platform' rows for it. |
| + // wrong platform sqid -> ErrAccountGone; success marks deleted_at (its credentials then fail the link check, Task 10). |
| } |
| func TestMigrateIsIdempotentWithPlatformTables(t *testing.T) // Open, Close, Open the same file: no error |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPlatformGrantRoundTrip|TestRevokePlatformGrant|TestCreateLinkedAccount|TestLinkedCustomer|TestEnsureLinkedAccount|TestDeleteAccountRefusesAPlatform|TestDeleteUnclaimedCustomer|TestMigrateIsIdempotentWithPlatform' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPlatformGrantRoundTrip|TestRevokePlatformGrant|TestPendingMints|TestCreateLinkedAccount|TestLinkedCustomer|TestEnsureLinkedAccount|TestDeleteAccountRefusesAPlatform|TestDeleteUnclaimedCustomer|TestMigrateIsIdempotentWithPlatform' -count=1`. Expected: FAIL. |
| - [ ] **Step 3: Make room in `migrate` first.** `(*Store).migrate` is 389 code lines, held by the ratchet. Replace the run of feature calls from `migrateCLIAuth` to `migrateDomains` (`store.go:721-793`) with one `migrateFeatures()` method that iterates an ordered `[]func() error{s.migrateCLIAuth, s.migrateLinks, ...}` in the same order, carrying each call's comment onto its element, and append `s.migratePlatformAccounts` last. No reordering, nothing else changed. `migrate` shrinks; nothing grows. |
| - [ ] **Step 4: Implement the store.** Points the signatures leave open: |
| - - `CreateLinkedAccount`: one transaction: the `accounts` insert with `platform`, `platform_ref`; when `Plan != ""`, the plan row through `accountPlanUpsertSQL`/`accountPlanUpsertArgs` with `PlanSourcePlatform`. No membership. No `sponsorOnInsertTx`: a linked account's plan is its platform's (decision D9). |
| + - `CreateLinkedAccount` (Astra r1-1): one transaction. If a live row with this id, sqid and platform exists (materialized first), keep it and only replace a `default`-source plan row; otherwise insert the `accounts` row with `platform`, `platform_ref`. When `Plan != ""`, the plan row through `accountPlanUpsertSQL`/`accountPlanUpsertArgs` with `PlanSourcePlatform`. Then `DELETE FROM platform_pending_mints WHERE mint_id = ?`. No membership. No `sponsorOnInsertTx`: a linked account's plan is its platform's (decision D9). |
| + - `ReservePlatformMint`: one transaction: a non-empty ref held by a live linked account of that platform or by another pending mint is `ErrPlatformRefTaken`; otherwise insert. The partial unique index backs it. |
| + - `PlatformGenerationLive` (Astra r1-2): `SELECT p.sqid FROM platform_grants g JOIN accounts p ON p.id = g.account_id WHERE g.account_id = ? AND g.state = 'active' AND g.generation = ? AND p.deleted_at = 0`. `dbQuerier` is the `QueryRowContext` interface both `*sql.DB` and `*sql.Tx` satisfy, so the resolver and the mint transactions ask the identical question. |
| - `EnsureLinkedAccount`: `EnsureAccount`'s body (share an unexported helper) plus the two columns; inside its transaction, a ref already held by a live account of the same platform is dropped to `""` before the insert, so the unique index can never turn a birth into an ignored insert. No sponsorship either. |
| - - `DeleteAccount` (`ownership.go:790`): inside its transaction, before the deletes, count live accounts whose `platform` is this account's sqid; non-zero is `ErrPlatformHasCustomers`. |
| - - `DeleteUnclaimedCustomer`: one transaction: the row must be live with `platform = platformSqid` (else `ErrAccountGone`); owner count 0 (else `ErrCustomerClaimed`); `apps` count 0, unfiltered like `AppCount` (else `ErrCustomerHasApps`); then the same statements as `DeleteAccount` and `UPDATE cli_tokens SET revoked_at = ? WHERE kind = 'platform' AND account_id = ? AND revoked_at = 0`. |
| - - `RevokePlatformGrant`: one transaction: grant row to revoked, then `UPDATE cli_tokens SET revoked_at = ? WHERE revoked_at = 0 AND ((kind = 'platform' AND platform_account_id = ?) OR (kind = 'service' AND role = 'platform' AND account_id = ?))`; returns rows affected. A missing grant is `ErrNotPlatform`. |
| + - `DeleteAccount` (`ownership.go:790`): inside its transaction, before the deletes, count live accounts whose `platform` is this account's sqid plus its pending mints; non-zero is `ErrPlatformHasCustomers` (Astra r1-3). |
| + - `DeleteUnclaimedCustomer`: one transaction: the row must be live with `platform = platformSqid` (else `ErrAccountGone`); owner count 0 (else `ErrCustomerClaimed`); `apps` count 0, unfiltered like `AppCount` (else `ErrCustomerHasApps`); then the same statements as `DeleteAccount`. No token sweep: a deleted account fails the link check every credential resolution makes (Task 10). |
| + - `RevokePlatformGrant` (Astra r1-2): one transaction: count live rows minted under the current generation (`(kind = 'platform' AND platform_account_id = ?) OR (kind = 'service' AND role = 'platform' AND account_id = ?)`, `platform_generation = ?`, unrevoked, unexpired), then set state revoked and `generation = generation + 1`. It touches no `cli_tokens` row: the generation check is what ends them, in the one place every resolution and every mint asks. A missing grant is `ErrNotPlatform`. `PutPlatformGrant` never changes the generation, so a re-grant after a revoke runs under the new one. |
| - [ ] **Step 5: Run** the Step 2 command, then the existing migration and deletion tests: `go test ./internal/console/ -run 'TestOpen|TestMigrate|TestDeleteAccount|TestEnsureAccount' -count=1`. Expected: PASS. |
| @@ -341,7 +396,7 @@ func TestMigrateIsIdempotentWithPlatformTables(t *testing.T) // Open, Close, Ope |
| ```bash |
| git add internal/console/platform_store.go internal/console/platform_store_test.go internal/console/store.go internal/console/ownership.go internal/console/accountplans.go |
| -git commit -m "console: platform grants and customer links in the store" |
| +git commit -m "console: platform grants, pending mints and customer links" |
| ``` |
| --- |
| @@ -396,7 +451,7 @@ git commit -m "console: materialize the platform link at an account's birth only |
| `GET /api/cli/accounts/{account}/platform` → `handleAPIPlatformGrantGet`; |
| `PUT /api/cli/accounts/{account}/platform` → `handleAPIPlatformGrantPut`; |
| `POST /api/cli/accounts/{account}/platform/revoke` → `handleAPIPlatformGrantRevoke`. |
| - - Wire: `type platformGrantReply struct { Account string; Platform bool; State string; MaxCustomers, Customers int; Plans []string; DefaultPlan, Reason, GrantedBy string; GrantedAt time.Time; RevokedBy, RevokeReason string; RevokedAt time.Time }` (JSON snake_case, time fields `omitempty` via pointers); `type putPlatformGrantRequest struct { MaxCustomers int; Plans []string; DefaultPlan, Reason string }`; revoke body `{ "reason": string }`, reply `platformGrantReply` plus `"credentials_revoked": int`. |
| + - Wire: `type platformGrantReply struct { Account string; Platform bool; State string; MaxCustomers, Customers int; Plans []string; DefaultPlan, Reason, GrantedBy string; GrantedAt time.Time; RevokedBy, RevokeReason string; RevokedAt time.Time }` (JSON snake_case, time fields `omitempty` via pointers); `type putPlatformGrantRequest struct { MaxCustomers int; Plans []string; DefaultPlan, Reason string }`; revoke body `{ "reason": string }`, reply `platformGrantReply` plus `"credentials_ended": int` (live credentials of the generation the revoke ended; Astra r1-2). |
| - `func (s *Server) platformGrantDoor(w http.ResponseWriter, r *http.Request) (addr string, acct *Account, ok bool)`: `accountPlanDoor`'s gate (`apiaccountplan.go:45`) without the catalog requirement: `cliUser`, `IsOperator` else stdlib 404, `AccountBySqid` else 404. |
| - CLI: `func runAccountsPlatformWithSession(ctx context.Context, sess *apiSession, args []string, out io.Writer) error`; `raw("platform", op, runAccountsPlatform)` in `accountsCommand`; session methods `platformGrant`, `putPlatformGrant`, `revokePlatformGrant` in `accounts_platform.go`. |
| @@ -409,7 +464,7 @@ func TestPlatformGrantDoorIsOperatorOnly(t *testing.T) // owner token |
| func TestPlatformGrantDoorRefusesOpsAndCustomerAccounts(t *testing.T) // 409 with platformCopy["grant.ops"], ["grant.linked"] |
| func TestPlatformGrantValidatesPlansAgainstTheCatalog(t *testing.T) // unknown plan, default not in plans, max 0 and 10001 -> 400s |
| func TestPlatformGrantWithoutACatalog(t *testing.T) // max only -> 200; plans set -> 400 grant.no_catalog |
| -func TestPlatformRevokeAndRegrant(t *testing.T) // revoke -> state revoked, credentials_revoked counted; PUT again -> active |
| +func TestPlatformRevokeAndRegrant(t *testing.T) // revoke -> state revoked, credentials_ended counted, generation +1; PUT again -> active under the new generation |
| func TestPlatformGrantDoorsAreClosedToEveryRole(t *testing.T) // serviceToken(Admin) at each door -> the closed-door 403 |
| ``` |
| @@ -442,10 +497,12 @@ git commit -m "accounts platform: operator grants and revokes platform status" |
| - Test: `internal/console/platform_credentials_test.go` (create) |
| **Interfaces:** |
| -- Consumes: `svcrole.Platform` (Task 3), `Store.PlatformGrant` (Task 4). |
| +- Consumes: `svcrole.Platform` (Task 3), `Store.PlatformGrant`, `Store.PlatformGenerationLive` (Task 4). |
| - Produces: |
| - `var ErrAppScopedPlatform = errors.New("console: a platform credential is never bound to an app")`; mint returns it, and `ErrNotPlatform` when the account has no active grant (checked inside the mint transaction). |
| - - `CLIPrincipalContext` refuses a `kind='service'` row with role `platform` and a non-empty app, and refuses any row with `platform_account_id != 0` unless its kind is `platform` (Task 10 adds that kind). |
| + - A platform-role row stores `platform_account_id` = its own account and `platform_generation` = the grant's generation read **inside the mint transaction** (Astra r1-2). |
| + - `Principal` gains `PlatformAccountID int64`, `Platform string` (platform sqid) and `PlatformGeneration int64`; zero for every other credential. |
| + - `CLIPrincipalContext` resolves a platform-role row only when its app is empty and `PlatformGenerationLive(row.platform_account_id, row.platform_generation)` holds (Astra r1-2), and refuses any non-platform row whose `platform_account_id` or `platform_generation` is not 0 (Task 10 adds the `platform` kind). |
| - [ ] **Step 1: Write the failing tests** |
| @@ -455,12 +512,16 @@ func TestServicesDoorMintsAPlatformCredentialOnlyOnAGrantedAccount(t *testing.T) |
| // grant -> 201 with role "platform" and app "". (Task 8 adds the assertion that its doors are the platform patterns.) |
| func TestPlatformCredentialTakesNoApp(t *testing.T) // {role:"platform", app:"site"} -> 400 platformCopy["svc.platform_app"] |
| func TestPlatformRoleRowWithAnAppDoesNotResolve(t *testing.T) // raw row kind service role platform app "x" -> CLIPrincipal ok == false |
| -func TestRowWithAPlatformAccountIDOnlyResolvesAsPlatformKind(t *testing.T) // kind service + platform_account_id 5 -> refused |
| +func TestRowWithAPlatformAccountIDOnlyResolvesAsPlatformKind(t *testing.T) // kind service role publish + platform_account_id 5 -> refused |
| +func TestPlatformCredentialFromAnEndedGenerationIsRefused(t *testing.T) { // (Astra r1-2) |
| + // mint P under gen 1; RevokePlatformGrant; PutPlatformGrant (gen 2, active): P -> 401 at a platform door; |
| + // a fresh mint now resolves with PlatformGeneration 2. |
| +} |
| func TestBrowserMintFormDoesNotOfferPlatform(t *testing.T) // servicePane's ServiceRoles has no "platform" |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestServicesDoorMintsAPlatform|TestPlatformCredentialTakesNoApp|TestPlatformRoleRowWithAnApp|TestRowWithAPlatformAccountID|TestBrowserMintFormDoesNotOfferPlatform' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** In `claimRawNewServicePrincipalScoped` (`svcprincipal.go:355`), beside the Service rule: Platform with an app is `ErrAppScopedPlatform`; inside the existing transaction, a Platform mint on an account whose grant row is missing or not active is `ErrNotPlatform`. Map both in `handleAPIServiceCreate` (`apiservices.go:256-299`) to 400 and 409 with the copy rows. Add `platform_account_id` to the `CLIPrincipalContext` SELECT and the checks above. `servicePane` skips `svcrole.Platform` when building `ServiceRoles`. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestServicesDoorMintsAPlatform|TestPlatformCredentialTakesNoApp|TestPlatformRoleRowWithAnApp|TestRowWithAPlatformAccountID|TestPlatformCredentialFromAnEndedGeneration|TestBrowserMintFormDoesNotOfferPlatform' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** In `claimRawNewServicePrincipalScoped` (`svcprincipal.go:355`), beside the Service rule: Platform with an app is `ErrAppScopedPlatform`; inside the existing transaction, read the grant: missing or not active is `ErrNotPlatform`; otherwise insert with that generation (Astra r1-2). The services door is person-only, so a mint paused across a revoke and re-grant takes the generation current at its insert, which is the authority its owner holds then. Map both in `handleAPIServiceCreate` (`apiservices.go:256-299`) to 400 and 409 with the copy rows. Add `platform_account_id` and `platform_generation` to the `CLIPrincipalContext` SELECT and the checks above. `servicePane` skips `svcrole.Platform` when building `ServiceRoles`. |
| - [ ] **Step 4: Run** the Step 2 command plus `-run 'TestServiceCreate|TestCLIPrincipal'`. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| @@ -512,12 +573,30 @@ git commit -m "console: mint platform credentials on granted accounts only" |
| GraceEnds *time.Time `json:"grace_ends,omitempty"` |
| } |
| func validPlatformRef(ref string) bool // 1-64 of [A-Za-z0-9._:-] |
| + // finishPendingMints finishes every pending mint of the platform, oldest first: MintLinkedAccount |
| + // with the mint's id (idempotent, Task 2), startNewAccountAnalytics, CreateLinkedAccount. The caller |
| + // holds s.lockAccount(platform.Sqid). It stops at the first failure and returns it (Astra r1-1). |
| + func (s *Server) finishPendingMints(ctx context.Context, platform *Account) error |
| + // Test seam, nil in production: called with "lock" just before create takes the platform lock, |
| + // "mint" before MintLinkedAccount and "finish" before CreateLinkedAccount; a non-nil error is |
| + // treated as that step failing. A test may block in it to interleave. |
| + platformMintStep func(step string) error // field on Server |
| ``` |
| - List reply `{"platform": sqid, "max_customers": n, "count": n, "customers": [...]}`; create reply 201 `{"created": true, "customer": view}` or 200 `{"created": false, "customer": view}` on a ref hit. |
| -`platformGate` order: `apiPrincipalAccount` (service binding or membership; the family's 404) → a person who is not an owner gets 403 `door.not_owner` → `PlatformGrant` missing is 403 `door.not_platform`, revoked is 403 `door.revoked`. `platformCustomer`: `LinkedCustomer(platform.Sqid, PathValue("customer"))` nil is the stdlib 404, whatever the reason. |
| +`platformGate` order: `apiPrincipalAccount` (service binding or membership; the family's 404) → a person who is not an owner gets 403 `door.not_owner` → `PlatformGrant` missing is 403 `door.not_platform`, revoked is 403 `door.revoked` (a service principal of an ended generation never gets here: resolution refused it, Task 7) → when the platform has pending mints, take `s.lockAccount(platform.Sqid)`, run `finishPendingMints`, and release the lock before the handler runs (the lock is not re-entrant; create takes it again in its step 2); on a read door a failure is logged and the request goes on, on a write door it is 502 `create.failed` (Astra r1-1). One indexed query when there are none. `platformCustomer`: `LinkedCustomer(platform.Sqid, PathValue("customer"))` nil is the stdlib 404, whatever the reason. |
| + |
| +Create, in order. The invariant (Astra r1-1): **one live account per (platform, ref), and a promised account uses capacity from the moment it is promised until it exists.** It holds because the promise (`ReservePlatformMint`) is written before the bucket is touched, the bucket write is idempotent on the promise's id, and every path finishes promises before it reads capacity or refs. |
| + |
| +1. Decode `{name, ref, plan}` → `ValidAccountName` (`create.name`) → `ref == "" || validPlatformRef` (`create.ref`) → plan: empty means `Grant.DefaultPlan`; non-empty must be in `Grant.Plans` (`create.plan`); with no catalog a named plan is `create.no_catalog_plan`. |
| +2. Take `s.lockAccount(platform.Sqid)`, the lock platform deletion also takes (Astra r1-3). Under it, re-read: `AccountByIDContext(platform.ID)` nil is the stdlib 404, and the grant must still be active with the generation the gate saw, else 403 `door.revoked`. Nothing below runs for a platform being deleted or revoked. |
| +3. `finishPendingMints` (502 `create.failed` on error). This is what makes a retry after a failed finish, or the first request after a restart, land on the account the first attempt minted. |
| +4. A ref held by a live customer: answer 200 with it, spending nothing. |
| +5. `allowCreate(P)` (`create.rate`, 429) → `LinkedCustomerCount >= MaxCustomers` (pending mints included) is 409 `create.cap`. |
| +6. `ReservePlatformMint` with a fresh mint id (`newCredentialID()`'s 128 random bits, hex). |
| +7. `domains.MintLinkedAccount(..., mintID, now)` → `startNewAccountAnalytics` → `CreateLinkedAccount` (`MintID`; plan reason `fmt.Sprintf("platform %s", platform.Sqid)`, by `Actor`) → audit on the platform account (`audit.customer_create`) and on the customer (`audit.customer_created_by`) → 201. |
| -Create, in order: decode `{name, ref, plan}` → `ValidAccountName` (`create.name`) → `ref == "" || validPlatformRef` (`create.ref`) → plan: empty means `Grant.DefaultPlan`; non-empty must be in `Grant.Plans` (`create.plan`); with no catalog a named plan is `create.no_catalog_plan` → take `s.lockAccount(platform.Sqid)` → ref hit: answer 200 with it, spending nothing → `allowCreate(P)` (`create.rate`, 429) → `LinkedCustomerCount >= MaxCustomers` is 409 `create.cap` → `domains.MintLinkedAccount` → `startNewAccountAnalytics` → `CreateLinkedAccount` (plan reason `fmt.Sprintf("platform %s", platform.Sqid)`, by `Actor`) → audit on the platform account (`audit.customer_create`) and on the customer (`audit.customer_created_by`) → 201. Mint or row failures log the sqid like `mintAccount` does (`server.go:3155-3190`) and answer 502 `create.failed`. |
| +A failure in step 7 leaves the pending mint in place, logs the mint id (and the sqid once known) like `mintAccount` does (`server.go:3155-3190`), and answers 502 `create.failed`. The pending mint keeps counting against the cap and keeps its ref, and the next platform request finishes it. A console restart in between converges too: `MaterializeAccounts` births the stranded manifest as a linked account with its ref (Task 5), and the next `finishPendingMints` finds that manifest by mint id and finishes over the existing row (`CreateLinkedAccount`'s materialized case). No path deletes a pending mint except finishing it. |
| Usage: the customer's `plan_cap_state` rows whose `Period == capPeriod(Cap, now)`, in `capOrder`. The list must not run two queries per customer (up to 10000 of them on a one-connection database), so it reads both in two queries through a new store method in `platform_store.go`: |
| @@ -540,6 +619,27 @@ func TestCustomerCreateMintsALinkedOwnerlessAccount(t *testing.T) |
| // 201; manifest Platform == platform sqid, Owner ""; Members empty; plan row source platform, plan == grant default |
| func TestCustomerCreateIsIdempotentOnRef(t *testing.T) // second create, same ref, other name -> 200 created:false, same sqid |
| func TestCustomerCreateConcurrentSameRefMakesOneAccount(t *testing.T) // 8 goroutines, same ref -> one sqid, LinkedCustomerCount == 1 |
| +func TestCustomerCreateSurvivesAFailedFinish(t *testing.T) { // (Astra r1-1): failure injection, retry, restart |
| + // max_customers 1. platformMintStep fails "finish" once: create ref 4812 -> 502; one manifest with Platform == p, |
| + // no account row, one pending mint; LinkedCustomerCount == 1. |
| + // create ref 4813 -> 409 create.cap (the pending mint holds the only slot), and no new manifest. |
| + // retry ref 4812 -> 200 created:false (finished by step 3, then the ref hit); same sqid as the stranded manifest; |
| + // accounts/ holds exactly one manifest for p; pending mints empty. |
| +} |
| +func TestCustomerCreateSurvivesAFailedMintPut(t *testing.T) { // (Astra r1-1) |
| + // releases wrapper whose first Put on accounts/ lands the object and then errors: create -> 502; |
| + // retry -> 200 or 201 with the sqid of the object that landed; one manifest for p. |
| +} |
| +func TestCustomerCreateConvergesAcrossARestart(t *testing.T) { // (Astra r1-1) |
| + // platformMintStep fails "finish": 502. Close the Server; NewServer over the SAME console.db and DirStore |
| + // (startup runs MaterializeAccounts, Task 5). GET .../customers -> exactly one customer, ref "4812", |
| + // plan_source "platform" (the gate finished the mint over the materialized row); pending mints empty. |
| +} |
| +func TestCustomerCreateRechecksThePlatformUnderTheLock(t *testing.T) { // (Astra r1-3) |
| + // the test holds s.lockAccount(p), starts a create and waits for platformMintStep("lock"), deletes the |
| + // platform with Store.DeleteAccount (it has no customers yet), and releases: the create answers the stdlib 404 |
| + // and writes no manifest and no pending mint. Same with a revoke in place of the delete: 403 door.revoked. |
| +} |
| func TestCustomerCreateRefusesAPlanOutsideTheGrant(t *testing.T) |
| func TestCustomerCreateStopsAtMaxCustomers(t *testing.T) // max 2: third 409 create.cap; lower the grant to 1: existing two still listed |
| func TestCustomerCreateRefusesBadNamesAndRefs(t *testing.T) // "Shop!", ref "a b", ref of 65 chars, ref "é" -> 400 |
| @@ -548,7 +648,7 @@ func TestCustomerDoorsHideOtherPlatformsCustomers(t *testing.T) // platform A's |
| func TestPlatformCredentialRefusedAtOrdinaryDoors(t *testing.T) // GET /api/cli/apps/<platform>, POST /api/cli/services/<platform> -> role refusal, not 200 |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPlatformDoor|TestAdminCredentialIsRefusedAtPlatformDoors|TestCustomerCreate|TestCustomerListAndShow|TestCustomerDoorsHide|TestPlatformCredentialRefusedAtOrdinaryDoors' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPlatformDoor|TestAdminCredentialIsRefusedAtPlatformDoors|TestCustomerCreate|TestCustomerListAndShow|TestCustomerDoorsHide|TestPlatformCredentialRefusedAtOrdinaryDoors' -count=1`. Expected: FAIL. (The restart test opens a second `Server`; it needs no sockets, but if any fixture does, use `TMPDIR=/tmp/g`.) |
| - [ ] **Step 3: Implement** `apiplatformcustomers.go` and the three declarations (a block after the services family, `routedecls.go:943-946`, with a comment naming spec §6.1 and that Admin is out on purpose). |
| - [ ] **Step 4: Run** the Step 2 command plus `-run 'TestEveryCLIDoorNamesItsRoles|TestNoRoleReachesAMintFleetOrPolicyDoor|TestRouteDeclsMatchRegistrations'`. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| @@ -579,7 +679,9 @@ Update: write budget; nothing to change is 400 `update.empty`; a name runs `Vali |
| Delete: write budget; take `s.lockAccount(customer.Sqid)` for the rest; `LinkedCustomer.Owners > 0` is 409 `delete.claimed`; `AppCount > 0` is 409 `delete.apps`; then `tombstoneAccount` (bucket first, `ownership.go:672`), `s.manifestSeen.Delete`, `DeleteUnclaimedCustomer`, `auditAccountDeleted`. A bucket failure is 502 `delete.failed` and nothing is deleted. If `DeleteUnclaimedCustomer` refuses after the tombstone (an owner added box-side by `console member` in that window), log one line naming the account and answer 409 `delete.claimed`: the same accepted hazard `deleteAccountNow` documents (`ownership.go:196-201`), and the lock is what slice 2's claim must take to close it for claims. |
| -Platform account deletion: `deletionRefused` (`ownership.go:161`) adds, before the app count, a refusal when `LinkedCustomerCount(acct.Sqid) > 0` (flash `delete.platform_has_customers`), and a refusal for a linked account deleted by a person in the browser (flash `delete.linked`): until slice 2's leave, a linked account's end is its platform's door (decision D11). |
| +Platform account deletion: `deletionRefused` (`ownership.go:161`) adds, before the app count, a refusal when `LinkedCustomerCount(acct.Sqid) > 0` (live customers and pending mints; flash `delete.platform_has_customers`), and a refusal for a linked account deleted by a person in the browser (flash `delete.linked`): until slice 2's leave, a linked account's end is its platform's door (decision D11). |
| + |
| +Serializing deletion with creation (Astra r1-3). The invariant: **no customer, pending or live, can appear between the deletion's last check and its tombstone.** `deleteAccountNow` (`ownership.go:183`) takes `s.lockAccount(acct.Sqid)` as its first line and holds it to the end, so its existing re-run of `deletionRefused` and the tombstone and `DeleteAccount` all happen while customer create (which takes the same lock before reserving, Task 8 step 2) cannot run; a create that was waiting re-reads the platform afterwards and finds it gone. Lock order: on the billing path `retireForDeletion` holds the billing hold (`billingretire.go:228`) and then `deleteAccountNow` takes the account lock; nothing in this plan, and no existing `lockAccount` caller found (`grep -n 's.lockAccount(\|s.planLock(' internal/console/*.go`), takes the billing hold while holding the account lock. `deleteAccountNow`'s callees take no account lock. The test seam `deleteBeforeTombstone func()` (nil in production) is called after the re-check, before `tombstoneAccount`. |
| - [ ] **Step 1: Write the failing tests** |
| @@ -592,9 +694,20 @@ func TestCustomerDeleteTombstonesAnUnclaimedAccount(t *testing.T) // manifest De |
| func TestCustomerDeleteRefusesClaimedOrAppHolding(t *testing.T) // AddMember owner -> 409 delete.claimed; CreateAppIn -> 409 delete.apps; manifest untouched |
| func TestPlatformAccountDeletionRefusedWithCustomers(t *testing.T) // browser POST delete on the platform account -> flash delete.platform_has_customers, manifest not tombstoned |
| func TestLinkedAccountBrowserDeletionRefused(t *testing.T) // console member owner of a customer -> flash delete.linked |
| +func TestPlatformDeletionWaitsForAnInFlightCreate(t *testing.T) { // (Astra r1-3): creation first |
| + // platformMintStep blocks at "mint" (the create holds the platform lock and its pending mint exists); |
| + // the owner's browser delete of the platform starts and waits; release the create -> 201; |
| + // the delete then refuses with delete.platform_has_customers; the platform's manifest is not tombstoned |
| + // and a fresh MaterializeAccounts reaps nothing. |
| +} |
| +func TestCreateWaitsForAnInFlightPlatformDeletion(t *testing.T) { // (Astra r1-3): deletion first |
| + // deleteBeforeTombstone blocks (the delete holds the lock, its checks passed); a customer create starts and |
| + // waits; release the delete -> platform deleted; the create answers the stdlib 404; no customer manifest and |
| + // no pending mint exist. |
| +} |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestCustomerRename|TestCustomerPlanChange|TestCustomerDelete|TestPlatformAccountDeletionRefused|TestLinkedAccountBrowserDeletionRefused' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestCustomerRename|TestCustomerPlanChange|TestCustomerDelete|TestPlatformAccountDeletionRefused|TestLinkedAccountBrowserDeletionRefused|TestPlatformDeletionWaitsForAnInFlightCreate|TestCreateWaitsForAnInFlightPlatformDeletion' -count=1`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** the Step 2 command plus `-run 'TestDeleteAccount|TestHandleDeleteAccount|TestAccountPlan'`. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| @@ -616,8 +729,8 @@ git commit -m "console: platforms rename, re-plan and delete unclaimed customers |
| **Interfaces:** |
| - Consumes: Tasks 4, 7, 8. |
| - Produces: |
| - - `const cliKindPlatform = "platform"` in the `authstore.go:390` block, with a comment: bound to one customer account, minted only by the platform door, expiring, live only while its link and grant are. |
| - - `Principal` gains `PlatformAccountID int64` and `Platform string` (the platform's sqid); both zero for every other kind. |
| + - `const cliKindPlatform = "platform"` in the `authstore.go:390` block, with a comment: bound to one customer account, minted only by the platform door, expiring, live only while its link and its grant generation are. |
| + - Fills `Principal.PlatformAccountID`, `Platform` and `PlatformGeneration` (added in Task 7). |
| - ```go |
| const ( |
| PlatformCredentialDefaultTTL = time.Hour |
| @@ -630,6 +743,8 @@ git commit -m "console: platforms rename, re-plan and delete unclaimed customers |
| ) |
| type PlatformCredentialRequest struct { |
| CustomerID, PlatformAccountID int64 |
| + Generation int64 // the grant generation the platform gate admitted the caller under (Astra r1-2) |
| + Minter Principal // re-checked inside the insert transaction |
| Name string // the minter's handle: the platform credential's name, or the person's address |
| MintedBy string // auditActor of the minter |
| Role svcrole.Role |
| @@ -638,16 +753,20 @@ git commit -m "console: platforms rename, re-plan and delete unclaimed customers |
| TTL time.Duration // 0 means PlatformCredentialDefaultTTL |
| } |
| func (s *Store) NewPlatformCustomerCredential(ctx context.Context, req PlatformCredentialRequest, now time.Time) (raw string, expiresAt time.Time, err error) |
| - func (s *Store) platformLinkLive(ctx context.Context, customerID, platformAccountID int64) (platformSqid string, ok bool) |
| + func (s *Store) platformLinkLive(ctx context.Context, q dbQuerier, customerID, platformAccountID, generation int64) (platformSqid string, ok bool) |
| + var ErrPlatformAuthorityEnded = errors.New("console: the platform's grant or the minter's authority ended during the request") |
| + // Test seam, nil in production: called after the door's checks, before the insert transaction begins. |
| + platformCredentialBeforeInsert func() // field on Server |
| ``` |
| - Door: `POST /api/cli/platform/{account}/customers/{customer}/credentials`, `Exactly(Platform)`, handler `handlePlatformCredentialMint`, body `{role, app, rungs, ttl_seconds}`, reply 201 `{"token", "account", "role", "app", "rungs", "expires_at"}`. |
| -Rules: |
| -- Mint: role Publish needs app "" and no rungs; role Deploy needs an app the customer holds (`HasAppIn`, else stdlib 404) and rungs through `canonicalRungs` (stable refused as today); anything else is `ErrPlatformCredentialRole`. TTL outside [1 min, 24 h] is `ErrPlatformCredentialTTL`. Row: `kind 'platform'`, `account_id` customer, `platform_account_id`, `address = MintedBy`, `name = Name`, `role`, `app`, `rungs`, fresh `credential_id`, `expires_at = now + TTL`. |
| -- Resolve (`CLIPrincipalContext`, new `case cliKindPlatform`): `expires != 0 && now <= expires` (0 is refused, never "never"); role Publish with app "" and rungs "", or Deploy with app and readable rungs; commands and scope empty; `platformLinkLive` true. `platformLinkLive` is one query: the customer row live with `platform` equal to the platform row's sqid, the platform row live, and its grant `active`. Anything else is `Principal{}, false`, the unknown-token 401. |
| +Rules. The invariant (Astra r1-2): **a per-customer credential is valid only under the grant generation it was minted in, and it is only ever written while that generation is current and its minter still holds authority under it.** Both halves ask `PlatformGenerationLive` (Task 4), so resolution and minting cannot disagree. |
| +- Mint, shape: role Publish needs app "" and no rungs; role Deploy needs an app the customer holds (`HasAppIn`, else stdlib 404) and rungs through `canonicalRungs` (stable refused as today); anything else is `ErrPlatformCredentialRole`. TTL outside [1 min, 24 h] is `ErrPlatformCredentialTTL`. |
| +- Mint, authority, **inside the insert transaction** (Astra r1-2): `platformLinkLive(tx, CustomerID, PlatformAccountID, Generation)` must hold; a service minter's own row (by `Minter.CredentialID`) must still be unrevoked, role platform, with `platform_generation == Generation`; a person minter must still hold `owner` on the platform account. Any failure is `ErrPlatformAuthorityEnded` and nothing is written. Row: `kind 'platform'`, `account_id` customer, `platform_account_id`, `platform_generation = Generation`, `address = MintedBy`, `name = Name`, `role`, `app`, `rungs`, fresh `credential_id`, `expires_at = now + TTL`. The door maps `ErrPlatformAuthorityEnded` to 403 `door.revoked`. |
| +- Resolve (`CLIPrincipalContext`, new `case cliKindPlatform`): `expires != 0 && now <= expires` (0 is refused, never "never"); role Publish with app "" and rungs "", or Deploy with app and readable rungs; commands and scope empty; `platformLinkLive(db, account_id, platform_account_id, platform_generation)` true. `platformLinkLive` is `PlatformGenerationLive` plus the customer row live with `platform` equal to the returned platform sqid: one query. Anything else is `Principal{}, false`, the unknown-token 401. |
| - `auditActor` (`apicli.go:118`): `p.Platform != ""` renders `"platform:" + p.Platform + "/" + p.Name`. |
| - `principalKey` is unchanged: `service:<customer id>/<name>`, so each customer has its own budgets. |
| -- Door: platform gate, `platformCustomer`, write budget, then the mint, then audit on the customer (`audit.credential`). |
| +- Door: platform gate, `platformCustomer`, write budget, `platformCredentialBeforeInsert`, then the mint with `Generation: caller.Grant.Generation` and `Minter: caller.P`, then audit on the customer (`audit.credential`). |
| - `CLITokensContext` (`authstore.go:861`) excludes kind platform as it excludes link: these are the customer account's credentials, not the minter's terminals. `ServicePrincipals` stays `kind IN (service, app)`; `RevokeAccountToken` already reaches them by id (decision D10). |
| - The door is a credential mint reached by a credential. It is the one deliberate exception to "a credential may never mint a credential" (`svcroutes_test.go:35-91`): what it mints is narrower than its minter in every dimension (one account, Publish at most, expiring, refused when the link or grant ends, and kind platform reaches no mint door). Say so in the declaration's comment. |
| @@ -656,12 +775,21 @@ Rules: |
| ```go |
| func TestCustomerCredentialResolvesToTheCustomerOnly(t *testing.T) |
| // CLIPrincipal: Kind PrincipalService, AccountID customer, Role Publish, Platform "bcd", PlatformAccountID P |
| -func TestCustomerCredentialRefusedOnASecondCustomer(t *testing.T) // GET /api/cli/apps/<customer2>/x/channels -> stdlib 404 |
| +func TestCustomerCredentialRefusedOnASecondCustomer(t *testing.T) { // (Astra r1-5) |
| + // app "site" created in c1 with T1 and in c2 with T2 (each 200 through its own credential, and each |
| + // T reads its own .../site/channels -> 200), THEN: T1 GET /api/cli/apps/<c2>/site/channels -> stdlib 404, |
| + // T1 POST /api/cli/apps/<c2>/site/promote -> stdlib 404, T2 at <c1>/site -> stdlib 404. |
| +} |
| func TestCustomerCredentialExpiryBoundary(t *testing.T) // default TTL 1h; at expires_at ok; +1s refused; ttl 25h -> 400 cred.ttl; 30s -> 400 |
| func TestCustomerCredentialRefusedAfterRevokeAndLinkGone(t *testing.T) |
| - // RevokePlatformGrant -> 401; re-grant -> still 401 (row revoked); a fresh credential, then DeleteUnclaimedCustomer -> 401 |
| -func TestCustomerCredentialRefusedWhileGrantRevokedEvenUnrevokedRow(t *testing.T) |
| - // set grant state revoked by SQL without touching cli_tokens -> 401 (the per-request check, not only the row revoke) |
| + // RevokePlatformGrant -> 401; re-grant -> still 401 (its generation ended; no cli_tokens row was touched); |
| + // a fresh credential (new generation) works, then DeleteUnclaimedCustomer -> 401 |
| +func TestCustomerCredentialMintPausedAcrossRevokeAndRegrant(t *testing.T) { // (Astra r1-2) |
| + // platformCredentialBeforeInsert blocks; while the mint (by platform credential P, gen 1) waits: RevokePlatformGrant, |
| + // PutPlatformGrant (gen 2, active). Release: 403 door.revoked; no kind 'platform' row exists for the customer. |
| + // Repeat with a person owner as minter: also 403 (the generation changed under it), no row. |
| + // Repeat with only a revoke of P's own row (RevokeServicePrincipal) during the pause: 403, no row. |
| +} |
| func TestCustomerCredentialAuditNamesThePlatform(t *testing.T) // create an app with it: audit actor "platform:bcd/cms" |
| func TestCustomerCredentialNeverReachesPersonOrMintDoors(t *testing.T) |
| // POST services/<customer>, instance-token, accounts/<customer>/plan, domains/purchases, platform/<customer>/customers -> refused |
| @@ -722,19 +850,24 @@ git commit -m "carlos platform: customers and per-customer credentials" |
| ### Task 12: A static site's first host from a service credential (§6.3) |
| -**Decision (D3), the smaller fix and why.** The spec offers two fixes. The `domains kind:"static"` route cannot do it: on a console with `CONSOLE_RESERVE_PLATFORM_DOMAINS=true` (the flagship and Tito) every host under the apps domain, including the app's own `<app>.<sqid>.<apps-domain>`, is reserved (`domainHostPolicy`, `domainpolicy.go:73`; `reservedDomainsWith`, `apidomains.go:163`). And `carlos deploy` with a Publish credential stops earlier than the spec says: `GET .../instances` admits Instance and Deploy only (`routedecls.go:613`), so `deploy.go:397` exits on the 403 before the first-host step. Opening `PUT instances-manifest` to Publish is the other spec option, but `policyDoors` (`svcroutes_test.go:89`) pins it shut to every role on purpose. The smaller fix that keeps that pin: add Publish to the instance list, and add one narrow Publish door that does exactly what `mintPlatformHost` does for a person, with no caller-chosen manifest field: write the default manifest only when there is none, then create the static record at `<app>.<manifest domain>`. Any CI Publish credential benefits, not only platforms. |
| +**Decision (D3), the smaller fix and why.** The spec offers two fixes. The `domains kind:"static"` route cannot do it: on a console with `CONSOLE_RESERVE_PLATFORM_DOMAINS=true` (the flagship and Tito) every host under the apps domain, including the app's own `<app>.<sqid>.<apps-domain>`, is reserved (`domainHostPolicy`, `domainpolicy.go:73`; `reservedDomainsWith`, `apidomains.go:163`). And `carlos deploy` with a Publish credential stops earlier than the spec says: `GET .../instances` admits Instance and Deploy only (`routedecls.go:613`), so `deploy.go:397` exits on the 403 before the first-host step. Opening `PUT instances-manifest` to Publish is the other spec option, but `policyDoors` (`svcroutes_test.go:89`) pins it shut to every role on purpose. The smaller fix that keeps that pin: add Publish to the instance list, and add one narrow Publish door that creates the app's static record at `<app>.<sqid>.<apps-domain>`, with no caller-chosen field but channel and message. **It writes no manifest (Astra r1-4).** Reconcile serves a record whose app has no instances manifest: an absent manifest reads as "no seed" and "no policy", and "a record already written is truth regardless; the manifest only governs the API door" (`provision/reconcile.go:1628-1660`), which is also how the domains door's static first route has always served. So the only thing the create handler needs the manifest for is its own admission (the host suffix, the default channel), and the door supplies that in memory. Any CI Publish credential benefits, not only platforms. |
| **Files:** |
| - Create: `internal/console/apiplatformhost.go`, `internal/console/apiplatformhost_test.go`, `deploy_platformhost.go` |
| -- Modify: `internal/console/routedecls.go`, `deploy.go` (`mintPlatformHost :1086`), `deploy_test.go` |
| +- Modify: `internal/console/routedecls.go`, `internal/console/apiinstances.go` (`instanceManifest :161`, one branch), `deploy.go` (`mintPlatformHost :1086`), `deploy_test.go` |
| **Interfaces:** |
| - Produces: |
| - `GET /api/cli/apps/{account}/{app}/instances` Allow becomes `svcrole.Allow(svcrole.Instance, svcrole.Deploy, svcrole.Publish)`. |
| - `POST /api/cli/apps/{account}/{app}/platform-host`, `Kind: kindCLI, Allow: svcrole.Allow(svcrole.Publish)`, handler `handleAPIPlatformHost`, body `{channel, message}`, reply exactly the instance-create door's reply. |
| - CLI: `func (s *apiSession) platformHost(ctx context.Context, a apiAcct, app, channel, message string) (apiInstanceRecord, error)` in `deploy_platformhost.go`. |
| + - `type defaultManifestKey struct{}` and `func withDefaultManifest(ctx context.Context, m *provision.Manifest) context.Context` in `apiplatformhost.go`; `handleAPIPlatformHost` is their only caller. |
| -Handler: `apiAccountApp` → `instancesDomain(acct)` (`apiinstances.go:3783`) → `readEnableManifest` (`:3814`); when it reports `created`, `writeEnableManifest` (`:3841`) with the manifest exactly as read (the enable door's defaults for nil fields, `handleAPIInstanceEnable :3637`), audit detail `audit.platform_host_enable`; an existing manifest is left alone → then delegate to `s.handleAPIInstanceCreate(w, r2)` where `r2` is `r.Clone(r.Context())` with the body replaced by `{"host": app + "." + m.Domain, "kind": "static", "channel": channel, "message": message}`. Delegating keeps every create rule (control-plane refusal, lifetimes, host suffix check, caps) in one place, and the caller chooses nothing but channel and message. |
| +The invariant (Astra r1-4): **the platform-host door performs no write of its own; every write is the instance-create handler's, after that handler's refusals and under its locks.** So a refused request leaves the manifest, the audit trail and the serial exactly as they were, and the copies lock contract is the create handler's unchanged (it takes `beginCopiesMutation` itself, `apiinstances.go:2626`; this door takes no lock). |
| + |
| +Handler: `apiAccountApp` → body `{channel, message}` (channel required: `release.ValidChannel`, else 400 with the enable door's existing "invalid channel name") → `instancesDomain(acct)` (`apiinstances.go:3783`) → `readEnableManifest` (`:3814`; read-only: on an absent manifest it returns the default, with a born-HA app's pool and regions bound in memory by `haManifestBinding`) → delegate to `s.handleAPIInstanceCreate(w, r2)`, where `r2 := r.Clone(ctx)` with `ctx = withDefaultManifest(r.Context(), m)` only when the manifest was absent, and the body replaced by `{"host": app + "." + m.Domain, "kind": "static", "channel": channel, "message": message}`. `instanceManifest` (`apiinstances.go:161`) gains one branch: on `os.ErrNotExist`, a manifest carried by `defaultManifestKey` is returned instead of the 409. Nothing else reads the key. Delegating keeps every create rule (the service control-plane refusal at `:1597`, lifetimes, the host suffix check, the caps, `staticHeadRefusal`) in one place. |
| + |
| +`audit.platform_host_enable` is dropped from the copy table: the door writes no audit row of its own; the create handler's record audit stands. |
| CLI: in `mintPlatformHost` (`deploy.go:1086`), when `instancesEnable` fails with `*enableError` status 403, call `sess.platformHost` instead and print the same `minted` line. A 404 from `platform-host` (an older console) returns the original 403 error unchanged. |
| @@ -743,22 +876,29 @@ CLI: in `mintPlatformHost` (`deploy.go:1086`), when `instancesEnable` fails with |
| ```go |
| // internal/console |
| func TestPublishCredentialListsInstances(t *testing.T) // serviceToken(Publish) GET instances -> 200 |
| -func TestPlatformHostDoorMintsTheAppsStaticHost(t *testing.T) // fresh app: manifest Domain "<sqid>.<apps-domain>"; record Kind static at app.<domain>, Channel as sent |
| -func TestPlatformHostDoorLeavesAnExistingManifestAlone(t *testing.T) // pre-written manifest with a Channel: bytes unchanged after the call |
| +func TestPlatformHostDoorMintsTheAppsStaticHost(t *testing.T) // fresh app: record Kind static at app.<sqid>.<apps-domain>, Channel as sent; NO instances manifest exists afterwards (Astra r1-4) |
| +func TestPlatformHostRecordServesWithoutAManifest(t *testing.T) // provision reconcile over the store mints the static route for that record (the reconcile.go:1628 contract, pinned here) |
| +func TestPlatformHostDoorLeavesAnExistingManifestAlone(t *testing.T) // pre-written manifest with a Channel: bytes and etag unchanged after the call |
| func TestPlatformHostDoorRoles(t *testing.T) // Publish and Admin pass; Deploy, Instance, Operate -> role refusal |
| -func TestPlatformHostDoorRefusesAControlPlaneApp(t *testing.T) // the instance-create refusal, nothing written |
| +func TestPlatformHostDoorRefusalsWriteNothing(t *testing.T) { // (Astra r1-4) |
| + // For each refusal: a control-plane app (service credential), a bad channel, a channel whose head is not static, |
| + // an app at its running-things cap: snapshot the app's instances.json (absent), its audit rows and control/serial; |
| + // call the door; assert the refusal status, and that the manifest is still absent, the audit rows are the same, |
| + // and control/serial is unchanged. |
| +} |
| +func TestDefaultManifestKeyIsReadOnlyByInstanceManifest(t *testing.T) // source scan: defaultManifestKey appears only in apiplatformhost.go and instanceManifest |
| // root |
| func TestMintPlatformHostFallsBackForAServiceCredential(t *testing.T) // fake: PUT instances-manifest 403, POST platform-host 200 -> record returned, "minted" line printed |
| func TestMintPlatformHostOnAnOlderConsole(t *testing.T) // platform-host 404 -> the 403 error is returned |
| ``` |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPublishCredentialListsInstances|TestPlatformHostDoor' -count=1` and `go test . -run 'TestMintPlatformHost' -count=1`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestPublishCredentialListsInstances|TestPlatformHost|TestDefaultManifestKey' -count=1` and `go test . -run 'TestMintPlatformHost' -count=1`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** Update any role pin the instance-list change trips (search `svcroutes_test.go` and `deploydoors_test.go` for the list pattern) with a comment: Publish reads the records of an app it already deploys and manages hostnames for. |
| - [ ] **Step 4: Run** the Step 2 commands plus `go test ./internal/console/ -run 'TestEveryCLIDoorNamesItsRoles|TestInstanceRoleMatchesTodaysAppTokenReach|TestDeployReachesExactlyItsDoors|TestNoRoleReachesAMintFleetOrPolicyDoor' -count=1`. Expected: PASS. |
| - [ ] **Step 5: Commit** |
| ```bash |
| -git add internal/console/apiplatformhost*.go internal/console/routedecls.go internal/console/*_test.go deploy.go deploy_platformhost.go deploy_test.go |
| +git add internal/console/apiplatformhost*.go internal/console/apiinstances.go internal/console/routedecls.go internal/console/*_test.go deploy.go deploy_platformhost.go deploy_test.go |
| git commit -m "deploy: a Publish credential can give a static app its first host" |
| ``` |
| @@ -831,14 +971,20 @@ func TestE2EPlatformCustomerStaticSite(t *testing.T) { |
| // 5. t.Setenv CARLOS_SERVICE_TOKEN=P, CARLOS_CONSOLE=ts.URL: |
| // carlos platform customers create --platform <p> --name shop --ref 4812 --json -> customer c1; |
| // again with --name bakery --ref 4813 -> c2. |
| - // 6. carlos platform credentials mint --platform <p> --customer c1 --json -> token T (expires_at within 1h). |
| - // 7. CARLOS_SERVICE_TOKEN=T: runDeploy(-app site -account c1 -kind static -version sha0001 -channel <entry> site/) |
| + // 6. carlos platform credentials mint --platform <p> --customer c1 --json -> token T1 (expires_at within 1h); |
| + // the same for c2 -> T2. |
| + // 7. CARLOS_SERVICE_TOKEN=T1: runDeploy(-app site -account c1 -kind static -version sha0001 -channel <entry> site/) |
| // -> stdout has "minted site.<c1>.oncarlos.test" and "live https://site.<c1>.oncarlos.test"; |
| // provision.GetRecord(c1, site, host).Kind == "static"; assertServes(edge, "hello", "sha0001"). |
| - // 8. With T: GET /api/cli/apps/<c2>/site/channels -> 404; GET /api/cli/apps/<c1>/site/channels -> 200. |
| - // 9. As the operator: --revoke --reason "witness". With T: GET .../<c1>/site/channels -> 401. |
| + // 8. (Astra r1-5) CARLOS_SERVICE_TOKEN=T2: carlos apps create --account c2 --app site succeeds, and with T2 |
| + // GET /api/cli/apps/<c2>/site/channels -> 200. With T1 GET /api/cli/apps/<c1>/site/channels -> 200. |
| + // So "site" exists in both accounts and each credential works in its own. |
| + // 9. Only now the cross-account assertions, reads and writes: T1 GET /api/cli/apps/<c2>/site/channels -> 404; |
| + // T1 POST /api/cli/apps/<c2>/site/releases (a ship) -> 404, and c2's release list (read with T2) is unchanged; |
| + // T2 GET /api/cli/apps/<c1>/site/channels -> 404. |
| + // 10. As the operator: --revoke --reason "witness". With T1: GET .../<c1>/site/channels -> 401. |
| // With P: GET /api/cli/platform/<p>/customers -> 401. |
| - // 10. The site still serves (assertServes again): revoking stops credentials, not sites. |
| + // 11. The site still serves (assertServes again): revoking stops credentials, not sites. |
| } |
| ``` |
| @@ -952,7 +1098,6 @@ Every row is pending copy review (Task 15). `%s`/`%d` are filled as named. CLI e |
| | audit.customer_rename | renamed customer account %s to %s | |
| | audit.customer_plan | moved customer account %s to the %s plan | |
| | audit.credential | minted a %s credential for %s, valid until %s | |
| -| audit.platform_host_enable | turned on instances for %s to give it its first address | |
| **CLI** (`platform_copy.go`, constants `cliPlatformCopy*`) |
| @@ -1037,10 +1182,12 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta |
| - D1. Platform doors use `/api/cli/platform/{account}/...`, not `{platform}`, so `apiPrincipalAccount`'s binding and membership resolution apply unchanged. |
| - D2. The grant lives in its own `platform_grants` table; the link is `accounts.platform` (the platform's sqid) and `accounts.platform_ref`; per-customer rows carry `cli_tokens.platform_account_id`. |
| -- D3. §6.3: Publish on the instance list plus one narrow `platform-host` door, not the domains route (blocked on reserve consoles) and not opening `instances-manifest` (pinned by `policyDoors`). |
| +- D3. §6.3: Publish on the instance list plus one narrow `platform-host` door that writes no manifest (Astra r1-4), not the domains route (blocked on reserve consoles) and not opening `instances-manifest` (pinned by `policyDoors`). |
| - D4. The manifest also carries `platform_ref`, so ref idempotency survives a console rebuild. |
| - D5. Ref grammar: 1-64 of `A-Z a-z 0-9 . _ : -`, case-sensitive, unique per platform among live accounts. |
| -- D6. Revoking a grant also revokes the rows of every per-customer credential and every platform-role credential of that platform, so a re-grant restores no old credential. The per-request check stays as well. |
| +- D6. Revoking a grant ends its generation; every platform-role and per-customer credential is bound to the generation it was minted in, so a re-grant restores no old credential (Astra r1-2). No token rows are swept. |
| +- D14. Customer creation records a pending mint before touching the bucket; pending mints count against `max_customers` and hold their ref until finished (Astra r1-1). |
| +- D15. Platform deletion and customer creation serialize on `s.lockAccount(platform sqid)` (Astra r1-3). |
| - D7. Budgets: customer create spends `allowCreate` (service 100 a day, person 10) except a ref hit, which spends nothing; update, delete and credential mint spend `allowWrite`. |
| - D8. TTL bounds 1 minute to 24 hours; `max_customers` 1 to 10000. Without a plan catalog a grant has no plans and customers get no plan row. |
| - D9. Linked accounts never take the launch sponsorship. |
| @@ -1055,12 +1202,13 @@ Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and insta |
| - §5.1/§5.2: the link survives a console rebuild, but the grant (and every account's plan row) is console-only, so a rebuilt console keeps links with no grant: the platform is refused until the operator grants again. Accepted for v1; noted for the operator runbook. Without D4, idempotent create would break on rebuild too. |
| - §6.1/AGENTS.md: the per-customer credential door is a credential mint reached by a credential, against the standing "a credential may never mint a credential" cut. The spec's A2 intends it; the plan names it as the one exception and pins it narrower than its minter. |
| - §5.1 is silent on whether re-granting restores the old credentials. D6 says it does not. |
| +- §5.2 says only that the manifest carries `platform`. The plan adds `platform_ref` (D4) and `platform_mint` (the pending-mint id, Astra r1-1); all three are additive and `omitempty`. |
| ## Slice 2/3 hand-offs |
| Slice 2 (claim and leave) needs from slice 1: |
| - `AccountPlatform`, `LinkedCustomer.Owners` (claimed = owners > 0), `DeleteUnclaimedCustomer`'s owner check, and `ErrCustomerClaimed`. Accepting a claim must hold `s.lockAccount(customer.Sqid)`, the lock the platform's delete door holds across its owner check and tombstone, or a claim can land between them. |
| -- Leave/release: clear `accounts.platform` and `platform_ref`, rewrite the manifest without `platform`/`platform_ref` keeping `owner` (a `domains` CAS helper beside `RenameAccountManifest`), revoke kind-platform rows for the account, set the plan row to the catalog default, and lift D11's browser deletion refusal and Task 13's billing refusal for the account (both read `AccountPlatform`, so clearing the column is enough). |
| +- Leave/release: clear `accounts.platform` and `platform_ref`, rewrite the manifest without `platform`/`platform_ref`/`platform_mint` keeping `owner` (a `domains` CAS helper beside `RenameAccountManifest`), revoke kind-platform rows for the account, set the plan row to the catalog default, and lift D11's browser deletion refusal and Task 13's billing refusal for the account (both read `AccountPlatform`, so clearing the column is enough). |
| - Claim must write `owner` into the manifest and teach materialization to adopt a late owner for linked accounts only (spec §7.4); `materializeOwner`'s birth-only rule is untouched by slice 1. |
| - How per-customer credentials appear to a claimed customer (D10): `ServicePrincipals` would add `cliKindPlatform`. |
| - The platform doors gain `POST .../customers/{customer}/claim-links` through `platformGate` and `platformCustomer`. |