accounts platform: audit the grant's own values; return CLI errors
The grant door records its audit row from the request's own values as soon as the write commits, before the read-back for the reply, so a failed read or an overlapping grant cannot lose or alter it. Tests pin both. carlos accounts platform returns its errors to the accounts branch's OnError, which shares the branch's one exit with the usage fallback, so no fatal site is added. --reason without --grant or --revoke is refused (new copy row ReasonAlone, pending copy review).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+151
−25
accounts.go+10 −3accounts_platform.go+17 −13accounts_platform_test.go+18 −0docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md+2 −1internal/console/apiplatformgrant.go+14 −7internal/console/apiplatformgrant_test.go+77 −0internal/console/platform_store.go+10 −1platform_copy.go+3 −0
diff --git a/accounts.go b/accounts.go| index fba761871..1cd44306d 100644 |
| --- a/accounts.go |
| +++ b/accounts.go |
| @@ -85,9 +85,12 @@ no-op, first. |
| // accountsCommand is `carlos accounts`: its sub-verbs, and accountsUsage |
| // (stderr, exit 1) bare or for any other word. plan maps its own errors |
| -// (runAccountsPlan), so the branch has no OnError. |
| +// (runAccountsPlan). platform returns its errors, and OnError prints one |
| +// as "accounts platform: <error>" (stderr, exit 1). The usage and the |
| +// error end at the branch's one exit. |
| func accountsCommand() *clireg.Node { |
| const cust, op = clireg.Customer, clireg.Operator |
| + exit := func() { os.Exit(1) } |
| return &clireg.Node{ |
| Name: "accounts", |
| Audience: cust, |
| @@ -96,12 +99,16 @@ func accountsCommand() *clireg.Node { |
| raw("list", cust, runAccountsList), |
| raw("migrate", op, runAccountsMigrate), |
| raw("plan", op, runAccountsPlan), |
| - raw("platform", op, runAccountsPlatform), |
| + {Name: "platform", Audience: op, Run: clireg.RawArgsErr(runAccountsPlatform)}, |
| accountsSubdomainCommand(), |
| }, |
| Fallback: func(args, consumed []string) { |
| fmt.Fprint(os.Stderr, accountsUsage) |
| - os.Exit(1) |
| + exit() |
| + }, |
| + OnError: func(path []string, err error) { |
| + log.Printf("%s: %v", strings.Join(path, " "), err) |
| + exit() |
| }, |
| } |
| } |
diff --git a/accounts_platform.go b/accounts_platform.go| index e15ed2646..5a0f42f32 100644 |
| --- a/accounts_platform.go |
| +++ b/accounts_platform.go |
| @@ -11,7 +11,6 @@ import ( |
| "flag" |
| "fmt" |
| "io" |
| - "log" |
| "net/http" |
| "net/url" |
| "strings" |
| @@ -52,13 +51,14 @@ type putPlatformGrantRequest struct { |
| Reason string `json:"reason"` |
| } |
| -func runAccountsPlatform(args []string) { |
| - if err := runAccountsPlatformWithSession(context.Background(), nil, args, stdout); err != nil { |
| - if errors.Is(err, flag.ErrHelp) { |
| - return |
| - } |
| - log.Fatalf("accounts platform: %v", err) |
| - } |
| +// runAccountsPlatform is the leaf: -h's ErrHelp is not an error (usage on |
| +// stdout, exit 0); any other error goes to accountsCommand's OnError. |
| +func runAccountsPlatform(args []string) error { |
| + err := runAccountsPlatformWithSession(context.Background(), nil, args, stdout) |
| + if errors.Is(err, flag.ErrHelp) { |
| + return nil |
| + } |
| + return err |
| } |
| func runAccountsPlatformWithSession(ctx context.Context, sess *apiSession, args []string, out io.Writer) error { |
| @@ -97,9 +97,13 @@ func runAccountsPlatformWithSession(ctx context.Context, sess *apiSession, args |
| return errors.New(cliPlatformCopyGrantFlagsAlone) |
| case (*grant || *revoke) && strings.TrimSpace(*reason) == "": |
| return errors.New(cliPlatformCopyReasonRequired) |
| + case *reason != "" && !*grant && !*revoke: |
| + return errors.New(cliPlatformCopyReasonAlone) |
| } |
| if sess == nil { |
| - sess = requirePlatformAPISession(*consoleFlag, "accounts platform") |
| + if sess, err = requirePlatformAPISession(*consoleFlag, "accounts platform"); err != nil { |
| + return err |
| + } |
| printUsing(out, sess) |
| } |
| switch { |
| @@ -218,13 +222,13 @@ func decodePlatformReply(status int, body []byte, err error, out any) error { |
| // requirePlatformAPISession is the console session the platform doors |
| // need. Grants and links live in the console's database, so direct bucket |
| // mode has no equivalent. command names the verb in the refusal. |
| -func requirePlatformAPISession(consoleFlag, command string) *apiSession { |
| +func requirePlatformAPISession(consoleFlag, command string) (*apiSession, error) { |
| sess, err := resolveMode(consoleFlag) |
| if err != nil { |
| - log.Fatal(err) |
| + return nil, err |
| } |
| if sess == nil { |
| - log.Fatalf(cliPlatformCopyNeedsConsole, command) |
| + return nil, fmt.Errorf(cliPlatformCopyNeedsConsole, command) |
| } |
| - return sess |
| + return sess, nil |
| } |
diff --git a/accounts_platform_test.go b/accounts_platform_test.go| index f2ad22277..da9c26c41 100644 |
| --- a/accounts_platform_test.go |
| +++ b/accounts_platform_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "flag" |
| + "fmt" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| @@ -169,6 +170,7 @@ func TestAccountsPlatformFlagRefusals(t *testing.T) { |
| {[]string{"--account", "bcd", "--revoke", "--default-plan", "free", "--reason", "r"}, cliPlatformCopyGrantFlagsAlone}, |
| {[]string{"--account", "bcd", "--grant", "--max-customers", "50"}, cliPlatformCopyReasonRequired}, |
| {[]string{"--account", "bcd", "--revoke", "--reason", " "}, cliPlatformCopyReasonRequired}, |
| + {[]string{"--account", "bcd", "--reason", "r"}, cliPlatformCopyReasonAlone}, |
| {[]string{"--grant", "--max-customers", "50", "--reason", "r"}, ""}, |
| {[]string{"--account", "bcd", "extra"}, ""}, |
| } { |
| @@ -185,3 +187,19 @@ func TestAccountsPlatformFlagRefusals(t *testing.T) { |
| t.Fatalf("%d requests reached the console", hits) |
| } |
| } |
| + |
| +// TestAccountsPlatformNeedsConsoleIsAnError: in direct bucket mode the |
| +// session refusal comes back as an error for the branch's OnError, never as |
| +// an exit from inside the command. |
| +func TestAccountsPlatformNeedsConsoleIsAnError(t *testing.T) { |
| + t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir()) |
| + t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "") |
| + t.Setenv("CARLOS_SERVICE_TOKEN", "") |
| + err := runAccountsPlatformWithSession(context.Background(), nil, []string{"--account", "bcd"}, io.Discard) |
| + if want := fmt.Sprintf(cliPlatformCopyNeedsConsole, "accounts platform"); err == nil || err.Error() != want { |
| + t.Fatalf("err = %v, want %q", err, want) |
| + } |
| + if err := runAccountsPlatform([]string{"-h"}); err != nil { |
| + t.Fatalf("-h = %v, want nil (usage is not an error)", err) |
| + } |
| +} |
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 8b9c33e72..edef9d570 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 |
| @@ -1303,6 +1303,7 @@ Every row is pending copy review (Task 15). `%s`/`%d` are filled as named. CLI e |
| | GrantAndRevoke | --grant and --revoke can’t be used together | |
| | GrantFlagsAlone | --max-customers, --plans and --default-plan go with --grant | |
| | ReasonRequired | --reason is required | |
| +| ReasonAlone | --reason goes with --grant or --revoke | |
| | Usage | show or change an account’s platform grant (deployment operators) | |
| | OneHandle | pass --customer or --ref, not both | |
| | NoHandle | pass --customer or --ref | |
| @@ -1356,7 +1357,7 @@ A grant with no plans (no plan catalog) prints no `LabelPlans` or `LabelDefault` |
| Task 1's UX pass (2026-11-19) changed the text of `ValueByOn`, `LabelPlans`, `LabelDefault`, `Revoked`, `ListHeading`, `ColOwned`, `LabelOwned`, `UsageNear`, `UsageOver`, `UsageOverLimit`, `Minted`, `CreatedNoPlan` and `audit.grant_no_plans`, and added these rows: `LabelReason`, `ListOver`, `ListNear`, `ShowOK`, `ShowNear`, `ShowOver`, `LabelValidUntil`. The ids `ColOwned` and `LabelOwned` are kept although the words are now “claimed”. `ShowHeading` is used only for a customer with no plan. `ListOver` and `ListNear` are appended to `ListHeading` in that order, each only when its count is non-zero. |
| -Task 6 added `ReasonRequired` (the CLI's refusal of `--grant` or `--revoke` without `--reason`, before anything is sent; the text of the console's `grant.reason`) and `Usage` (the `platform` line in `carlos accounts`' usage). |
| +Task 6 added `ReasonRequired` (the CLI's refusal of `--grant` or `--revoke` without `--reason`, before anything is sent; the text of the console's `grant.reason`), `ReasonAlone` (its refusal of `--reason` with neither, pending copy review; Task 6 fix round 1) and `Usage` (the `platform` line in `carlos accounts`' usage). |
| Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and instances, object storage, emails a day, bandwidth a month, awake hours a month); `CapPDF` is the one new label. |
diff --git a/internal/console/apiplatformgrant.go b/internal/console/apiplatformgrant.go| index 70465dc40..0a25e3f12 100644 |
| --- a/internal/console/apiplatformgrant.go |
| +++ b/internal/console/apiplatformgrant.go |
| @@ -153,7 +153,7 @@ func (s *Server) handleAPIPlatformGrantPut(w http.ResponseWriter, r *http.Reques |
| jsonError(w, http.StatusBadRequest, platformCopy[id]) |
| return |
| } |
| - g := PlatformGrant{AccountID: acct.ID, MaxCustomers: req.MaxCustomers, Plans: req.Plans, |
| + g := PlatformGrant{AccountID: acct.ID, MaxCustomers: req.MaxCustomers, Plans: grantPlans(req.Plans), |
| DefaultPlan: req.DefaultPlan, Reason: reason, GrantedBy: addr} |
| if err := s.store.PutPlatformGrant(r.Context(), g, time.Now()); err != nil { |
| if errors.Is(err, ErrAccountGone) { |
| @@ -164,21 +164,28 @@ func (s *Server) handleAPIPlatformGrantPut(w http.ResponseWriter, r *http.Reques |
| jsonError(w, http.StatusInternalServerError, platformCopy["grant.failed"]) |
| return |
| } |
| + // The audit row is this write's own values, recorded as soon as the |
| + // write has committed: a read-back that fails, or a second operator's |
| + // grant landing in between, cannot lose it or change what it says. |
| + s.audit(acct, accountAuditSubject, addr, auditPlatformGrant, grantAuditDetail(g)) |
| reply, found, err := s.platformGrantReplyFor(r, acct) |
| if err != nil || !found { |
| log.Printf("console: api platform grant %s: read back: found %v, %v", acct.Sqid, found, err) |
| jsonError(w, http.StatusInternalServerError, platformCopy["grant.failed"]) |
| return |
| } |
| - detail := fmt.Sprintf(platformCopy["audit.grant_no_plans"], reply.MaxCustomers, reason) |
| - if len(reply.Plans) > 0 { |
| - detail = fmt.Sprintf(platformCopy["audit.grant"], reply.MaxCustomers, strings.Join(reply.Plans, ", "), |
| - reply.DefaultPlan, reason) |
| - } |
| - s.audit(acct, accountAuditSubject, addr, auditPlatformGrant, detail) |
| writeJSON(w, http.StatusOK, reply) |
| } |
| +// grantAuditDetail is the audit text for the grant g writes: |
| +// audit.grant_no_plans for a grant with no plans (pre-flight C17). |
| +func grantAuditDetail(g PlatformGrant) string { |
| + if len(g.Plans) == 0 { |
| + return fmt.Sprintf(platformCopy["audit.grant_no_plans"], g.MaxCustomers, g.Reason) |
| + } |
| + return fmt.Sprintf(platformCopy["audit.grant"], g.MaxCustomers, strings.Join(g.Plans, ", "), g.DefaultPlan, g.Reason) |
| +} |
| + |
| // grantPlansProblem is the copy id that refuses req's plans, or "". With a |
| // catalog a grant names at least one of its plans and a default among them; |
| // without one it names none (decision D8, pre-flight C17). |
diff --git a/internal/console/apiplatformgrant_test.go b/internal/console/apiplatformgrant_test.go| index 2188302eb..1944268f1 100644 |
| --- a/internal/console/apiplatformgrant_test.go |
| +++ b/internal/console/apiplatformgrant_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "fmt" |
| "net/http" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| @@ -345,3 +346,79 @@ func TestPlatformGrantDoorsAreClosedToEveryRole(t *testing.T) { |
| t.Fatalf("grant after refused credentials %+v, want it untouched", g) |
| } |
| } |
| + |
| +// TestPlatformGrantAuditSurvivesAFailedReadBack: the grant commits, then the |
| +// read-back for the reply fails. The answer is 500 grant.failed, and the |
| +// audit row is already there with this request's own values. |
| +func TestPlatformGrantAuditSurvivesAFailedReadBack(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct := planAccount(t, fx, 501) |
| + op := planOperatorToken(t, fx, "ops@keymail.dev", "code-platform-readback") |
| + // The reply's customer count reads the pending mints; without the table |
| + // that read fails after the grant has been written. |
| + if _, err := fx.st.db.ExecContext(context.Background(), `DROP TABLE platform_pending_mints`); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, out := platformPut(t, fx, acct.Sqid, map[string]any{"max_customers": 7, |
| + "plans": []string{"personal", "free"}, "default_plan": "free", "reason": "agreed by email"}, op) |
| + wantPlatformError(t, "PUT with a failing read-back", status, out, http.StatusInternalServerError, "grant.failed") |
| + if g, err := fx.st.PlatformGrant(context.Background(), acct.ID); err != nil || g == nil || g.MaxCustomers != 7 { |
| + t.Fatalf("grant %+v %v, want the write committed", g, err) |
| + } |
| + rows := platformAudit(t, fx, acct.ID, auditPlatformGrant) |
| + want := fmt.Sprintf(platformCopy["audit.grant"], 7, "free, personal", "free", "agreed by email") |
| + if len(rows) != 1 || rows[0].Detail != want || rows[0].Address != "ops@keymail.dev" { |
| + t.Fatalf("audit %+v, want one row %q by ops@keymail.dev", rows, want) |
| + } |
| +} |
| + |
| +// TestPlatformGrantOverlappingUpdatesAuditTheirOwnValues: operators grant |
| +// the same account at once, each with its own limit and reason. Every audit |
| +// row pairs its actor with that actor's own request, whichever write the |
| +// account ends on. |
| +func TestPlatformGrantOverlappingUpdatesAuditTheirOwnValues(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + acct := planAccount(t, fx, 501) |
| + const operators, each = 4, 6 |
| + tokens := make([]string, operators) |
| + for i := range tokens { |
| + tokens[i] = planOperatorToken(t, fx, fmt.Sprintf("ops%d@keymail.dev", i), fmt.Sprintf("code-platform-overlap-%d", i)) |
| + } |
| + want := map[string]string{} // detail -> actor |
| + type put struct { |
| + token, actor string |
| + max int |
| + reason string |
| + } |
| + var puts []put |
| + for i := 0; i < operators; i++ { |
| + for j := 0; j < each; j++ { |
| + p := put{tokens[i], fmt.Sprintf("ops%d@keymail.dev", i), 1 + i*each + j, fmt.Sprintf("round %d of ops%d", j, i)} |
| + puts = append(puts, p) |
| + want[fmt.Sprintf(platformCopy["audit.grant_no_plans"], p.max, p.reason)] = p.actor |
| + } |
| + } |
| + var wg sync.WaitGroup |
| + for _, p := range puts { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + status, raw := putRaw(t, platformGrantURL(fx, acct.Sqid), map[string]any{"max_customers": p.max, "reason": p.reason}, p.token) |
| + if status != http.StatusOK { |
| + t.Errorf("PUT %d by %s = %d %s", p.max, p.actor, status, raw) |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + rows := platformAudit(t, fx, acct.ID, auditPlatformGrant) |
| + if len(rows) != len(puts) { |
| + t.Fatalf("%d audit rows, want %d", len(rows), len(puts)) |
| + } |
| + for _, r := range rows { |
| + if actor, ok := want[r.Detail]; !ok || actor != r.Address { |
| + t.Errorf("audit row %q by %s: no request by that actor had those values", r.Detail, r.Address) |
| + } |
| + delete(want, r.Detail) |
| + } |
| +} |
diff --git a/internal/console/platform_store.go b/internal/console/platform_store.go| index e4f692500..2c8c0fa6e 100644 |
| --- a/internal/console/platform_store.go |
| +++ b/internal/console/platform_store.go |
| @@ -210,7 +210,7 @@ func (s *Store) PlatformGrant(ctx context.Context, accountID int64) (*PlatformGr |
| // deduped. A deleted or unknown account is ErrAccountGone. Who may hold a |
| // grant (never ops, never a customer account) is the caller's check. |
| func (s *Store) PutPlatformGrant(ctx context.Context, g PlatformGrant, now time.Time) error { |
| - plans := slices.Compact(slices.Sorted(slices.Values(g.Plans))) |
| + plans := grantPlans(g.Plans) |
| if plans == nil { |
| plans = []string{} |
| } |
| @@ -239,6 +239,15 @@ func (s *Store) PutPlatformGrant(ctx context.Context, g PlatformGrant, now time. |
| return nil |
| } |
| +// grantPlans is a grant's plans as PutPlatformGrant stores them: sorted and |
| +// deduped, nil for none. The grant door's audit row reads the same form. |
| +func grantPlans(plans []string) []string { |
| + if len(plans) == 0 { |
| + return nil |
| + } |
| + return slices.Compact(slices.Sorted(slices.Values(plans))) |
| +} |
| + |
| // RevokePlatformGrant ends the account's grant and its generation, in one |
| // transaction: the grant is revoked, its generation moves on, and every |
| // credential of the platform (its platform-role service credentials and |
diff --git a/platform_copy.go b/platform_copy.go| index 015cba1ad..664c270a3 100644 |
| --- a/platform_copy.go |
| +++ b/platform_copy.go |
| @@ -30,6 +30,9 @@ const ( |
| // ReasonRequired is the console's grant.reason, said before anything is |
| // sent (a row this task adds). |
| cliPlatformCopyReasonRequired = "--reason is required" |
| + // ReasonAlone refuses --reason with neither --grant nor --revoke (a |
| + // row this task adds). |
| + cliPlatformCopyReasonAlone = "--reason goes with --grant or --revoke" |
| cliPlatformCopyIsPlatform = "%s is a platform account" |
| cliPlatformCopyNotPlatform = "%s isn’t a platform account" |