platform accounts: final-review fixes (recovery, sweep, minted revoke)
- Recovery checks the database before any effect: a pending mint whose manifest sits at an id held by another account is held before analytics is turned on (Astra I1). The transactional check stays. - The expired-token sweep leaves app-bound kind platform rows to app purge, so the armed claim gate no longer aborts it, and both sweep errors are logged (Fable I1). - Revoking or rotating a platform credential ends the per-customer credentials it minted, in the same transaction, matched by platform, minter name and minter actor address; person-minted rows are kept (Fable I2). Covers revoke by name, rotate, and revoke by id. - e2e refused-ship request gets a 30 s deadline; store_gate.go header documents the permit-free revoke; cli.md gets an operator section on held customer creates (pending copy review). - code-health record lowered for four functions now using *Context.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+373
−42
.amadan/code-health.tsv+0 −4docs/site/cli.md+37 −0internal/console/apiplatformcustomers.go+20 −4internal/console/apiplatformcustomers_test.go+67 −0internal/console/authstore.go+16 −2internal/console/platform_credentials_test.go+145 −0internal/console/platform_store.go+25 −1internal/console/store_gate.go+10 −2internal/console/svcprincipal.go+48 −28platform_e2e_test.go+5 −1
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index 4de3db1c0..3b77fbbb3 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -1532,7 +1532,6 @@ db-no-context internal/console (*Store).PeoplePage console.sqlHandle.QueryRow 2 |
| db-no-context internal/console (*Store).PersonWouldBeNew console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).PlansToPublish console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).PurchasesToday console.sqlHandle.QueryRow 1 |
| -db-no-context internal/console (*Store).PurgeCLIAuth console.sqlHandle.Exec 2 |
| db-no-context internal/console (*Store).PurgeDueApps console.sqlHandle.Query 1 |
| db-no-context internal/console (*Store).PurgeExpired console.sqlHandle.Exec 3 |
| db-no-context internal/console (*Store).PurgeMoveLogIncarnation console.sqlHandle.Exec 1 |
| @@ -1570,16 +1569,13 @@ db-no-context internal/console (*Store).RestoringAppsIn console.sqlHandle.Query |
| db-no-context internal/console (*Store).ResumeAlertConnector console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).RetryMoveLog console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).Revoke console.sqlHandle.Exec 1 |
| -db-no-context internal/console (*Store).RevokeAccountToken console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).RevokeInvite console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).RevokeLink (*sql.Tx).Exec 2 |
| db-no-context internal/console (*Store).RevokeLink (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).RevokeLink console.sqlHandle.Begin 1 |
| -db-no-context internal/console (*Store).RevokeServicePrincipal console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).RotateLinkToken (*sql.Tx).Exec 3 |
| db-no-context internal/console (*Store).RotateLinkToken (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).RotateLinkToken console.sqlHandle.Begin 1 |
| -db-no-context internal/console (*Store).RotateServicePrincipal console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).SaveBillingSync (*sql.Tx).Exec 2 |
| db-no-context internal/console (*Store).SaveBillingSync console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).SealedAlertTargets console.sqlHandle.Query 1 |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index dc952b56e..df0e02a33 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2640,6 +2640,43 @@ carlos accounts platform --account bcd --revoke --reason "contract ended" |
| Turning platform access off stops the platform’s credentials at once. Its customers’ sites keep serving. |
| +#### A customer create that stays pending |
| + |
| +When a platform creates a customer account, the console first records a promise for it. The promise holds the customer’s ref and a place in `--max-customers`. The console then writes the account to the deployment bucket and records it in its database. If the bucket and the database disagree about that account, the console stops and keeps the promise. This is a held promise. Nothing more is written for it until an operator repairs it. |
| + |
| +While a promise is held, the console logs this line on every request the platform makes: |
| + |
| +```text |
| +console: platform <platform>: pending customer create <mint id> held: account <id> <reason>; it stays pending, holding its ref, until an operator repairs the bucket or the console |
| +``` |
| + |
| +Only that platform is affected, and only its creates. Its customer list, updates and credentials keep working. A create for the held ref fails. When the reason is `is in this console with no manifest in the bucket`, every create on that platform fails, because the bucket offers each new create the same id. The promise counts towards `--max-customers` until it is repaired. |
| + |
| +First read the promise and the account in the console’s database: |
| + |
| +```text |
| +SELECT mint_id, platform, ref, name FROM platform_pending_mints WHERE mint_id = '<mint id>'; |
| +SELECT id, sqid, name, created_at, platform, platform_ref, platform_mint, deleted_at FROM accounts WHERE id = <id>; |
| +``` |
| + |
| +The account’s manifest is `accounts/<sqid>/account.json` in the deployment bucket. |
| + |
| +**The account has no manifest, or the create’s manifest sits at its id.** The reason is `is in this console with no manifest in the bucket` or `is another account in this console`. Check that the manifest is missing, or that its `platform_mint` is the mint id and the account row’s is not. Then give the account its manifest back. Write `accounts/<sqid>/account.json` from the row: `id`, `sqid`, `name`, and `created_at` as an RFC 3339 UTC time. Add `platform`, `platform_ref` and `platform_mint` when the row has them, and `deleted_at`, also as an RFC 3339 UTC time, when the row’s is not 0. This replaces the create’s manifest if one is there. The platform’s next request creates the customer at a new id. |
| + |
| +**Another live customer holds the ref.** The reason starts `holds ref` or `would take ref`. Check which account holds it: |
| + |
| +```text |
| +SELECT id, sqid, name, platform_mint FROM accounts WHERE platform = '<platform>' AND platform_ref = '<ref>' AND deleted_at = 0; |
| +``` |
| + |
| +If that is the customer the platform meant, the promise is a stray. Search the bucket’s account manifests for `"platform_mint":"<mint id>"`. If one carries it, add `deleted_at` with the current UTC time to it. Don’t delete it: an account id is never given out twice. Then remove the promise: |
| + |
| +```text |
| +DELETE FROM platform_pending_mints WHERE mint_id = '<mint id>'; |
| +``` |
| + |
| +After either repair the log line stops, and `carlos platform customers list --platform <platform>` shows the count you expect. |
| + |
| ### carlos accounts subdomain |
| Assigns a readable name to an account's app addresses, so `shop.bdq.oncarlos.com` also works as `shop.harbour.oncarlos.com`. Only platform operators can use it. |
diff --git a/internal/console/apiplatformcustomers.go b/internal/console/apiplatformcustomers.go| index 8bd76130c..7176042d0 100644 |
| --- a/internal/console/apiplatformcustomers.go |
| +++ b/internal/console/apiplatformcustomers.go |
| @@ -619,6 +619,10 @@ var errPlatformMintHeld = errors.New("console: the pending customer create is he |
| // promise. Create withdraws its own fresh promise on it. |
| var errMintNotWritten = errors.New("console: nothing was written for the pending customer create") |
| +// platformMintHeldOtherID is the held line's reason when the manifest |
| +// carrying a mint sits at an id whose row is another account's. |
| +const platformMintHeldOtherID = "is another account in this console, and the manifest carrying this create sits at its id" |
| + |
| // finishPendingMints finishes every pending mint of the platform, oldest |
| // first. The caller holds s.lockPlatformLifecycle(platform.Sqid). A mint |
| // that ended without an account (errPlatformMintEnded) is past, and a held |
| @@ -669,7 +673,9 @@ func (s *Server) finishPendingMints(ctx context.Context, platform *Account) erro |
| // before it writes and nothing is written; |
| // - the ref is held by a live customer that is not this mint's; |
| // - a manifest already carrying this mint id sits at an id whose row is |
| -// another account's (errLinkedIDTaken from CreateLinkedAccount). |
| +// another account's: asked before any effect (linkedIDHeldByAnother, |
| +// so analytics is not turned on for that account), and again in |
| +// CreateLinkedAccount's transaction (errLinkedIDTaken). |
| // |
| // A bucket that cannot be read, or a database or analytics failure, keeps |
| // the promise too, and the next platform request tries again. The one end |
| @@ -722,6 +728,18 @@ func (s *Server) finishPlatformMint(ctx context.Context, platform *Account, m Pe |
| log.Printf("console: platform %s: pending customer create %s (%q): mint: %v", platform.Sqid, m.MintID, m.Name, err) |
| return nil, err |
| } |
| + a := NewLinkedAccount{ID: id, Sqid: sqid, Name: m.Name, Platform: platform.Sqid, Ref: m.Ref, MintID: m.MintID, |
| + Plan: m.Plan, PlanReason: m.PlanReason, By: m.By} |
| + // A manifest found by its mint id was returned without free being |
| + // asked: before any effect (analytics, the row), the id must not be |
| + // another account's (final review, Astra I1). CreateLinkedAccount asks |
| + // again in its transaction. |
| + if taken, err := s.store.linkedIDHeldByAnother(ctx, a); err != nil { |
| + log.Printf("console: platform %s: pending customer create %s: account %d: %v", platform.Sqid, m.MintID, id, err) |
| + return nil, err |
| + } else if taken { |
| + return nil, held(id, true, platformMintHeldOtherID) |
| + } |
| if err := s.startNewAccountAnalytics(ctx, sqid); err != nil { |
| log.Printf("console: platform %s: minted customer %s (id %d, pending create %s) into the bucket but "+ |
| "could not turn analytics on: %v; the next platform request finishes it", platform.Sqid, sqid, id, m.MintID, err) |
| @@ -732,8 +750,6 @@ func (s *Server) finishPlatformMint(ctx context.Context, platform *Account, m Pe |
| "could not record it: %v; the next platform request finishes it", platform.Sqid, sqid, id, m.MintID, err) |
| return nil, err |
| } |
| - a := NewLinkedAccount{ID: id, Sqid: sqid, Name: m.Name, Platform: platform.Sqid, Ref: m.Ref, MintID: m.MintID, |
| - Plan: m.Plan, PlanReason: m.PlanReason, By: m.By} |
| err = s.store.CreateLinkedAccount(ctx, a, m.CreatedAt) |
| switch { |
| case err == nil: |
| @@ -742,7 +758,7 @@ func (s *Server) finishPlatformMint(ctx context.Context, platform *Account, m Pe |
| platform.Sqid, m.MintID, sqid) |
| return nil, fmt.Errorf("%w: %w", errPlatformMintEnded, err) |
| case errors.Is(err, errLinkedIDTaken): |
| - return nil, held(id, true, "is another account in this console, and the manifest carrying this create sits at its id") |
| + return nil, held(id, true, platformMintHeldOtherID) |
| case errors.Is(err, ErrPlatformRefTaken): |
| return nil, held(id, true, fmt.Sprintf("would take ref %q, which another live customer holds", m.Ref)) |
| default: |
diff --git a/internal/console/apiplatformcustomers_test.go b/internal/console/apiplatformcustomers_test.go| index fd1ff7e92..ce6bea5e4 100644 |
| --- a/internal/console/apiplatformcustomers_test.go |
| +++ b/internal/console/apiplatformcustomers_test.go |
| @@ -21,6 +21,7 @@ import ( |
| "github.com/carlosframework/platform/internal/plans" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/svcrole" |
| + "github.com/carlosframework/platform/internal/telemetry" |
| ) |
| // platformDoorPatterns is every platform door Tasks 8, 9 and 10 register. |
| @@ -1081,6 +1082,72 @@ func TestCustomerHeldIDKeepsAnAcceptedPromise(t *testing.T) { |
| } |
| } |
| +// TestCustomerRecoveryRefusesAnotherIdentityBeforeAnalytics (final review, |
| +// Astra I1): a pending mint finds its own manifest in the bucket, but this |
| +// console holds that id for another account. The recovery is refused before |
| +// any effect: the other account's telemetry.json is byte for byte what it |
| +// was, no row is written or linked, nothing is audited, and the promise is |
| +// kept, holding its slot and ref. |
| +func TestCustomerRecoveryRefusesAnotherIdentityBeforeAnalytics(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + acct := planAccount(t, fx, 501) |
| + grantPlatformAccount(t, fx, acct.Sqid, 5) |
| + tok := platformToken(t, fx, acct.ID, "cms") |
| + ctx := context.Background() |
| + mintID := strings.Repeat("ab", 16) |
| + if err := fx.st.ReservePlatformMint(ctx, PendingMint{MintID: mintID, Platform: acct.Sqid, Ref: "4812", Name: "shop", |
| + By: "service:" + acct.Sqid + "/cms", CreatedAt: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A first attempt wrote the manifest; the console then lost the row, |
| + // and another account took the id. |
| + id, sqid, _, err := domains.MintLinkedAccount(ctx, fx.rel, "shop", acct.Sqid, "4812", mintID, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.CreateAccount(id, sqid, "other", "other@example.com", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := telemetry.Update(ctx, fx.rel, telemetry.AccountKey(sqid), func(st *telemetry.Settings) { |
| + st.Analytics = &telemetry.Analytics{Count: telemetry.CountOff} |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + before, _, err := fx.rel.Get(ctx, telemetry.AccountKey(sqid)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + if status, _, raw := getPlatform(t, platformCustomersURL(fx.ts.URL, acct.Sqid), tok); status != http.StatusOK { |
| + t.Fatalf("list = %d %s, want the read door to go on past the held promise", status, raw) |
| + } |
| + _, err = fx.srv.finishPlatformMint(ctx, acct, pendingMints(t, fx.st, acct.Sqid)[0]) |
| + if !errors.Is(err, errPlatformMintHeld) || errors.Is(err, errMintNotWritten) { |
| + t.Fatalf("finish = %v, want held, with its manifest written", err) |
| + } |
| + |
| + after, _, err := fx.rel.Get(ctx, telemetry.AccountKey(sqid)) |
| + if err != nil || !bytes.Equal(after, before) { |
| + t.Fatalf("the other account's telemetry.json = %s %v, was %s: want it unchanged", after, err, before) |
| + } |
| + if p := pendingMints(t, fx.st, acct.Sqid); len(p) != 1 || p[0].MintID != mintID || p[0].Ref != "4812" { |
| + t.Fatalf("pending mints %+v, want the promise kept", p) |
| + } |
| + if n := linkedCount(t, fx.st, acct.Sqid); n != 1 { |
| + t.Fatalf("LinkedCustomerCount = %d, want 1: the held promise keeps its slot", n) |
| + } |
| + other, err := fx.st.AccountBySqid(sqid) |
| + if err != nil || other == nil || other.Name != "other" { |
| + t.Fatalf("the other account %+v %v, want it untouched", other, err) |
| + } |
| + if linked, _, err := fx.st.AccountPlatform(ctx, id); err != nil || linked != "" { |
| + t.Fatalf("the other account's link %q %v, want none", linked, err) |
| + } |
| + if rows := platformAudit(t, fx, acct.ID, auditPlatformCustomerCreate); len(rows) != 0 { |
| + t.Fatalf("audit %+v, want no create recorded", rows) |
| + } |
| +} |
| + |
| // TestCustomerHeldPromiseFailsOnlyItsOwnRef is fix round 2 (ruling C): a |
| // promise held because a live customer took its ref fails only a create for |
| // that ref. The gate goes on, a create for another ref succeeds, and the |
diff --git a/internal/console/authstore.go b/internal/console/authstore.go| index e70fd45f4..009bc67a8 100644 |
| --- a/internal/console/authstore.go |
| +++ b/internal/console/authstore.go |
| @@ -28,6 +28,7 @@ import ( |
| "encoding/hex" |
| "errors" |
| "fmt" |
| + "log" |
| "strings" |
| "sync/atomic" |
| "time" |
| @@ -513,14 +514,27 @@ func (s *Store) PurgeCLIAuth(now time.Time) { |
| if !lastCLIPurge.CompareAndSwap(last, now.Unix()) { |
| return // another request is doing it |
| } |
| - s.db.Exec(`DELETE FROM cli_auth_requests WHERE expires_at < ?`, now.Unix()) |
| + // No ctx: the login path and PurgeExpired call this as housekeeping. |
| + ctx := context.Background() |
| + if _, err := s.db.ExecContext(ctx, `DELETE FROM cli_auth_requests WHERE expires_at < ?`, now.Unix()); err != nil { |
| + log.Printf("console: purge expired login requests: %v", err) |
| + } |
| // expires_at = 0 means "never" (app tokens, see NewAppToken) and must be |
| // excluded from a sweep that compares against the clock — 0 is less than |
| // every now, so an unguarded sweep would delete exactly the credentials |
| // that are supposed to outlive it. A link credential is excluded by kind |
| // as well as by its 0: only rotate and unlink end one, because only they |
| // also end its channel. |
| - s.db.Exec(`DELETE FROM cli_tokens WHERE expires_at != 0 AND expires_at < ? AND kind != ?`, now.Unix(), cliKindLink) |
| + // |
| + // An app-bound per-customer credential (kind platform, an app) is left |
| + // out too. This DELETE holds no permit, and under the armed claim gate |
| + // one such row would abort the whole statement, so nothing expired |
| + // would be purged again. An expired one already resolves to nothing, |
| + // and app purge deletes it with its app. |
| + if _, err := s.db.ExecContext(ctx, `DELETE FROM cli_tokens WHERE expires_at != 0 AND expires_at < ? AND kind != ? |
| + AND NOT (kind = ? AND app != '')`, now.Unix(), cliKindLink, cliKindPlatform); err != nil { |
| + log.Printf("console: purge expired tokens: %v", err) |
| + } |
| } |
| // CLIAuthByUserCode resolves a typed code to the request it names, for the |
diff --git a/internal/console/platform_credentials_test.go b/internal/console/platform_credentials_test.go| index d2203a820..ef1c17a91 100644 |
| --- a/internal/console/platform_credentials_test.go |
| +++ b/internal/console/platform_credentials_test.go |
| @@ -1002,6 +1002,151 @@ func TestCustomerCredentialUnderTheGateIsSweptByARevoke(t *testing.T) { |
| } |
| } |
| +// TestExpiredTokenSweepUnderTheGateGoesOnPastACustomerCredential (final |
| +// review, Fable I1): the expired-token sweep holds no permit. Under the |
| +// armed claim gate an expired app-bound per-customer credential is left to |
| +// app purge, and the sweep still purges an ordinary expired token instead |
| +// of aborting on that row. |
| +func TestExpiredTokenSweepUnderTheGateGoesOnPastACustomerCredential(t *testing.T) { |
| + s, _, _ := sqlIngestFixture(t) |
| + ctx := context.Background() |
| + p := newPlatform(t, s, "bcd") |
| + grantPlatform(t, s, p) |
| + if _, err := s.db.ExecContext(ctx, `UPDATE accounts SET platform = 'bcd', platform_ref = 'census' WHERE id = ?`, gateAcct); err != nil { |
| + t.Fatal(err) |
| + } |
| + platformTok, err := s.NewServicePrincipal(p, "cms", "", svcrole.Platform, "owner-bcd@example.com", platformNow) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + minter, ok := s.CLIPrincipal(platformTok, time.Now()) |
| + if !ok { |
| + t.Fatal("platform credential does not resolve") |
| + } |
| + now := time.Now() |
| + deploy, _, err := s.NewPlatformCustomerCredential(ctx, PlatformCredentialRequest{CustomerID: gateAcct, PlatformAccountID: p, |
| + Generation: minter.PlatformGeneration, Minter: minter, Name: "cms", MintedBy: "service:bcd/cms", Role: svcrole.Deploy, |
| + App: "blog", Rungs: []string{"edge"}, TTL: PlatformCredentialMinTTL}, now) |
| + if err != nil { |
| + t.Fatalf("gated mint: %v", err) |
| + } |
| + user := mintUserToken(t, s, "paul@keymail.dev", now) |
| + later := now.Add(CLITokenTTL + time.Hour) |
| + |
| + lastCLIPurge.Store(0) |
| + defer lastCLIPurge.Store(0) |
| + s.PurgeCLIAuth(later) |
| + |
| + rows := func(raw string) int { |
| + var n int |
| + if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM cli_tokens WHERE token_hash = ?`, hashToken(raw)).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| + } |
| + if n := rows(user); n != 0 { |
| + t.Fatalf("expired ordinary token rows = %d after the sweep, want it purged", n) |
| + } |
| + if n := rows(deploy); n != 1 { |
| + t.Fatalf("expired app-bound customer credential rows = %d, want it left to app purge", n) |
| + } |
| + if pr, ok := s.CLIPrincipal(deploy, later); ok { |
| + t.Fatalf("expired customer credential resolved to %+v", pr) |
| + } |
| +} |
| + |
| +// TestRevokingAPlatformCredentialUnderTheGateEndsItsDeployMints: under the |
| +// armed claim gate, the revoke of a platform credential ends the app-bound |
| +// Deploy credential it minted with no permit (RevokeFree), and succeeds. |
| +func TestRevokingAPlatformCredentialUnderTheGateEndsItsDeployMints(t *testing.T) { |
| + s, _, _ := sqlIngestFixture(t) |
| + ctx := context.Background() |
| + p := newPlatform(t, s, "bcd") |
| + grantPlatform(t, s, p) |
| + if _, err := s.db.ExecContext(ctx, `UPDATE accounts SET platform = 'bcd', platform_ref = 'census' WHERE id = ?`, gateAcct); err != nil { |
| + t.Fatal(err) |
| + } |
| + platformTok, err := s.NewServicePrincipal(p, "cms", "", svcrole.Platform, "owner-bcd@example.com", platformNow) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + minter, ok := s.CLIPrincipal(platformTok, time.Now()) |
| + if !ok { |
| + t.Fatal("platform credential does not resolve") |
| + } |
| + now := time.Now() |
| + raw, _, err := s.NewPlatformCustomerCredential(ctx, PlatformCredentialRequest{CustomerID: gateAcct, PlatformAccountID: p, |
| + Generation: minter.PlatformGeneration, Minter: minter, Name: "cms", MintedBy: "service:bcd/cms", Role: svcrole.Deploy, |
| + App: "blog", Rungs: []string{"edge"}}, now) |
| + if err != nil { |
| + t.Fatalf("gated mint: %v", err) |
| + } |
| + revokeAt := now.Add(time.Minute) |
| + if err := s.RevokeServicePrincipal(p, "cms", revokeAt); err != nil { |
| + t.Fatalf("RevokeServicePrincipal under the gate = %v", err) |
| + } |
| + if at := tokenRevokedAt(t, s, hashToken(raw)); at != revokeAt.Unix() { |
| + t.Fatalf("minted deploy credential revoked_at = %d, want %d", at, revokeAt.Unix()) |
| + } |
| + if pr, ok := s.CLIPrincipal(raw, revokeAt); ok { |
| + t.Fatalf("minted deploy credential resolved to %+v", pr) |
| + } |
| +} |
| + |
| +// TestRevokingOrRotatingAPlatformCredentialEndsWhatItMinted (final review, |
| +// Fable I2): an owner who revokes or rotates a leaked platform credential |
| +// ends every per-customer credential it minted, from the next request. |
| +// What the owner minted in person, and what another platform credential |
| +// minted, go on working. |
| +func TestRevokingOrRotatingAPlatformCredentialEndsWhatItMinted(t *testing.T) { |
| + for _, door := range []string{"revoke", "rotate", "revoke by id"} { |
| + t.Run(door, func(t *testing.T) { |
| + fx, p, tok, cust := customerWorld(t, "free") |
| + owner := cliToken(t, fx, "owner"+p.Sqid+"@example.com", "code-platform-minted-"+strings.ReplaceAll(door, " ", "-")) |
| + if _, err := fx.st.CreateAppIn(cust.ID, "site", "service:"+p.Sqid+"/cms", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + publish := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish"})) |
| + deploy := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok, |
| + map[string]any{"role": "deploy", "app": "site", "rungs": []string{"edge"}})) |
| + byPerson := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, owner, map[string]any{"role": "publish"})) |
| + other := platformToken(t, fx, p.ID, "cms-2") |
| + byOther := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, other, map[string]any{"role": "publish"})) |
| + for _, raw := range []string{publish, byPerson, byOther} { |
| + if status := appsStatus(t, fx, raw); status != http.StatusOK { |
| + t.Fatalf("live customer credential = %d, want 200", status) |
| + } |
| + } |
| + if status := channelsStatus(t, fx, cust.Sqid, "site", deploy); status != http.StatusOK { |
| + t.Fatalf("live deploy credential = %d, want 200", status) |
| + } |
| + |
| + if door == "revoke by id" { |
| + // The account pane's one Revoke button (RevokeAccountToken). |
| + if err := fx.st.RevokeAccountToken(p.ID, hashToken(tok), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } else if status, body := postRaw(t, servicesURL(fx, p.Sqid)+"/cms/"+door, map[string]any{}, owner); status != http.StatusOK { |
| + t.Fatalf("%s cms = %d %s, want 200", door, status, body) |
| + } |
| + if status := appsStatus(t, fx, publish); status != http.StatusUnauthorized { |
| + t.Fatalf("after the %s, cms's publish credential = %d, want 401", door, status) |
| + } |
| + if status := channelsStatus(t, fx, cust.Sqid, "site", deploy); status != http.StatusUnauthorized { |
| + t.Fatalf("after the %s, cms's deploy credential = %d, want 401", door, status) |
| + } |
| + for what, raw := range map[string]string{"the owner's": byPerson, "cms-2's": byOther} { |
| + if status := appsStatus(t, fx, raw); status != http.StatusOK { |
| + t.Fatalf("after the %s of cms, %s credential = %d, want 200", door, what, status) |
| + } |
| + } |
| + if status := appsStatus(t, fx, other); status != http.StatusForbidden && status != http.StatusOK { |
| + t.Fatalf("after the %s of cms, cms-2 itself = %d, want it still resolving", door, status) |
| + } |
| + }) |
| + } |
| +} |
| + |
| // deployOnSite is customerWorld with an app site in shop and a Deploy |
| // per-customer credential on it, which reads site's channels. |
| func deployOnSite(t *testing.T) (*consoleFixture, *Account, string, *Account, string) { |
diff --git a/internal/console/platform_store.go b/internal/console/platform_store.go| index 07d1cb01b..60bfa39f7 100644 |
| --- a/internal/console/platform_store.go |
| +++ b/internal/console/platform_store.go |
| @@ -626,7 +626,7 @@ func (s *Store) CreateLinkedAccount(ctx context.Context, a NewLinkedAccount, now |
| } |
| case err != nil: |
| return err |
| - case sqid != a.Sqid || platform != a.Platform || mint == "" || mint != a.MintID: |
| + case !a.identifiedBy(sqid, platform, mint): |
| return errLinkedIDTaken |
| case deleted != 0: |
| // This customer was materialized and then deleted before the |
| @@ -659,6 +659,30 @@ func (s *Store) CreateLinkedAccount(ctx context.Context, a NewLinkedAccount, now |
| return tx.Commit() |
| } |
| +// identifiedBy reports whether a row carrying sqid, platform and mint is |
| +// this mint's account: the same sqid, platform AND mint id. It is the one |
| +// identity rule of CreateLinkedAccount and linkedIDHeldByAnother. |
| +func (a NewLinkedAccount) identifiedBy(sqid, platform, mint string) bool { |
| + return sqid == a.Sqid && platform == a.Platform && mint != "" && mint == a.MintID |
| +} |
| + |
| +// linkedIDHeldByAnother reports whether a row at a.ID, live or deleted, |
| +// carries another identity than a's (identifiedBy). A recovered mint asks it |
| +// before any effect (finishPlatformMint), so a refused finish writes |
| +// nothing; CreateLinkedAccount asks the same again in its transaction. |
| +func (s *Store) linkedIDHeldByAnother(ctx context.Context, a NewLinkedAccount) (bool, error) { |
| + var sqid, platform, mint string |
| + err := s.db.QueryRowContext(ctx, `SELECT sqid, platform, platform_mint FROM accounts WHERE id = ?`, a.ID). |
| + Scan(&sqid, &platform, &mint) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + return !a.identifiedBy(sqid, platform, mint), nil |
| +} |
| + |
| // 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 != "" { |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index 855d242d4..4d3d1eea5 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -25,6 +25,13 @@ package console |
| // refused by the permit table's CHECK and matches no trigger branch. Tables |
| // whose rows cannot be bound to one account (owners) refuse every write. |
| // |
| +// One UPDATE needs no permit at all: a table's RevokeFree revoke. On a row |
| +// whose RevokeScope column is not 0, the RevokeFree column may rise from 0 |
| +// to a positive value with every other column unchanged (cli_tokens: a |
| +// per-customer platform credential's revoked_at). A revoke only takes |
| +// authority away. It covers no DELETE: a permit-less DELETE of such a row |
| +// is refused like any other. |
| +// |
| // Permits are only ever written by Store.withClaimSQL, on a connection it |
| // holds exclusively, and only after the caller's check callback has accepted |
| // the scope. Only local checks run before each write and commit; remote |
| @@ -167,8 +174,9 @@ type claimSQLTable struct { |
| // the rows it covers are revoked by a sweep that holds no app |
| // incarnation to bind a permit to (cli_tokens: a platform grant's |
| // revoke, which must end every per-customer credential, app-bound ones |
| - // included, in the transaction that ends the grant's generation). |
| - // Lowering it, or changing anything else, still needs a permit. |
| + // included, in the transaction that ends the grant's generation; and a |
| + // platform credential's own revoke or rotate, which ends what it |
| + // minted). Lowering it, or changing anything else, still needs a permit. |
| RevokeFree string |
| RevokeScope string |
diff --git a/internal/console/svcprincipal.go b/internal/console/svcprincipal.go| index ec8448108..7730f6ec9 100644 |
| --- a/internal/console/svcprincipal.go |
| +++ b/internal/console/svcprincipal.go |
| @@ -567,19 +567,12 @@ func (s *Store) RotateServicePrincipal(accountID int64, name string, now time.Ti |
| if err != nil { |
| return "", err |
| } |
| - res, err := s.db.Exec(`UPDATE cli_tokens SET token_hash = ?, rotated_at = ?, last_used = 0 |
| -WHERE kind = ? AND account_id = ? AND name = ? AND name != '' AND revoked_at = 0`, |
| + err = s.retireServiceCredential(accountID, now, `UPDATE cli_tokens SET token_hash = ?, rotated_at = ?, last_used = 0 |
| +WHERE kind = ? AND account_id = ? AND name = ? AND name != '' AND revoked_at = 0 RETURNING kind, role, name`, |
| hashToken(raw), now.Unix(), cliKindService, accountID, name) |
| if err != nil { |
| return "", err |
| } |
| - n, err := res.RowsAffected() |
| - if err != nil { |
| - return "", err |
| - } |
| - if n == 0 { |
| - return "", ErrNoServicePrincipal |
| - } |
| return raw, nil |
| } |
| @@ -594,20 +587,57 @@ WHERE kind = ? AND account_id = ? AND name = ? AND name != '' AND revoked_at = 0 |
| // exactly that reason. The same name != "" guard applies here, for |
| // the same reason RotateServicePrincipal needs it. |
| func (s *Store) RevokeServicePrincipal(accountID int64, name string, now time.Time) error { |
| - res, err := s.db.Exec(`UPDATE cli_tokens SET revoked_at = ? |
| -WHERE kind = ? AND account_id = ? AND name = ? AND name != '' AND revoked_at = 0`, |
| + return s.retireServiceCredential(accountID, now, `UPDATE cli_tokens SET revoked_at = ? |
| +WHERE kind = ? AND account_id = ? AND name = ? AND name != '' AND revoked_at = 0 RETURNING kind, role, name`, |
| now.Unix(), cliKindService, accountID, name) |
| +} |
| + |
| +// retireServiceCredential runs a rotate's or a revoke's UPDATE of one |
| +// credential (update, ending RETURNING kind, role, name) and, in the same |
| +// transaction, when that credential is a platform credential, ends every |
| +// per-customer credential it minted (endPlatformMintsTx): a platform owner |
| +// rotating or revoking a leaked platform secret also ends what the secret |
| +// minted (final review, Fable I2). Nothing matched is ErrNoServicePrincipal. |
| +// The callers take no ctx (pre-flight C11). |
| +func (s *Store) retireServiceCredential(accountID int64, now time.Time, update string, args ...any) error { |
| + ctx := context.Background() |
| + tx, err := s.db.BeginTx(ctx, nil) |
| if err != nil { |
| return err |
| } |
| - n, err := res.RowsAffected() |
| + defer tx.Rollback() |
| + var kind, role, name string |
| + err = tx.QueryRowContext(ctx, update, args...).Scan(&kind, &role, &name) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return ErrNoServicePrincipal |
| + } |
| if err != nil { |
| return err |
| } |
| - if n == 0 { |
| - return ErrNoServicePrincipal |
| + if kind == cliKindService && role == string(svcrole.Platform) && name != "" { |
| + if err := endPlatformMintsTx(ctx, tx, accountID, name, now); err != nil { |
| + return err |
| + } |
| } |
| - return nil |
| + return tx.Commit() |
| +} |
| + |
| +// endPlatformMintsTx revokes, in tx, every live per-customer credential |
| +// (kind platform) that the platform credential named name on the platform |
| +// account accountID minted. Such a row records its platform |
| +// (platform_account_id), its minter's name, and its minter's actor as its |
| +// address: service:<platform sqid>/<name> (auditActor). The name is unique |
| +// among an account's live service credentials, so it is that credential, |
| +// and an earlier one of the same name ended its own at its revoke. A |
| +// person's mints carry the person's address and are not touched. Revoking |
| +// only raises revoked_at, which the claim gate allows without a permit on a |
| +// platform row (store_gate.go RevokeFree). |
| +func endPlatformMintsTx(ctx context.Context, tx *sql.Tx, accountID int64, name string, now time.Time) error { |
| + _, err := tx.ExecContext(ctx, `UPDATE cli_tokens SET revoked_at = ? |
| + WHERE kind = ? AND platform_account_id = ? AND name = ? AND revoked_at = 0 |
| + AND address = 'service:' || (SELECT sqid FROM accounts WHERE id = ?) || '/' || name`, |
| + now.Unix(), cliKindPlatform, accountID, name, accountID) |
| + return err |
| } |
| // RevokeAccountToken soft-revokes one credential by its listing id (the |
| @@ -639,19 +669,9 @@ func (s *Store) RevokeAccountToken(accountID int64, id string, now time.Time) er |
| } |
| // A link credential is bound to an account too, and is excluded: only |
| // rotate and unlink end one, because only they also end its channel. |
| - res, err := s.db.Exec(`UPDATE cli_tokens SET revoked_at = ? |
| -WHERE token_hash = ? AND account_id = ? AND revoked_at = 0 AND kind != ?`, now.Unix(), id, accountID, cliKindLink) |
| - if err != nil { |
| - return err |
| - } |
| - n, err := res.RowsAffected() |
| - if err != nil { |
| - return err |
| - } |
| - if n == 0 { |
| - return ErrNoServicePrincipal |
| - } |
| - return nil |
| + return s.retireServiceCredential(accountID, now, `UPDATE cli_tokens SET revoked_at = ? |
| +WHERE token_hash = ? AND account_id = ? AND revoked_at = 0 AND kind != ? RETURNING kind, role, name`, |
| + now.Unix(), id, accountID, cliKindLink) |
| } |
| // ---- rate limits keyed on the principal (Task 5, issue #220 consequence 1) |
diff --git a/platform_e2e_test.go b/platform_e2e_test.go| index e845ac49a..a5ff5923f 100644 |
| --- a/platform_e2e_test.go |
| +++ b/platform_e2e_test.go |
| @@ -380,7 +380,11 @@ func platformE2EShipRefused(t *testing.T, sess *apiSession, account, siteDir, ve |
| t.Fatal(err) |
| } |
| path := apiPath(apiAcct{Seg: account}, "site", "/releases") |
| - status, body, err := sess.c.doMultipart(context.Background(), path, func(mw *multipart.Writer) error { |
| + // doMultipart's client has no timeout of its own: bound the request, so |
| + // a stalled refusal fails here rather than at the test binary's timeout. |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + defer cancel() |
| + status, body, err := sess.c.doMultipart(ctx, path, func(mw *multipart.Writer) error { |
| meta, err := json.Marshal(map[string]string{"version": version, "kind": "static"}) |
| if err != nil { |
| return err |