console: the ops account is exempt from plans (no caps, limits or billing; not counted as a free account); settlement clears the limits record and cap rows
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from ops-plan-exempt into main.
50 files changed,
+1,339
−114
docs/site/plans.md+4 −0docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r1.md+18 −0docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r2.md+27 −0docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r3.md+28 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt-R2.md+41 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt-R3.md+41 −0docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt.md+35 −0internal/console/accountplans.go+4 −3internal/console/apiaccountplan.go+6 −1internal/console/apiaccountplan_copy.go+3 −0internal/console/apibilling.go+4 −1internal/console/apibillinghouse.go+6 −2internal/console/apiinstances_ratelimit_test.go+2 −0internal/console/apiplacements_put_test.go+1 −0internal/console/appsettings_ratelimit_test.go+2 −0internal/console/billingchange.go+12 −12internal/console/billingcheckout.go+22 −19internal/console/billinghold.go+44 −5internal/console/billinglate.go+6 −3internal/console/billinglate_test.go+8 −1internal/console/billingops.go+6 −6internal/console/billingops_test.go+7 −1internal/console/billingpage.go+14 −3internal/console/billingpage_copy.go+1 −0internal/console/billingpass.go+27 −6internal/console/billingportal.go+1 −5internal/console/billingretire.go+13 −5internal/console/billingseats.go+17 −10internal/console/billingstore.go+9 −3internal/console/billingsync.go+5 −1internal/console/claim_invariant_world_test.go+3 −0internal/console/ownership.go+4 −1internal/console/perfwrites_test.go+1 −0internal/console/plancaps.go+2 −1internal/console/plancaps_doors_test.go+28 −2internal/console/planexempt.go+105 −0internal/console/planexempt_test.go+714 −0internal/console/plangrace_cli_test.go+1 −0internal/console/plangrace_view_test.go+5 −0internal/console/plangracepass.go+3 −3internal/console/planlapse.go+7 −4internal/console/planlapse_keep.go+3 −3internal/console/planlapse_test.go+2 −0internal/console/planlimits.go+10 −3internal/console/planmail_test.go+1 −0internal/console/planmembers.go+6 −5internal/console/planmembers_test.go+5 −0internal/console/planstorage_test.go+1 −0internal/console/server.go+17 −4internal/console/store.go+7 −1
CI passed — run details
diff --git a/docs/site/plans.md b/docs/site/plans.md| index 8654bd99b..c91feb5d8 100644 |
| --- a/docs/site/plans.md |
| +++ b/docs/site/plans.md |
| @@ -44,6 +44,10 @@ carlos accounts plan --account bac --set personal --reason "upgraded" |
| The console writes each account's limits to `accounts/<sqid>/limits.json` in the deployment bucket, and the boxes read them from there. A change reaches the bucket straight away, or within a minute if the bucket was unavailable. |
| +## The ops account |
| + |
| +The deployment's built-in ops account (`bab`) is exempt from plans. It has no limits, caps or billing, and owning it doesn't count toward anyone's free account. `carlos accounts plan --account bab` says so and changes nothing. If it was under a plan before, the console removes the limits and warnings that plan left. |
| + |
| ## Sponsored accounts |
| A sponsored account keeps its plan but gets limits of its own where those are more generous, for example the usage it already had when plans were turned on: |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r1.md| new file mode 100644 |
| index 000000000..3801fe418 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r1.md |
| @@ -0,0 +1,18 @@ |
| +# Astra findings: ops-plan-exempt, round 1 of 3 |
| + |
| +gpt-6-astra via codex, high, brief CODEX-REVIEW-BRIEF-ops-plan-exempt.md at e492e431. Unedited. |
| + |
| +Reviewed `e492e431b21ad75be8a75c4ead8a32885d4c6531`, round 1. |
| + |
| +1. **P1 — Existing plan mail pauses can persist indefinitely.** |
| + `EffectiveLimits` now returns nil for ops ([planlimits.go:138](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planlimits.go:138)), causing the grace pass to return before its automatic mail-resume step ([plangracepass.go:83](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/plangracepass.go:83), [line 180](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/plangracepass.go:180)). Startup settlement clears limits and storage denies, but no mail pauses. If ops was plan-paused before deployment, its inactive credentials generate no new send events to resume it; without manual intervention, mail remains stopped after midnight. **Fix:** clear existing `PauseKindPlan` pauses during exemption settlement, using a conditional mutation that preserves manual and rate pauses. Add a regression covering an already-paused sender. **Invariant:** ops has no plan-enforced email stage. |
| + |
| +2. **P1 — Checkout recovery and continuation bypass the exemption.** |
| + `confirmBillingLocked` reaches checkout recovery without consulting `planExempt` ([billingops.go:701](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/billingops.go:701)). Recovery can resend a previously prepared checkout creation ([billingcheckout.go:999](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/billingcheckout.go:999), [line 707](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/billingcheckout.go:707)). Separately, Continue still returns an existing checkout’s payment URL ([line 1071](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/billingcheckout.go:1071)). An owner using an old page or direct endpoint after deployment can therefore create or continue payment for ops despite the new billing page hiding those actions. **Fix:** enforce the exemption before recovery and continuation read or act on billing state; include these paths in the guard and regression tests. **Invariant:** no billing action or purchase path reaches ops. |
| + |
| +3. **P2 — Startup cleanup misses storage denies on trashed apps.** |
| + Settlement calls `clearStorageDeny` and then marks itself complete ([planexempt.go:65](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planexempt.go:65)). That cleanup enumerates `AppsIn`, which explicitly excludes trashed apps ([planstorage.go:48](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planstorage.go:48), [store.go:1838](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/store.go:1838)). Restore clears the trash marker and database state without clearing the storage deny. Thus, restoring an ops app that was denied before being trashed leaves uploads refused; subsequent grace passes skip ops. **Fix:** include trashed apps in exemption cleanup, or clear their plan denies during restoration. Test deny → trash → exemption settlement → restore. **Invariant:** ops’s stores retain no plan storage deny. |
| + |
| +No P3 findings. No root-binary package changed, so no root-read census card is required. Changed Go files pass formatting checks, and `git diff --check` passes. Targeted tests could not start because the read-only sandbox prevented Go from creating its work directory; census test passes were not independently reproduced. No files were edited. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r2.md b/docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r2.md| new file mode 100644 |
| index 000000000..aba1b2328 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r2.md |
| @@ -0,0 +1,27 @@ |
| +# Astra findings: ops-plan-exempt, round 2 of 3 |
| + |
| +gpt-6-astra via codex, high, brief CODEX-REVIEW-BRIEF-ops-plan-exempt-R2.md at 4b28c0b3. Unedited. |
| + |
| +Round-one finding 1 — **Partly resolved:** normal mail cleanup works, but a failed sender read can leave a plan pause permanently skipped. |
| +Round-one finding 2 — **Resolved:** checkout recovery, Continue and the return endpoint now refuse ops. |
| +Round-one finding 3 — **Resolved:** storage cleanup includes trashed apps. |
| + |
| +Reviewed `4b28c0b3182885742c93c21d7bafacb50eb8b7c6`, round 2. |
| + |
| +1. **P1 — Mail cleanup can falsely declare settlement complete.** |
| + [planexempt.go:152](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planexempt.go:152) uses `mail.ListSenders`, which silently skips failed reads of non-app senders ([mail.go:312](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/mail/mail.go:312)). If a plan-paused instance sender’s GET fails during startup, cleanup returns success and sets `planExemptSettled` ([planexempt.go:86](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planexempt.go:86)). Later limits passes skip cleanup, while the grace pass exits for ops before resuming mail. The sender remains paused until another restart or manual intervention. |
| + **Fix:** require complete sender enumeration before marking settlement complete; propagate individual read/decode failures. Add a regression that fails one instance-sender read, then verifies the next pass resumes it. **Invariant:** ops retains no plan-enforced email pause. |
| + |
| +2. **P2 — Webhook error paths bypass the billing exemption.** |
| + When a subscription lookup returns not-found, [billingsync.go:179](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/billingsync.go:179) calls `subscriptionMissing` outside the billing hold. That function reads an existing ops billing row and opens `subscription_missing` without checking exemption ([billingsync.go:389](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/billingsync.go:389)). A webhook concerning an old ops subscription can therefore create a problem that operators cannot close: the close path now refuses ops ([apibilling.go:174](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/apibilling.go:174)). The unknown-customer branch likewise opens problems before acquiring a hold. |
| + **Fix:** apply `planExempt` at the shared problem-opening boundary and test these webhook paths. **Invariant:** billing does not act on ops’s state. |
| + |
| +3. **P2 — The house-flag API still accepts ops.** |
| + [apibillinghouse.go:48](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/apibillinghouse.go:48) calls `SetBillingHouse` without either exemption guard. An operator can submit ops to `/api/cli/billing/house`, receive success and create or delete its billing-house row. The new route guard covers only `/a/{sqid}/billing/` endpoints. |
| + **Fix:** refuse exempt accounts before this mutation and cover the operator endpoint in the exemption tests. **Invariant:** every billing action excludes ops. |
| + |
| +No P3 findings. No root-binary package changed, confirmed through dependency listings for Linux amd64 and arm64; no root-read census card is required. Missing limits records clear cached limits, throttle and disabled hosts. Changed Go files are formatted. Targeted tests could not start because the sandbox denied Go’s work-directory creation; census passes were not independently reproduced. `git diff --check` reports only Markdown trailing spaces in the archived round-one findings. No files were edited. |
| + |
| +The mail invariant has findings in rounds 1 and 2, triggering stopping rule 2 before another fix. Of its prescribed choices, I recommend enforcing settlement completeness in one place with a fault-injection guard test. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r3.md b/docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r3.md| new file mode 100644 |
| index 000000000..b4624c206 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r3.md |
| @@ -0,0 +1,28 @@ |
| +# Astra findings: ops-plan-exempt, round 3 of 3 |
| + |
| +gpt-6-astra via codex, high, at c7d07387. Unedited. |
| + |
| +R1 finding 1 — **Cut:** mail cleanup removed under Paul’s decision in discussion 455. |
| +R1 finding 2 — **Resolved:** recovery, Continue and the return endpoint refuse ops. |
| +R1 finding 3 — **Resolved:** storage cleanup includes trashed apps. |
| +R2 finding 1 — **Cut:** the mail-cleanup completeness issue is outside the accepted scope. |
| +R2 finding 2 — **Resolved:** the shared problem-opening function refuses ops. |
| +R2 finding 3 — **Resolved:** the house-flag endpoint refuses ops. |
| + |
| +Reviewed `origin/main...c7d07387ad71d2e5d66ad0a772ee258a46730817`, round 3 of 3. |
| + |
| +1. **P1 — Storage cleanup can mark settlement complete while uploads remain denied.** |
| + |
| + **Evidence:** [planexempt.go:110](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planexempt.go:110) relies on `convergeStoresOf` returning an error for incomplete cleanup. However, `convergeStoreDeny` returns nil when a keyless or trashed app’s `GrantHealthy` read fails ([planstorage.go:115](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planstorage.go:115), [line 126](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planstorage.go:126)). Other seal-key failures also return nil ([line 130](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planstorage.go:130)). Settlement then sets `planExemptSettled` ([planexempt.go:89](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/planexempt.go:89)). |
| + |
| + **Failure scenario:** ops has a denied store on a trashed app. During startup cleanup, one config-manifest GET fails inside `GrantHealthy`. The helper skips the store and reports success. If the other steps succeed, settlement finishes permanently for that process. Restoring the app leaves uploads denied; later limits passes skip settlement, and the grace pass exits before storage cleanup because ops has no effective limits ([plangracepass.go:82](/home/paulca/.cache/tmp/claude-1001/ops-plan-exempt/internal/console/plangracepass.go:82)). |
| + |
| + **Concrete fix:** propagate incomplete storage convergence to settlement, including skipped stores, and add a regression that fails one manifest read and verifies successful cleanup on the next pass. Under the final-round stopping rule, take this scope decision to Paul first; a concrete cut is to require verified absence of ops storage denies before enabling the exemption. |
| + |
| + **Invariant / fault family:** exemption settlement is complete only when every existing plan storage deny has been removed. |
| + |
| +No new P2 or P3 findings. The merged billing success screen and usage view remain excluded for ops. |
| + |
| +No root-binary package changed, confirmed through Linux amd64 and arm64 dependency listings; no root-read census card is required. Changed Go files are formatted. Targeted tests could not start because the read-only sandbox prevented Go’s work-directory creation, so census passes were not independently reproduced. `git diff --check` reports only trailing spaces in archived findings. No files were edited. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt-R2.md| new file mode 100644 |
| index 000000000..715c18730 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt-R2.md |
| @@ -0,0 +1,41 @@ |
| +# Review brief: branch ops-plan-exempt, round 2 of 3 |
| + |
| +Repo carlos/platform, branch `ops-plan-exempt`, the commit that adds this brief (named in your prompt). |
| +Under review: the diff `origin/main...HEAD`. |
| +Authorities: the plans spec `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md` and docs/site/plans.md (merged on main), plus Paul's requirement (2026-10-28): "The ops account needs to be exempt", and "because my paul@keymail.dev owns ops, it counts against my 1 free account". |
| + |
| +You are an independent reviewer. Read the diff and the code it touches, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The built-in ops account (account #1, internal/registry/registry.go:353, :895) is exempt from plans: no limits record, no caps, warnings, grace, after-grace, throttle or lapse, no billing, and it does not count toward free_accounts_per_person. The plan door refuses it. |
| +- One predicate, `(s *Store) planExempt`, enforced in one place, pinned by `TestPlanExemptConsulted`. |
| + |
| +## What to check |
| + |
| +1. Every path that applies a limit, cap, lifecycle stage, billing action or free-account count either consults `planExempt` (directly or through `EffectiveLimits`) or cannot reach ops. Look for paths the guard test's list misses: box-side limits, the storage deny, email and bandwidth stages, the lapse switch-off, member caps, the billing passes and doors, /upgrade. |
| +2. No other account is exempted by accident: the predicate is true for ops only in production (`planExemptID` is set to OpsAccountID), and test-only overrides cannot leak into production. |
| +3. `settlePlanExempt` deletes `accounts/<ops sqid>/limits.json` and any storage deny at console start: it can touch only ops's own objects, it is safe when the objects are missing, and it costs at most the stated requests per start (S3 requests cost money: no new per-box polling). |
| +4. The box side: a missing limits record really means "no limits" to plansPass and the activator (check the box code, not the comments). |
| +5. The plan door's 409 for ops (show and set), and that existing ops rows are never read for a decision. |
| +6. The census (you judge it; Paul does not rule on census classes, #280): the implementer reports the root-read and record-write censuses pass with no card. Confirm no root package changed, or say what did. |
| + |
| +## Round 2 |
| + |
| +Earlier round: `docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r1.md` (at e492e431: 2 P1, 1 P2). The fix is commit 4f11128a. Each invariant is now enforced at one shared point: `settlePlanExempt` (internal/console/planexempt.go) clears every plan-enforced state for ops (limits record, storage denies on live and trashed apps, PauseKindPlan mail pauses, cap rows, lapse items); `holdBilling(acct)` refuses ops (the only place a billing hold is made) and `billingOwner` is the entry for every /a/{sqid}/billing/ route, pinned by `TestBillingDoorsEnterThroughBillingOwner`. |
| + |
| +First give one line per round 1 finding: resolved, partly, or not. Carry forward anything unresolved, then add new findings, looking first at the fix (newly changed billing and production-storage behaviour). The verdict covers everything outstanding. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant it breaks. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt-R3.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt-R3.md| new file mode 100644 |
| index 000000000..659051f75 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt-R3.md |
| @@ -0,0 +1,41 @@ |
| +# Review brief: branch ops-plan-exempt, round 3 of 3 |
| + |
| +Repo carlos/platform, branch `ops-plan-exempt`, the commit that adds this brief (named in your prompt). |
| +Under review: the diff `origin/main...HEAD`. |
| +Authorities: the plans spec `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md` and docs/site/plans.md (merged on main), plus Paul's requirement (2026-10-28): "The ops account needs to be exempt", and "because my paul@keymail.dev owns ops, it counts against my 1 free account". |
| + |
| +You are an independent reviewer. Read the diff and the code it touches, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The built-in ops account (account #1, internal/registry/registry.go:353, :895) is exempt from plans: no limits record, no caps, warnings, grace, after-grace, throttle or lapse, no billing, and it does not count toward free_accounts_per_person. The plan door refuses it. |
| +- One predicate, `(s *Store) planExempt`, enforced in one place, pinned by `TestPlanExemptConsulted`. |
| + |
| +## What to check |
| + |
| +1. Every path that applies a limit, cap, lifecycle stage, billing action or free-account count either consults `planExempt` (directly or through `EffectiveLimits`) or cannot reach ops. Look for paths the guard test's list misses: box-side limits, the storage deny, email and bandwidth stages, the lapse switch-off, member caps, the billing passes and doors, /upgrade. |
| +2. No other account is exempted by accident: the predicate is true for ops only in production (`planExemptID` is set to OpsAccountID), and test-only overrides cannot leak into production. |
| +3. `settlePlanExempt` deletes `accounts/<ops sqid>/limits.json` and any storage deny at console start: it can touch only ops's own objects, it is safe when the objects are missing, and it costs at most the stated requests per start (S3 requests cost money: no new per-box polling). |
| +4. The box side: a missing limits record really means "no limits" to plansPass and the activator (check the box code, not the comments). |
| +5. The plan door's 409 for ops (show and set), and that existing ops rows are never read for a decision. |
| +6. The census (you judge it; Paul does not rule on census classes, #280): the implementer reports the root-read and record-write censuses pass with no card. Confirm no root package changed, or say what did. |
| + |
| +## Round 3 (the last) |
| + |
| +Earlier rounds: `docs/superpowers/reviews/CODEX-FINDINGS-ops-plan-exempt-r1.md` (2 P1, 1 P2) and `CODEX-FINDINGS-ops-plan-exempt-r2.md` (1 P1 in the mail family, 2 P2). Stopping rule 2 triggered on the mail family and Paul chose the cut (discussion 455): `settlePlanExempt` no longer lifts plan mail pauses (none can exist on ops: flagship has no catalog, dev's ops was sponsored at once; the exemption stops new ones because enforceAccountMail reads EffectiveLimits, nil for ops). Do not re-raise the cut mail clean-up. Round 2's P2s are fixed in 2f31a678 (`openBillingProblemTx` opens nothing for ops; the house door refuses ops). Main was merged in afterwards (40 commits: the billing success screen, the usage view, the billing restyle); the one conflict, billingPageInput's fields, kept both sides. |
| + |
| +First give one line per round 1 and round 2 finding: resolved, partly, cut (mail), or not. Then new findings, looking first at the round 2 fixes and at how main's new billing code (success screen, usage view from plan_cap_state) treats ops. This is the last round: a P1 here means cutting scope and asking Paul, so state each P1's failure scenario precisely. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant it breaks. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. |
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt.md| new file mode 100644 |
| index 000000000..ac302e285 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-ops-plan-exempt.md |
| @@ -0,0 +1,35 @@ |
| +# Review brief: branch ops-plan-exempt, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `ops-plan-exempt`, the commit that adds this brief (named in your prompt). |
| +Under review: the diff `origin/main...HEAD`. |
| +Authorities: the plans spec `docs/superpowers/specs/2026-10-20-plans-caps-packs-design.md` and docs/site/plans.md (merged on main), plus Paul's requirement (2026-10-28): "The ops account needs to be exempt", and "because my paul@keymail.dev owns ops, it counts against my 1 free account". |
| + |
| +You are an independent reviewer. Read the diff and the code it touches, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The built-in ops account (account #1, internal/registry/registry.go:353, :895) is exempt from plans: no limits record, no caps, warnings, grace, after-grace, throttle or lapse, no billing, and it does not count toward free_accounts_per_person. The plan door refuses it. |
| +- One predicate, `(s *Store) planExempt`, enforced in one place, pinned by `TestPlanExemptConsulted`. |
| + |
| +## What to check |
| + |
| +1. Every path that applies a limit, cap, lifecycle stage, billing action or free-account count either consults `planExempt` (directly or through `EffectiveLimits`) or cannot reach ops. Look for paths the guard test's list misses: box-side limits, the storage deny, email and bandwidth stages, the lapse switch-off, member caps, the billing passes and doors, /upgrade. |
| +2. No other account is exempted by accident: the predicate is true for ops only in production (`planExemptID` is set to OpsAccountID), and test-only overrides cannot leak into production. |
| +3. `settlePlanExempt` deletes `accounts/<ops sqid>/limits.json` and any storage deny at console start: it can touch only ops's own objects, it is safe when the objects are missing, and it costs at most the stated requests per start (S3 requests cost money: no new per-box polling). |
| +4. The box side: a missing limits record really means "no limits" to plansPass and the activator (check the box code, not the comments). |
| +5. The plan door's 409 for ops (show and set), and that existing ops rows are never read for a decision. |
| +6. The census (you judge it; Paul does not rule on census classes, #280): the implementer reports the root-read and record-write censuses pass with no card. Confirm no root package changed, or say what did. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant it breaks. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites. |
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go| index 62b4db272..87a84d482 100644 |
| --- a/internal/console/accountplans.go |
| +++ b/internal/console/accountplans.go |
| @@ -240,13 +240,14 @@ func billingSetPlan(tx *sql.Tx, accountID int64, plan string, packs map[string]i |
| } |
| // EnsureDefaultPlans gives every live account without a plan row the |
| -// default plan, and reports how many rows it inserted. |
| +// default plan, and reports how many rows it inserted. The exempt account |
| +// (planExempt) gets none. |
| func (s *Store) EnsureDefaultPlans(defaultPlan string, now time.Time) (int, error) { |
| res, err := s.db.Exec(`INSERT INTO account_plans |
| (account_id, plan, packs, source, revision, updated_by, updated_at) |
| SELECT id, ?, '{}', ?, 1, ?, ? FROM accounts |
| - WHERE deleted_at = 0 AND id NOT IN (SELECT account_id FROM account_plans)`, |
| - defaultPlan, PlanSourceDefault, planDefaultActor, now.Unix()) |
| + WHERE deleted_at = 0 AND id != ? AND id NOT IN (SELECT account_id FROM account_plans)`, |
| + defaultPlan, PlanSourceDefault, planDefaultActor, now.Unix(), s.planExemptID) |
| if err != nil { |
| return 0, err |
| } |
diff --git a/internal/console/apiaccountplan.go b/internal/console/apiaccountplan.go| index d7d0dd575..649cde6eb 100644 |
| --- a/internal/console/apiaccountplan.go |
| +++ b/internal/console/apiaccountplan.go |
| @@ -15,7 +15,8 @@ import ( |
| // The account plan door (plans-caps-packs spec §4, §8.7, §9.4): a fleet |
| // operator reads or sets an account's plan, packs and sponsored limits. |
| // Everyone else gets 404, the store-approval doors' convention. With no |
| -// catalog configured it answers 409: plans are off. |
| +// catalog configured it answers 409: plans are off. The exempt ops account |
| +// (planExempt) answers 409 too, to a read as to a change: it has no plan. |
| type accountPlanReply struct { |
| Account string `json:"account"` |
| @@ -70,6 +71,10 @@ func (s *Server) accountPlanDoor(w http.ResponseWriter, r *http.Request) (string |
| jsonError(w, http.StatusConflict, planCopyNoCatalog) |
| return "", nil, false |
| } |
| + if s.store.planExempt(acct.ID) { |
| + jsonError(w, http.StatusConflict, planCopyExempt) |
| + return "", nil, false |
| + } |
| return addr, acct, true |
| } |
diff --git a/internal/console/apiaccountplan_copy.go b/internal/console/apiaccountplan_copy.go| index e9e62051f..9f4e307ee 100644 |
| --- a/internal/console/apiaccountplan_copy.go |
| +++ b/internal/console/apiaccountplan_copy.go |
| @@ -11,4 +11,7 @@ const ( |
| planCopyPackNotOffered = "the %s plan does not offer the %s pack" |
| planCopyPackQuantity = "the %s pack can be bought 1 to %d times" |
| planCopySaveFailed = "could not save the plan. try again" |
| + // Draft (2026-10-28), awaiting copy review: the plan door's answer for |
| + // the exempt ops account. |
| + planCopyExempt = "the ops account is exempt from plans. it has no limits, caps or billing" |
| ) |
diff --git a/internal/console/apibilling.go b/internal/console/apibilling.go| index 93ee363ac..532a24246 100644 |
| --- a/internal/console/apibilling.go |
| +++ b/internal/console/apibilling.go |
| @@ -171,7 +171,10 @@ func (s *Server) closeBillingProblem(ctx context.Context, p *billingProblem, add |
| return http.StatusInternalServerError, billingCopyFailed |
| } |
| if acct != nil { |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return http.StatusConflict, planCopyExempt |
| + } |
| defer release() |
| return s.closeBillingProblemLocked(h, ctx, p, addr, note, now) |
| } |
diff --git a/internal/console/apibillinghouse.go b/internal/console/apibillinghouse.go| index 2512b932a..606d95528 100644 |
| --- a/internal/console/apibillinghouse.go |
| +++ b/internal/console/apibillinghouse.go |
| @@ -14,8 +14,8 @@ import ( |
| // handleAPIBillingHouse is POST /api/cli/billing/house, body |
| // {"account":"<sqid>","on":true,"note":"..."}. It goes through billingDoor |
| -// (signed in, operator, billing configured). An empty note is 400 and an |
| -// unknown account 404. It writes an audit line. Clearing an account that is |
| +// (signed in, operator, billing configured). An empty note is 400, an |
| +// unknown account 404, and the exempt ops account 409 (planExempt). It writes an audit line. Clearing an account that is |
| // not marked is not an error. |
| func (s *Server) handleAPIBillingHouse(w http.ResponseWriter, r *http.Request) { |
| addr, ok := s.billingDoor(w, r) |
| @@ -45,6 +45,10 @@ func (s *Server) handleAPIBillingHouse(w http.ResponseWriter, r *http.Request) { |
| http.NotFound(w, r) |
| return |
| } |
| + if s.store.planExempt(acct.ID) { |
| + jsonError(w, http.StatusConflict, planCopyExempt) |
| + return |
| + } |
| if err := s.store.SetBillingHouse(acct.ID, req.On, addr, note, time.Now()); err != nil { |
| log.Printf("console: api billing house %s: %v", acct.Sqid, err) |
| jsonError(w, http.StatusInternalServerError, billingCopyFailed) |
diff --git a/internal/console/apiinstances_ratelimit_test.go b/internal/console/apiinstances_ratelimit_test.go| index dd020cad3..497bdff3a 100644 |
| --- a/internal/console/apiinstances_ratelimit_test.go |
| +++ b/internal/console/apiinstances_ratelimit_test.go |
| @@ -140,6 +140,7 @@ func TestPatchRateLimitOverPlanCeiling(t *testing.T) { |
| // Installed after the create: the catalog's running_things cap is not |
| // what this test is about. |
| fx.srv.cfg.PlanCatalog = rlCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| refused := []struct{ body, want string }{ |
| {`{"rate":500}`, "The backstop rate can be at most 400 on this account's plan."}, |
| @@ -244,6 +245,7 @@ func TestRateLimitGet(t *testing.T) { |
| } |
| fx.srv.cfg.PlanCatalog = rlCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| status, _, out = rawReq(t, http.MethodGet, gu, token, "") |
| if status != http.StatusOK { |
| t.Fatalf("GET = %d %s", status, out) |
diff --git a/internal/console/apiplacements_put_test.go b/internal/console/apiplacements_put_test.go| index 6510ae245..b2b2fa12b 100644 |
| --- a/internal/console/apiplacements_put_test.go |
| +++ b/internal/console/apiplacements_put_test.go |
| @@ -1050,6 +1050,7 @@ func TestPlacementsPutPlanCapComesFirst(t *testing.T) { |
| attachShopClaim(t, w.fx, w.fx.sqid, "shop", "alias.example.com", rdIE) |
| attachShopClaim(t, w.fx, "zzz", "blog", "theirs.example.com", "theirs.example.net") |
| w.fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(w.fx) // the fixture account is ops |
| if _, err := w.fx.st.SetAccountPlan(OpsAccountID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", time.Now()); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/appsettings_ratelimit_test.go b/internal/console/appsettings_ratelimit_test.go| index 25a1f1dbe..d4b7cec62 100644 |
| --- a/internal/console/appsettings_ratelimit_test.go |
| +++ b/internal/console/appsettings_ratelimit_test.go |
| @@ -142,6 +142,7 @@ func TestAppSettingsRateLimitKeepsPaths(t *testing.T) { |
| // Under a plan the lines show what the edge applies: clamped. |
| fx.srv.cfg.PlanCatalog = rlCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| _, _, body = get(t, c, fx.u("/apps/shop/settings/domains")) |
| if want := "<li>/api/ 8 in flight per address when busy, backstop 77 a second, bursts of 1000</li>"; !strings.Contains(body, want) { |
| t.Fatalf("page lacks the clamped line %q: %s", want, body) |
| @@ -173,6 +174,7 @@ func TestAppSettingsRateLimitKeepsPaths(t *testing.T) { |
| func TestAppSettingsRateLimitOverCeiling(t *testing.T) { |
| fx, c, csrf := rlSettingsFixture(t, "code-settings-rl-ceiling") |
| fx.srv.cfg.PlanCatalog = rlCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| status, loc, _ := postForm(t, c, fx.u("/apps/shop/ratelimit"), |
| rlForm(csrf, "set", "busy_at", "", "client_share", "", "rate", "500", "burst", "")) |
diff --git a/internal/console/billingchange.go b/internal/console/billingchange.go| index 0ec40836f..5b6ae6f2d 100644 |
| --- a/internal/console/billingchange.go |
| +++ b/internal/console/billingchange.go |
| @@ -146,11 +146,7 @@ func (s *Server) parseChangeForm(r *http.Request) (changeAsk, bool) { |
| // (Call 6), before the hold. An unconfirmed charge answers the confirm page; |
| // everything else goes back to the billing page with a flash. |
| func (s *Server) handleBillingChange(w http.ResponseWriter, r *http.Request) { |
| - if s.billing == nil { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - addr, raw, acct, ok := s.owner(w, r) |
| + addr, raw, acct, ok := s.billingOwner(w, r) |
| if !ok { |
| return |
| } |
| @@ -170,7 +166,11 @@ func (s *Server) handleBillingChange(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx := s.billingClock(r.Context()) |
| now := time.Now() |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + s.holdRefused(w, r, acct, err) |
| + return |
| + } |
| reply, err := s.changeLocked(h, ctx, acct, ask, now) |
| release() |
| if err != nil { |
| @@ -576,11 +576,7 @@ func packsDone() changeReply { |
| // it charges nothing (Call 6). Billing off answers 404, a member 404, no CSRF |
| // 403. |
| func (s *Server) handleBillingRenewal(w http.ResponseWriter, r *http.Request) { |
| - if s.billing == nil { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - _, raw, acct, ok := s.owner(w, r) |
| + _, raw, acct, ok := s.billingOwner(w, r) |
| if !ok { |
| return |
| } |
| @@ -597,7 +593,11 @@ func (s *Server) handleBillingRenewal(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx := s.billingClock(r.Context()) |
| now := time.Now() |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + s.holdRefused(w, r, acct, err) |
| + return |
| + } |
| reply, err := s.renewalLocked(h, ctx, acct, v == "resume", now) |
| release() |
| if err != nil { |
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go| index c6c3ab6e1..151070584 100644 |
| --- a/internal/console/billingcheckout.go |
| +++ b/internal/console/billingcheckout.go |
| @@ -148,11 +148,7 @@ func (s *Server) parseCheckoutForm(r *http.Request) (checkoutAsk, string) { |
| // a member the owner gate's 404, no CSRF 403. Success is a redirect to the |
| // payment page; anything else goes back to the billing page with a flash. |
| func (s *Server) handleBillingCheckout(w http.ResponseWriter, r *http.Request) { |
| - if s.billing == nil { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - _, raw, acct, ok := s.owner(w, r) |
| + _, raw, acct, ok := s.billingOwner(w, r) |
| if !ok { |
| return |
| } |
| @@ -174,7 +170,11 @@ func (s *Server) handleBillingCheckout(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx := s.billingClock(r.Context()) |
| now := time.Now() |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + s.holdRefused(w, r, acct, err) |
| + return |
| + } |
| to, err := s.checkoutLocked(h, ctx, acct, ask, now) |
| release() |
| if err != nil { |
| @@ -1012,11 +1012,7 @@ func (s *Server) confirmCheckoutLocked(h billingHold, ctx context.Context, acct |
| // only while open with more than continueMargin left in the read's provider |
| // time. Otherwise a flash and back to the billing page. |
| func (s *Server) handleBillingContinue(w http.ResponseWriter, r *http.Request) { |
| - if s.billing == nil { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - _, _, acct, ok := s.owner(w, r) |
| + _, _, acct, ok := s.billingOwner(w, r) |
| if !ok { |
| return |
| } |
| @@ -1028,7 +1024,11 @@ func (s *Server) handleBillingContinue(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx := s.billingClock(r.Context()) |
| now := time.Now() |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + s.holdRefused(w, r, acct, err) |
| + return |
| + } |
| to, key, err := s.continueLocked(h, ctx, acct, now) |
| release() |
| if err != nil { |
| @@ -1082,11 +1082,7 @@ func (s *Server) continueLocked(h billingHold, ctx context.Context, acct *Accoun |
| // which the page checks against the account's state again) and a flash |
| // naming the plan, which the success screen replaces. |
| func (s *Server) handleBillingDone(w http.ResponseWriter, r *http.Request) { |
| - if s.billing == nil { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - _, _, acct, ok := s.owner(w, r) |
| + _, _, acct, ok := s.billingOwner(w, r) |
| if !ok { |
| return |
| } |
| @@ -1097,7 +1093,11 @@ func (s *Server) handleBillingDone(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx := s.billingClock(r.Context()) |
| now := time.Now() |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + s.holdRefused(w, r, acct, err) |
| + return |
| + } |
| kind, text, err := s.doneLocked(h, ctx, acct, r.URL.Query().Get("session"), now) |
| release() |
| if err != nil { |
| @@ -1183,7 +1183,10 @@ func (s *Server) observeCheckoutEvent(ctx context.Context, session string, now t |
| if err != nil || acct == nil { |
| return false, err |
| } |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return true, nil // the exempt account: billing ignores it |
| + } |
| defer release() |
| cur, err := s.store.CheckoutIntent(acct.ID) |
| if err != nil || cur == nil || cur.ID != ci.ID || intentTerminal(cur) { |
diff --git a/internal/console/billinghold.go b/internal/console/billinghold.go| index 717bb6075..b4498f99b 100644 |
| --- a/internal/console/billinghold.go |
| +++ b/internal/console/billinghold.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "fmt" |
| + "net/http" |
| "time" |
| "github.com/carlosframework/platform/internal/billing" |
| @@ -67,13 +68,51 @@ type billingRefusal struct{ Key string } |
| func (r billingRefusal) Error() string { return "billing: refused: " + r.Key } |
| // holdBilling takes the account's billing lock and returns the hold and its |
| -// release. It is the only place the billing lock is taken. |
| +// release. It is the only place the billing lock is taken, and so the one |
| +// place the exempt ops account (planExempt) is refused billing: for it the |
| +// answer is errBillingExempt, no lock and a release that does nothing, so |
| +// no billing work (a door, a pass, a webhook sync, an invite's seat) can |
| +// act on it. Every function that acts on billing state takes the hold |
| +// (TestBillingLockedHelpersNeverLock, TestBillingHoldMintedOnlyByHoldBilling). |
| // |
| -// h, release := s.holdBilling(acct.Sqid) |
| +// h, release, err := s.holdBilling(acct) |
| +// if err != nil { ... } |
| // defer release() |
| -func (s *Server) holdBilling(sqid string) (billingHold, func()) { |
| - release := s.billing.locks.lock(sqid) |
| - return billingHold{sqid: sqid}, release |
| +func (s *Server) holdBilling(acct *Account) (billingHold, func(), error) { |
| + if s.store.planExempt(acct.ID) { |
| + return billingHold{}, func() {}, errBillingExempt |
| + } |
| + release := s.billing.locks.lock(acct.Sqid) |
| + return billingHold{sqid: acct.Sqid}, release, nil |
| +} |
| + |
| +// billingOwner is every billing door's entry (the routes under |
| +// /a/{sqid}/billing/, TestBillingDoorsEnterThroughBillingOwner): billing |
| +// off answers 404, then the owner gate, then the exempt ops account |
| +// (planExempt) goes back to its billing page with notice.exempt, before |
| +// any billing state is read or any form is looked at. |
| +func (s *Server) billingOwner(w http.ResponseWriter, r *http.Request) (addr, raw string, acct *Account, ok bool) { |
| + if s.billing == nil { |
| + http.NotFound(w, r) |
| + return "", "", nil, false |
| + } |
| + addr, raw, acct, ok = s.owner(w, r) |
| + if !ok { |
| + return "", "", nil, false |
| + } |
| + if s.store.planExempt(acct.ID) { |
| + s.setFlash(w, "err", billingCopy[errBillingExempt.Key]) |
| + http.Redirect(w, r, billingPagePath(acct.Sqid), http.StatusSeeOther) |
| + return "", "", nil, false |
| + } |
| + return addr, raw, acct, true |
| +} |
| + |
| +// holdRefused answers a door whose billing hold was refused: back to the |
| +// billing page with the refusal's copy. |
| +func (s *Server) holdRefused(w http.ResponseWriter, r *http.Request, acct *Account, err error) { |
| + s.setFlash(w, "err", changeText(acct.Sqid, err)) |
| + http.Redirect(w, r, billingPagePath(acct.Sqid), http.StatusSeeOther) |
| } |
| // billingClock is ctx with a provider-time recorder for one request or one |
diff --git a/internal/console/billinglate.go b/internal/console/billinglate.go| index 201d2b1f8..5e05689f4 100644 |
| --- a/internal/console/billinglate.go |
| +++ b/internal/console/billinglate.go |
| @@ -156,7 +156,7 @@ func (s *Store) FlagRestoreCheck(opID, detail string, now time.Time) error { |
| if err != nil { |
| return err |
| } |
| - if _, err := openBillingProblemTx(tx, accountID, subscription, problemRestoreAfterRenewal, detail, now); err != nil { |
| + if _, err := s.openBillingProblemTx(tx, accountID, subscription, problemRestoreAfterRenewal, detail, now); err != nil { |
| return err |
| } |
| return tx.Commit() |
| @@ -187,7 +187,7 @@ func (s *Store) StallRestoreCheck(opID string, providerNow, now time.Time) error |
| } |
| detail := fmt.Sprintf("restore %s has not been verified %s after the renewal of %s", opID, |
| restoreStallAfter.String(), time.Unix(periodEnd, 0).UTC().Format(time.RFC3339)) |
| - if _, err := openBillingProblemTx(tx, accountID, subscription, problemRestoreCheckStalled, detail, now); err != nil { |
| + if _, err := s.openBillingProblemTx(tx, accountID, subscription, problemRestoreCheckStalled, detail, now); err != nil { |
| return err |
| } |
| return tx.Commit() |
| @@ -321,7 +321,10 @@ func (s *Server) restoreStallsForMissing(ctx context.Context, subscription strin |
| if err != nil || acct == nil { |
| return err |
| } |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return nil // the exempt account: billing ignores it |
| + } |
| defer release() |
| return s.restoreStallsForMissingLocked(h, ctx, subscription, now) |
| } |
diff --git a/internal/console/billinglate_test.go b/internal/console/billinglate_test.go| index 5eea72b41..7052face1 100644 |
| --- a/internal/console/billinglate_test.go |
| +++ b/internal/console/billinglate_test.go |
| @@ -48,7 +48,14 @@ func (o *opsFixture) heldRestore(t *testing.T, id, subID string) billingOp { |
| o.observe() |
| op := o.restoreOp(t, id, subID) |
| o.fake.ApplyAfterRenewal(op.Prepared.Key) |
| - h, release := o.srv.holdBilling(o.sqidOf(t, subID)) |
| + acct, err := o.st.AccountBySqid(o.sqidOf(t, subID)) |
| + if err != nil || acct == nil { |
| + t.Fatalf("account of %s: %v", subID, err) |
| + } |
| + h, release, err := o.srv.holdBilling(acct) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| out, _, err := o.srv.sendOpLocked(h, o.ctx, op, billingNow) |
| release() |
| if err != nil || out.State != opUnresolved { |
diff --git a/internal/console/billingops.go b/internal/console/billingops.go| index 98525c99b..ce78dd797 100644 |
| --- a/internal/console/billingops.go |
| +++ b/internal/console/billingops.go |
| @@ -732,11 +732,7 @@ func (s *Server) confirmBillingLocked(h billingHold, ctx context.Context, acct * |
| // the account's outstanding work finished under the hold, then a redirect |
| // to the billing page with what happened. |
| func (s *Server) handleBillingConfirm(w http.ResponseWriter, r *http.Request) { |
| - if s.billing == nil { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - _, raw, acct, ok := s.owner(w, r) |
| + _, raw, acct, ok := s.billingOwner(w, r) |
| if !ok { |
| return |
| } |
| @@ -752,7 +748,11 @@ func (s *Server) handleBillingConfirm(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx := s.billingClock(r.Context()) |
| now := time.Now() |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + s.holdRefused(w, r, acct, err) |
| + return |
| + } |
| kind, key, err := s.confirmBillingLocked(h, ctx, acct, now) |
| release() |
| if err != nil { |
diff --git a/internal/console/billingops_test.go b/internal/console/billingops_test.go| index bc88e251c..066188ac4 100644 |
| --- a/internal/console/billingops_test.go |
| +++ b/internal/console/billingops_test.go |
| @@ -181,7 +181,13 @@ func (o *opsFixture) unresolved(t *testing.T, op billingOp) { |
| } |
| } |
| -func (o *opsFixture) hold() (billingHold, func()) { return o.srv.holdBilling(o.acct.Sqid) } |
| +func (o *opsFixture) hold() (billingHold, func()) { |
| + h, release, err := o.srv.holdBilling(o.acct) |
| + if err != nil { |
| + panic(err) |
| + } |
| + return h, release |
| +} |
| func (o *opsFixture) send(t *testing.T, op billingOp) (opOutcome, *billing.Subscription, error) { |
| t.Helper() |
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go| index 4357f028e..dc027c2c3 100644 |
| --- a/internal/console/billingpage.go |
| +++ b/internal/console/billingpage.go |
| @@ -49,7 +49,9 @@ type billingPageInput struct { |
| Op *billingOp // the outstanding operation, nil for none |
| Problems []string // open problem reasons |
| Retiring, Ready, Owner bool |
| - Now time.Time |
| + // Exempt is the ops account, which has no plan (planExempt). |
| + Exempt bool |
| + Now time.Time |
| // Caps is the plan-limits pass's rows for the account (plan_cap_state), |
| // the usage the page shows (billingusage.go). |
| Caps []capState |
| @@ -93,6 +95,8 @@ func decideBillingOwner(in billingPageInput) (string, []string) { |
| op = nil |
| } |
| switch { |
| + case in.Exempt: |
| + return "notice.exempt", nil |
| case !in.Ready: |
| return "notice.not_ready", nil |
| case in.Retiring: |
| @@ -301,7 +305,10 @@ type billingChangeView struct { |
| // billingPageInputFor reads the stored facts the page decides from. |
| func (s *Server) billingPageInputFor(acct *Account, role string, now time.Time) (billingPageInput, error) { |
| - in := billingPageInput{Owner: role == RoleOwner, Ready: s.billing.ready.Load(), Now: now} |
| + in := billingPageInput{Owner: role == RoleOwner, Ready: s.billing.ready.Load(), Exempt: s.store.planExempt(acct.ID), Now: now} |
| + if in.Exempt { |
| + return in, nil // nothing else decides its page |
| + } |
| var err error |
| if in.Row, err = s.store.AccountPlan(acct.ID); err != nil { |
| return in, err |
| @@ -389,6 +396,9 @@ func (s *Server) billingViewFor(r *http.Request, in billingPageInput, st billing |
| if st.OwnersOnly { |
| v.OwnersOnly = billingCopy["notice.owners_only"] |
| } |
| + if in.Exempt { |
| + return v // no plan, so no facts about one |
| + } |
| for _, k := range st.Offered { |
| switch k { |
| case offerBuy: |
| @@ -869,7 +879,8 @@ func (s *Server) handleUpgrade(w http.ResponseWriter, r *http.Request) { |
| } |
| var owned []Account |
| for _, a := range accts { |
| - if a.Role == RoleOwner { |
| + // The exempt account has nothing to buy (planExempt). |
| + if a.Role == RoleOwner && !s.store.planExempt(a.ID) { |
| owned = append(owned, a) |
| } |
| } |
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go| index 9594d9d13..9f8f33381 100644 |
| --- a/internal/console/billingpage_copy.go |
| +++ b/internal/console/billingpage_copy.go |
| @@ -72,6 +72,7 @@ var billingCopy = map[string]string{ |
| "notice.seats_unpaid": "This account has more members than it pays for. Remove members, or ask an operator.", |
| "notice.unresolved": "We couldn't confirm a recent change, and someone is checking it. Nothing more will be charged.", |
| "notice.operator_plan": "An operator set this account's plan, so there's nothing to buy here.", |
| + "notice.exempt": "This is the deployment's own account. It has no plan, so there's nothing to buy here.", // draft 2026-10-28, awaiting copy review |
| "notice.confirming": "We're confirming a recent change. Nothing more will be charged.", |
| "notice.settling": "We're confirming your payment. This page shows your new plan once it's done.", |
| "notice.pending_payment": "A change is waiting for payment. Pay it from Payment and invoices, or it will be dropped after a day.", |
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go| index d78f3bd88..3023d30e8 100644 |
| --- a/internal/console/billingpass.go |
| +++ b/internal/console/billingpass.go |
| @@ -107,7 +107,8 @@ func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| // stops the others. The round shares one provider-time recorder: an |
| // observation at most observationMaxAge old serves every decision in the |
| // round, and a decision reached after it expires probes again. The pass |
| -// never writes to the provider (Invariant 5). |
| +// never writes to the provider (Invariant 5). Every part of it skips the |
| +// exempt account (planExempt), which billing never governs. |
| func (s *Server) billingSyncPass(ctx context.Context, now time.Time) { |
| if s.billing == nil || !s.billing.ready.Load() { |
| return |
| @@ -124,6 +125,9 @@ func (s *Server) billingSyncPass(ctx context.Context, now time.Time) { |
| } |
| for _, b := range page { |
| after = b.AccountID |
| + if s.store.planExempt(b.AccountID) { |
| + continue |
| + } |
| if err := s.syncSubscription(ctx, b.Subscription, now); err != nil { |
| log.Printf("console: billing sync pass: account %d: %v", b.AccountID, err) |
| jobFailed(ctx, fmt.Errorf("billing sync pass: account %d: %w", b.AccountID, err)) |
| @@ -172,6 +176,9 @@ func (s *Server) billingIntentPass(ctx context.Context, now time.Time) { |
| } |
| func (s *Server) observeIntent(ctx context.Context, ci checkoutIntent, now time.Time) { |
| + if s.store.planExempt(ci.AccountID) { |
| + return |
| + } |
| acct, err := s.store.AccountByID(ci.AccountID) |
| if err != nil || acct == nil { |
| log.Printf("console: billing intent pass: intent %s: account %d: %v", ci.ID, ci.AccountID, err) |
| @@ -187,7 +194,10 @@ func (s *Server) observeIntent(ctx context.Context, ci checkoutIntent, now time. |
| return |
| } |
| } |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return |
| + } |
| defer release() |
| cur, err := s.store.CheckoutIntent(acct.ID) |
| if err != nil || cur == nil || cur.ID != ci.ID || intentTerminal(cur) { |
| @@ -225,12 +235,18 @@ func (s *Server) billingOpsPass(ctx context.Context, now time.Time, synced map[s |
| } |
| func (s *Server) observeOp(ctx context.Context, op billingOp, now time.Time, synced map[string]bool) { |
| + if s.store.planExempt(op.AccountID) { |
| + return |
| + } |
| acct, err := s.store.AccountByID(op.AccountID) |
| if err != nil || acct == nil { |
| log.Printf("console: billing ops pass: operation %s: account %d: %v", op.ID, op.AccountID, err) |
| return |
| } |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return |
| + } |
| defer release() |
| if !synced[op.Subscription] { |
| if err := s.syncSubscriptionLocked(h, ctx, acct, op.Subscription, now); err != nil { |
| @@ -277,7 +293,7 @@ func (s *Server) billingRestorePass(ctx context.Context, now time.Time, synced m |
| } |
| for _, c := range page { |
| afterCreated, afterID = c.CreatedAt, c.OpID |
| - if synced[c.Subscription] { |
| + if synced[c.Subscription] || s.store.planExempt(c.AccountID) { |
| continue |
| } |
| acct, err := s.store.AccountByID(c.AccountID) |
| @@ -285,7 +301,10 @@ func (s *Server) billingRestorePass(ctx context.Context, now time.Time, synced m |
| log.Printf("console: billing restore pass: obligation %s: account %d: %v", c.OpID, c.AccountID, err) |
| continue |
| } |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + continue |
| + } |
| err = s.syncSubscriptionLocked(h, ctx, acct, c.Subscription, now) |
| release() |
| if err != nil { |
| @@ -318,7 +337,9 @@ func (s *Server) billingDiscoveryPass(ctx context.Context, now time.Time) { |
| } |
| for _, b := range page { |
| after = b.AccountID |
| - s.discoverCustomer(ctx, b, now) |
| + if !s.store.planExempt(b.AccountID) { |
| + s.discoverCustomer(ctx, b, now) |
| + } |
| } |
| if len(page) < billingSyncBatch { |
| return |
diff --git a/internal/console/billingportal.go b/internal/console/billingportal.go| index 3ae012949..fb320b272 100644 |
| --- a/internal/console/billingportal.go |
| +++ b/internal/console/billingportal.go |
| @@ -31,11 +31,7 @@ func newPortalNonce() string { |
| // proof is required (the step-up redirect when stale) and the owner is sent |
| // to the provider's page, which returns to the billing page. |
| func (s *Server) handleBillingPortal(w http.ResponseWriter, r *http.Request) { |
| - if s.billing == nil { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - addr, raw, acct, ok := s.owner(w, r) |
| + addr, raw, acct, ok := s.billingOwner(w, r) |
| if !ok { |
| return |
| } |
diff --git a/internal/console/billingretire.go b/internal/console/billingretire.go| index e22ae4985..ce5d86159 100644 |
| --- a/internal/console/billingretire.go |
| +++ b/internal/console/billingretire.go |
| @@ -225,7 +225,11 @@ func (s *Server) retireForDeletion(w http.ResponseWriter, r *http.Request, addr, |
| ctx := s.billingClock(r.Context()) |
| fresh := s.store.FreshStepUp(raw, addr, time.Now(), StepUpWindow) |
| now := time.Now() |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + refuse(err) |
| + return nil, false |
| + } |
| // A replay needs the mark its first run set, whatever its proof's age: |
| // checked under the hold before anything else, so a replay whose proof |
| // expired on the way never marks the account again or asks for another |
| @@ -264,15 +268,19 @@ func (s *Server) retireForDeletion(w http.ResponseWriter, r *http.Request, addr, |
| if !fresh { |
| if !suspended { |
| // Nothing is pending: the account must not stay retiring. |
| - h, release = s.holdBilling(acct.Sqid) |
| - s.endRetirement(acct) |
| - release() |
| + if _, rel, err := s.holdBilling(acct); err == nil { |
| + s.endRetirement(acct) |
| + rel() |
| + } |
| } |
| return nil, false |
| } |
| // A proof that became fresh meanwhile: the mark this request set must |
| // still hold, as for a replay. |
| - h, release = s.holdBilling(acct.Sqid) |
| + if h, release, err = s.holdBilling(acct); err != nil { |
| + refuse(err) |
| + return nil, false |
| + } |
| if err := s.retireLocked(h, ctx, acct, addr, true, time.Now()); err != nil { |
| release() |
| refuse(err) |
diff --git a/internal/console/billingseats.go b/internal/console/billingseats.go| index 5e00acc53..78cb46aab 100644 |
| --- a/internal/console/billingseats.go |
| +++ b/internal/console/billingseats.go |
| @@ -133,10 +133,10 @@ func (s *Store) PutSeatObservation(accountID int64, driftAt time.Time, driftMemb |
| // billingTeam is the account's team block when billing is configured and the |
| // account's plan row is a team plan billing owns, else nil: only such an |
| -// account's membership is billed. |
| +// account's membership is billed. The exempt account's never is. |
| func (s *Server) billingTeam(acct *Account) (*plans.Team, error) { |
| cat := s.cfg.PlanCatalog |
| - if s.billing == nil || cat == nil { |
| + if s.billing == nil || cat == nil || s.store.planExempt(acct.ID) { |
| return nil, nil |
| } |
| row, err := s.store.AccountPlan(acct.ID) |
| @@ -240,7 +240,10 @@ func (s *Server) admitMember(ctx context.Context, acct *Account, token, addr str |
| return admitJoined, nil |
| } |
| ctx = s.billingClock(ctx) |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return admitRefused, err |
| + } |
| defer release() |
| return s.admitSeatLocked(h, ctx, acct, token, now, join) |
| } |
| @@ -594,7 +597,10 @@ func (s *Server) observeSeats(accountID int64, now time.Time) { |
| if err != nil || acct == nil { |
| return |
| } |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return // the exempt account: billing ignores it |
| + } |
| defer release() |
| members, err := s.store.MemberCount(acct.ID) |
| if err == nil { |
| @@ -702,11 +708,7 @@ func (s *Server) renderInviteConfirm(w http.ResponseWriter, r *http.Request, add |
| // the member lock and the hold, the plan item is reduced to the members |
| // billed (reconcileSeatsLocked); the flash is the reduction's outcome. |
| func (s *Server) handleBillingSeats(w http.ResponseWriter, r *http.Request) { |
| - if s.billing == nil { |
| - http.NotFound(w, r) |
| - return |
| - } |
| - _, raw, acct, ok := s.owner(w, r) |
| + _, raw, acct, ok := s.billingOwner(w, r) |
| if !ok { |
| return |
| } |
| @@ -723,7 +725,12 @@ func (s *Server) handleBillingSeats(w http.ResponseWriter, r *http.Request) { |
| ctx := s.billingClock(r.Context()) |
| now := time.Now() |
| unlock := s.lockMembers(acct.Sqid) |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + unlock() |
| + s.holdRefused(w, r, acct, err) |
| + return |
| + } |
| members, err := s.store.MemberCount(acct.ID) |
| var out opOutcome |
| if err == nil { |
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go| index 51fe29544..1d14d8c65 100644 |
| --- a/internal/console/billingstore.go |
| +++ b/internal/console/billingstore.go |
| @@ -493,13 +493,19 @@ func scanBillingProblem(sc interface{ Scan(...any) error }) (*billingProblem, er |
| // OpenBillingProblem opens a problem unless one is already open for the |
| // same account, subscription and reason, and reports whether it opened one. |
| func (s *Store) OpenBillingProblem(accountID int64, subscription, reason, detail string, now time.Time) (bool, error) { |
| - return openBillingProblemTx(s.db, accountID, subscription, reason, detail, now) |
| + return s.openBillingProblemTx(s.db, accountID, subscription, reason, detail, now) |
| } |
| // openBillingProblemTx is OpenBillingProblem's statement on a store handle or |
| // a transaction, so a problem opens in the same transaction as the state it |
| -// reports (a flagged restore check, plans 6b). |
| -func openBillingProblemTx(e sqlExecer, accountID int64, subscription, reason, detail string, now time.Time) (bool, error) { |
| +// reports (a flagged restore check, plans 6b). It is the one place a billing |
| +// problem opens, so the one place the exempt ops account (planExempt) is |
| +// refused one: for it nothing opens and the answer is (false, nil), from a |
| +// webhook path outside the billing hold as from anywhere else. |
| +func (s *Store) openBillingProblemTx(e sqlExecer, accountID int64, subscription, reason, detail string, now time.Time) (bool, error) { |
| + if s.planExempt(accountID) { |
| + return false, nil |
| + } |
| res, err := e.Exec(`INSERT INTO billing_problems (account_id, subscription, reason, detail, opened_at) |
| VALUES (?, ?, ?, ?, ?) ON CONFLICT(account_id, subscription, reason) WHERE closed_at = 0 DO NOTHING`, |
| accountID, subscription, reason, detail, now.Unix()) |
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go| index 0bbbf007b..a48103c89 100644 |
| --- a/internal/console/billingsync.go |
| +++ b/internal/console/billingsync.go |
| @@ -209,7 +209,11 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no |
| log.Printf("console: billing: subscription %s belongs to deleted account %d; nothing changed", subscriptionID, bound.AccountID) |
| return nil |
| } |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + log.Printf("console: billing: subscription %s belongs to %s, which billing never governs; nothing changed", subscriptionID, acct.Sqid) |
| + return nil |
| + } |
| defer release() |
| return s.syncSubscriptionLocked(h, ctx, acct, subscriptionID, now) |
| } |
diff --git a/internal/console/claim_invariant_world_test.go b/internal/console/claim_invariant_world_test.go| index e53dc5f6a..e55416c83 100644 |
| --- a/internal/console/claim_invariant_world_test.go |
| +++ b/internal/console/claim_invariant_world_test.go |
| @@ -608,6 +608,9 @@ func newClaimCaseWith(t *testing.T, opts ...func(*Config)) *claimCase { |
| secretsPriv: secretsPriv, vars: map[string]string{}, appIDs: map[claimAppRef]string{}, |
| hits: hits, |
| } |
| + // The world's account is ops, which plans exempt; its plan and billing |
| + // probes need it governed. |
| + governOps(cx.consoleFixture) |
| cx.enroll(t, release.OpsAccount, "kass") |
| cx.enroll(t, release.OpsAccount, "titogo") |
| cx.browser = newBrowser(t) |
diff --git a/internal/console/ownership.go b/internal/console/ownership.go| index 4d71e6a78..5d1675b9b 100644 |
| --- a/internal/console/ownership.go |
| +++ b/internal/console/ownership.go |
| @@ -82,7 +82,10 @@ func (s *Server) removalSeats(ctx context.Context, acct *Account, now time.Time) |
| return |
| } |
| ctx = s.billingClock(ctx) |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return |
| + } |
| defer release() |
| members, err := s.store.MemberCount(acct.ID) |
| if err == nil { |
diff --git a/internal/console/perfwrites_test.go b/internal/console/perfwrites_test.go| index fc706b6f8..2f188699b 100644 |
| --- a/internal/console/perfwrites_test.go |
| +++ b/internal/console/perfwrites_test.go |
| @@ -69,6 +69,7 @@ func newPerfWritesFx(t *testing.T) perfWritesFx { |
| if err != nil || acct == nil { |
| t.Fatalf("account %s: %v", fx.sqid, err) |
| } |
| + governOps(fx) // the fixture account is ops, which plans exempt |
| applyPlan(t, fx, acct, "free", nil, &plans.Limits{RunningThings: 10000, SidecarsPerApp: 10}, now) |
| codes := []string{"ie", "uk", "us"} |
| for i := perfFlagshipInstances; i < perfWritesInstances; i++ { |
diff --git a/internal/console/plancaps.go b/internal/console/plancaps.go| index 2324afbfe..3a76cedfb 100644 |
| --- a/internal/console/plancaps.go |
| +++ b/internal/console/plancaps.go |
| @@ -161,6 +161,7 @@ func (s *Server) checkSidecars(ctx context.Context, acct *Account, app string) e |
| // checkNewFreeAccount refuses a person a further account on a free plan once |
| // they own the catalog's allowance of them (spec §8.1; creation only). |
| +// Owning the exempt account (planExempt) is not owning a free one. |
| func (s *Server) checkNewFreeAccount(addr string) error { |
| cat := s.cfg.PlanCatalog |
| if cat == nil || cat.FreeAccountsPerPerson <= 0 { |
| @@ -175,7 +176,7 @@ func (s *Server) checkNewFreeAccount(addr string) error { |
| } |
| free := 0 |
| for _, a := range accts { |
| - if a.Role != RoleOwner { |
| + if a.Role != RoleOwner || s.store.planExempt(a.ID) { |
| continue |
| } |
| plan := cat.DefaultPlan |
diff --git a/internal/console/plancaps_doors_test.go b/internal/console/plancaps_doors_test.go| index b94632859..e78bdeff8 100644 |
| --- a/internal/console/plancaps_doors_test.go |
| +++ b/internal/console/plancaps_doors_test.go |
| @@ -25,6 +25,7 @@ import ( |
| func atRunningCap(t *testing.T, fx *consoleFixture, capN int) *Account { |
| t.Helper() |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, err := fx.st.AccountBySqid(fx.sqid) |
| if err != nil || acct == nil { |
| t.Fatalf("ops account: %v", err) |
| @@ -205,6 +206,7 @@ func TestSidecarCreateRefusedAtTheSidecarCap(t *testing.T) { |
| fx, token := instanceFixture(t, "code-cap-sidecar") |
| enableSidecars(t, fx, "titogo", titoSidecarManifest()) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, _ := fx.st.AccountBySqid("bab") |
| capsSidecar(t, fx, acct, "titogo", "first") |
| status, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx, "bab", "titogo"), token, `{"name":"bot","region":"ie"}`) |
| @@ -242,9 +244,15 @@ func accountCount(t *testing.T, fx *consoleFixture) int { |
| func TestNewAccountRefusedForASecondFreeAccount(t *testing.T) { |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| - before := accountCount(t, fx) |
| token := cliToken(t, fx, "paul@keymail.dev", "code-cap-acct") |
| - status, out := postJSON(t, fx.ts.URL+"/auth/cli/accounts", map[string]string{"name": "second"}, token) |
| + // Paul owns ops, which is exempt from plans (2026-10-28): his first |
| + // free account is allowed beside it. |
| + status, out := postJSON(t, fx.ts.URL+"/auth/cli/accounts", map[string]string{"name": "first"}, token) |
| + if status != http.StatusOK { |
| + t.Fatalf("CLI first free account beside ops = %d %v, want 200", status, out) |
| + } |
| + before := accountCount(t, fx) |
| + status, out = postJSON(t, fx.ts.URL+"/auth/cli/accounts", map[string]string{"name": "second"}, token) |
| if status != http.StatusConflict || out["code"] != "cap" { |
| t.Fatalf("CLI second free account = %d %v, want 409 cap", status, out) |
| } |
| @@ -271,6 +279,7 @@ func TestFirstAccountIsNeverRefused(t *testing.T) { |
| func TestNewAccountAllowedWhenTheOtherIsPaid(t *testing.T) { |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| ops, _ := fx.st.AccountBySqid(fx.sqid) |
| if _, err := fx.st.SetAccountPlan(ops.ID, "personal", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil { |
| t.Fatal(err) |
| @@ -294,6 +303,7 @@ func TestNewAccountWithoutACatalogUnchanged(t *testing.T) { |
| func TestFleetCreateRefusedOnAPlanWithoutFleets(t *testing.T) { |
| fx, token := fleetFixture(t, "code-cap-fleet") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| status, out := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "acme", "bucket": "bkt-1"}, token) |
| if status != http.StatusConflict || out["code"] != "cap" { |
| t.Fatalf("fleet create on free = %d %v, want 409 cap", status, out) |
| @@ -305,6 +315,7 @@ func TestCustomDomainRefusedOnAFreePlan(t *testing.T) { |
| shipVersion(t, fx, "titogo", "v1") |
| seedChannel(t, fx, "titogo", "canary/live", "v1") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| for name, body := range map[string]string{ |
| "alias": `{"host":"tickets.example.com","route":"go.tito.io"}`, |
| "first route": `{"host":"fresh.example.com","kind":"static"}`, |
| @@ -401,6 +412,7 @@ func daemonFixture(t *testing.T, code string) (*consoleFixture, string) { |
| func TestShipRefusesDaemonUnderAPlan(t *testing.T) { |
| fx, token := daemonFixture(t, "code-cap-daemon") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| status, out := shipDaemon(t, fx, token, "dmn00001") |
| if status != http.StatusConflict || out["code"] != "cap" { |
| t.Fatalf("daemon ship under a plan = %d %v, want 409 cap", status, out) |
| @@ -416,6 +428,7 @@ func TestShipRefusesDaemonEvenOnReship(t *testing.T) { |
| t.Fatalf("setup ship with no catalog = %d %v", status, out) |
| } |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| if status, out := shipDaemon(t, fx, token, "dmn00002"); status != http.StatusConflict || out["code"] != "cap" { |
| t.Fatalf("identical daemon re-ship under a plan = %d %v, want 409 cap", status, out) |
| } |
| @@ -451,6 +464,7 @@ func TestSidecarEnableRefusesHibernateFalseUnderAPlan(t *testing.T) { |
| fx, token := instanceFixture(t, "code-cap-alwayson") |
| enableSidecars(t, fx, "titogo", titoSidecarManifest()) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| status, _, out := rawReq(t, http.MethodPut, sidecarEnableURL(fx, "bab", "titogo"), token, `{"hibernate":false}`) |
| if status != http.StatusConflict || !strings.Contains(out, `"code":"cap"`) { |
| t.Fatalf("hibernate:false under a plan = %d %s, want 409 cap", status, out) |
| @@ -492,6 +506,7 @@ func setSchedule(t *testing.T, fx *consoleFixture, token, body string) int { |
| func TestScheduleRefusedBelowThePlanMinimum(t *testing.T) { |
| fx, token := scheduleFixture(t, "code-cap-schedule") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| for _, body := range []string{ |
| `{"name":"often","every":"5m","path":"/jobs/x"}`, |
| `{"name":"often","cron":"*/1 * * * *","path":"/jobs/x"}`, |
| @@ -570,6 +585,7 @@ func placeOnNamedFleet(t *testing.T, fx *consoleFixture, app, name string) { |
| func TestOwnBoxesNeedsAFleetTheAccountOwns(t *testing.T) { |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, _ := fx.st.AccountBySqid(fx.sqid) |
| addFleet(t, fx, "mine", fx.sqid) |
| addFleet(t, fx, "theirs", "zzz") |
| @@ -634,6 +650,7 @@ func TestSidecarCreateRefusedUnderAnAlwaysOnManifest(t *testing.T) { |
| m.Hibernate = &off |
| enableSidecars(t, fx, "titogo", m) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| status, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx, "bab", "titogo"), token, `{"name":"bot","region":"ie"}`) |
| if status != http.StatusConflict || !strings.Contains(out, `"code":"cap"`) { |
| t.Fatalf("new worker under an always-on manifest on shared boxes = %d %s, want 409 cap", status, out) |
| @@ -649,6 +666,7 @@ func TestAlwaysOnRefusedWhileSidecarsRemainOnSharedBoxes(t *testing.T) { |
| t.Fatalf("setup sidecar on shared boxes = %d %s", status, out) |
| } |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| placeOnFleet(t, fx, "titogo") |
| status, _, out := rawReq(t, http.MethodPut, sidecarEnableURL(fx, "bab", "titogo"), token, `{"hibernate":false}`) |
| if status != http.StatusConflict || !strings.Contains(out, `"code":"cap"`) { |
| @@ -664,6 +682,7 @@ func TestPromoteRefusesADaemonReleaseUnderAPlan(t *testing.T) { |
| t.Fatalf("setup daemon ship with no catalog = %d %v", status, out) |
| } |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/bab/relayapp/promote", |
| map[string]string{"version": "dmn00020", "channel": "canary/x"}, token) |
| if status != http.StatusConflict || out["code"] != "cap" { |
| @@ -696,6 +715,7 @@ func TestBrowserPromoteAndCanaryRefuseADaemonReleaseUnderAPlan(t *testing.T) { |
| fx := newConsoleFixture(t) |
| shipDaemonVersion(t, fx, "kass", "dmn1") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| c := signInPaul(t, fx) |
| csrf := sessionToken(t, fx, c) |
| @@ -735,6 +755,7 @@ func TestPendingPromoteOfADaemonReleaseRefusedUnderAPlan(t *testing.T) { |
| t.Fatalf("pending = %v, %v, want exactly one", pending, err) |
| } |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| kim := newBrowser(t) |
| fx.setUser("kim@keymail.dev") |
| @@ -755,6 +776,7 @@ func TestAlwaysOnRefusedPastAnUnreadableSidecarRecord(t *testing.T) { |
| t.Fatal(err) |
| } |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| placeOnFleet(t, fx, "titogo") |
| status, _, out := rawReq(t, http.MethodPut, sidecarEnableURL(fx, "bab", "titogo"), token, `{"hibernate":false}`) |
| if status == http.StatusOK || status == http.StatusNoContent { |
| @@ -783,6 +805,7 @@ func TestRollbackToADaemonReleaseRefusedUnderAPlan(t *testing.T) { |
| fx := newConsoleFixture(t) |
| daemonInHistory(t, fx, "kass") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| token := cliToken(t, fx, "paul@keymail.dev", "code-cap-daemon-rollback") |
| status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/bab/kass/rollback", map[string]string{"channel": "canary/x"}, token) |
| @@ -814,6 +837,7 @@ func TestRollbackDaemonGuardReadsThePointerAtWriteTime(t *testing.T) { |
| t.Fatalf("guard with plans off = %v, %v, want none", guard != nil, err) |
| } |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| guard, err := fx.srv.rollbackDaemonGuard(ctx, acct, "kass", "canary/x") |
| if err != nil || guard == nil { |
| t.Fatalf("guard under a plan = %v, %v, want one", guard != nil, err) |
| @@ -847,6 +871,7 @@ func TestPendingRollbackToADaemonReleaseRefusedUnderAPlan(t *testing.T) { |
| t.Fatalf("pending = %v, %v, want exactly one", pending, err) |
| } |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| kim := newBrowser(t) |
| fx.setUser("kim@keymail.dev") |
| signUp(t, fx, kim, "code-kim-daemon-rollback") |
| @@ -888,6 +913,7 @@ func TestRollbackGuardReadFailureIsAPlanCheckFailure(t *testing.T) { |
| seedChannel(t, fx, "kass", "canary/x", "old1") |
| seedChannel(t, fx, "kass", "canary/x", "new2") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| if err := fx.rel.Delete(context.Background(), release.ManifestKey(release.OpsAccount, "kass", "old1")); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/planexempt.go b/internal/console/planexempt.go| new file mode 100644 |
| index 000000000..42c2db509 |
| --- /dev/null |
| +++ b/internal/console/planexempt.go |
| @@ -0,0 +1,105 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +// The ops account is exempt from plans (Paul, 2026-10-28). Account #1 is |
| +// the deployment operator's built-in account: it runs the console and the |
| +// platform's own apps, and its owners are the operators. It has no plan: |
| +// |
| +// - no limits: the console never writes its limits record, and a box |
| +// reads an account with no record as having no limits (internal/host's |
| +// plansPass), the same as a deployment with plans off; |
| +// - no caps, warnings, grace, after-grace stages, throttle or lapse; |
| +// - owning it is not owning a free account; |
| +// - no billing: the billing page says there is nothing to buy; every |
| +// billing door refuses it at its entry (billingOwner), and no billing |
| +// hold can be had for it (holdBilling), so no door, pass, webhook sync |
| +// or invite acts on its billing state; |
| +// - the operator plan door refuses it. |
| +// |
| +// An account_plans row it already holds (dev's sponsored row) is ignored, |
| +// never migrated or deleted. Every path above asks planExempt |
| +// (TestPlanExemptConsulted). |
| + |
| +// planExempt reports whether plans never govern the account: the built-in |
| +// ops account (Store.planExemptID, always OpsAccountID). |
| +func (s *Store) planExempt(accountID int64) bool { return accountID == s.planExemptID } |
| + |
| +// errPlanExempt refuses a plan change for the exempt account. |
| +var errPlanExempt = errors.New("console: " + planCopyExempt) |
| + |
| +// errBillingExempt refuses a billing door for the exempt account. |
| +var errBillingExempt = billingRefusal{Key: "notice.exempt"} |
| + |
| +// settlePlanExempt is the one place that clears what a plan left on the |
| +// exempt account before it was exempt. It runs once per console start, |
| +// from the first limits pass, and is done only when both steps succeeded; |
| +// a failure leaves it not done, and the next pass retries. Each step |
| +// changes nothing when its state is absent: |
| +// |
| +// - the limits record (plans 2; accounts/<sqid>/limits.json), which is |
| +// how the plan's limits, the 4c throttle and the 4d turned-off hosts |
| +// reach the boxes: deleted, so boxes read no limits, no throttle and |
| +// nothing turned off; |
| +// - cap rows (4a, plan_cap_state), behind warning emails, banners and CLI |
| +// warning headers: deleted. |
| +// |
| +// Nothing else is cleared (Paul's cut, discussion 455): no storage deny, |
| +// plan mail pause or lapse item can exist on ops on any deployment. The |
| +// flagship never had a plan catalog, and dev's ops was sponsored a minute |
| +// after plans went on there, days before the storage, email or lapse |
| +// stages could act. The exemption stops new ones: EffectiveLimits is nil |
| +// for ops, so no grace pass measures it. |
| +// |
| +// The account's plan row (its throttle, lapse mark and turned-off column) |
| +// is left as it is: nothing reads it for ops, and it is never published. |
| +func (s *Server) settlePlanExempt(ctx context.Context, now time.Time) { |
| + if s.planExemptSettled.Load() { |
| + return |
| + } |
| + acct, err := s.store.AccountByID(s.store.planExemptID) |
| + if err != nil { |
| + log.Printf("console: plan limits: exempt account: %v", err) |
| + jobFailed(ctx, fmt.Errorf("plan limits: exempt account: %w", err)) |
| + return |
| + } |
| + if acct == nil { |
| + s.planExemptSettled.Store(true) |
| + return |
| + } |
| + defer s.lapseLock(acct.ID)() |
| + if err := s.clearPlanState(ctx, acct); err != nil { |
| + log.Printf("console: plan limits: exempt account %s: %v", acct.Sqid, err) |
| + jobFailed(ctx, fmt.Errorf("plan limits: exempt account %s: %w", acct.Sqid, err)) |
| + return |
| + } |
| + s.planExemptSettled.Store(true) |
| +} |
| + |
| +// clearPlanState is settlePlanExempt's two steps. Both run whatever the |
| +// other did, and every error comes back. |
| +func (s *Server) clearPlanState(ctx context.Context, acct *Account) error { |
| + var errs []error |
| + if err := s.cfg.Releases.Delete(ctx, plans.LimitsKey(acct.Sqid)); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + errs = append(errs, fmt.Errorf("limits record: %w", err)) |
| + } |
| + states, err := s.store.CapStates(acct.ID) |
| + if err != nil { |
| + errs = append(errs, fmt.Errorf("cap rows: %w", err)) |
| + } |
| + for _, st := range states { |
| + if err := s.store.DeleteCapState(acct.ID, st.Cap); err != nil { |
| + errs = append(errs, fmt.Errorf("cap row %s: %w", st.Cap, err)) |
| + } |
| + } |
| + return errors.Join(errs...) |
| +} |
diff --git a/internal/console/planexempt_test.go b/internal/console/planexempt_test.go| new file mode 100644 |
| index 000000000..3e692fcab |
| --- /dev/null |
| +++ b/internal/console/planexempt_test.go |
| @@ -0,0 +1,714 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "go/ast" |
| + "go/token" |
| + "net/http" |
| + "net/url" |
| + "slices" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The ops account is exempt from plans (Paul, 2026-10-28): no limits |
| +// record, no caps, no grace, lapse or throttle, no billing, and owning it |
| +// is not owning a free account. planExempt is the one predicate. |
| + |
| +// governOps puts the fixture's own account, which is ops, under plans, for |
| +// the tests that exercise plans through the fixture's account and doors. |
| +func governOps(fx *consoleFixture) { fx.st.planExemptID = 0 } |
| + |
| +// opsPlanAccount is the built-in ops account, created when the fixture's |
| +// store does not have it yet, owned by owner. |
| +func opsPlanAccount(t *testing.T, fx *consoleFixture, owner string) *Account { |
| + t.Helper() |
| + acct, err := fx.st.AccountByID(OpsAccountID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if acct == nil { |
| + if err := fx.st.CreateAccount(OpsAccountID, opsSqid, "ops", owner, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + } else if err := fx.st.AddMember(OpsAccountID, owner, RoleOwner, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if acct, err = fx.st.AccountByID(OpsAccountID); err != nil || acct == nil { |
| + t.Fatalf("ops account: %v", err) |
| + } |
| + return acct |
| +} |
| + |
| +// opsSponsoredRow gives ops the kind of row dev holds today: a sponsored |
| +// free assignment, published, with a throttle and a lapse mark. |
| +func opsSponsoredRow(t *testing.T, fx *consoleFixture, ops *Account) *AccountPlanRow { |
| + t.Helper() |
| + if _, err := fx.st.SetAccountPlan(ops.ID, "free", nil, 0, PlanSourceSponsored, &plans.Limits{RunningThings: 1}, "rehearsal", "paul@example.com", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.db.Exec(`UPDATE account_plans SET lapse_since = ?, throttle = '{"bandwidth":true,"until":"2099-01-01T00:00:00Z"}' WHERE account_id = ?`, planNow.Unix(), ops.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err := fx.st.AccountPlan(ops.ID) |
| + if err != nil || row == nil { |
| + t.Fatalf("ops row: %v", err) |
| + } |
| + return row |
| +} |
| + |
| +func TestPlanExemptIsTheOpsAccountAlone(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + if !fx.st.planExempt(OpsAccountID) { |
| + t.Fatal("ops is not exempt") |
| + } |
| + for _, id := range []int64{0, 2, 501} { |
| + if fx.st.planExempt(id) { |
| + t.Fatalf("account %d is exempt", id) |
| + } |
| + } |
| +} |
| + |
| +func TestPlanExemptLimitsPassWritesNoRecordAndRemovesAnOldOne(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + ops := opsPlanAccount(t, fx, "paul@example.com") |
| + other := planAccount(t, fx, 501) |
| + |
| + // A fresh deployment: no row for ops, no record. |
| + fx.srv.planLimitsPass(context.Background(), planNow) |
| + if row, _ := fx.st.AccountPlan(ops.ID); row != nil { |
| + t.Fatalf("the default pass gave ops a row: %+v", row) |
| + } |
| + if r, _ := readLimits(t, fx, ops.Sqid); r != nil { |
| + t.Fatalf("ops has a limits record: %+v", r) |
| + } |
| + if r, _ := readLimits(t, fx, other.Sqid); r == nil { |
| + t.Fatal("another account's record was not published") |
| + } |
| + |
| + // Dev today: a row and a record written before the exemption. The |
| + // record goes once per console start; the row is left as it is. |
| + row := opsSponsoredRow(t, fx, ops) |
| + old := &plans.Record{Account: ops.Sqid, CatalogID: fx.srv.cfg.PlanCatalog.ID(), Plan: "free", Source: PlanSourceSponsored, |
| + Revision: row.Revision, Limits: plans.Limits{RunningThings: 1, IdleSeconds: 60}, IssuedAt: planNow, |
| + Throttle: &plans.Throttle{Awake: true}, Disabled: []string{"shop.example.com"}} |
| + if _, err := plans.PutLimits(context.Background(), fx.rel, old, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.planExemptSettled.Store(false) // a console start |
| + fx.srv.planLimitsPass(context.Background(), planNow) |
| + if r, _ := readLimits(t, fx, ops.Sqid); r != nil { |
| + t.Fatalf("the old ops record is still there: %+v", r) |
| + } |
| + after, _ := fx.st.AccountPlan(ops.ID) |
| + if after == nil || after.Revision != row.Revision || after.Source != row.Source || after.Plan != row.Plan || |
| + after.PublishedRevision != row.PublishedRevision || after.Throttle == nil || after.LapseSince.IsZero() { |
| + t.Fatalf("the ops row changed: %+v, was %+v", after, row) |
| + } |
| + |
| + // A later pass, or a publish asked for directly, writes nothing back. |
| + fx.srv.planLimitsPass(context.Background(), planNow) |
| + if err := fx.srv.publishAccountLimits(context.Background(), *after, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r, _ := readLimits(t, fx, ops.Sqid); r != nil { |
| + t.Fatalf("ops record written back: %+v", r) |
| + } |
| +} |
| + |
| +func TestPlanExemptHasNoLimitsOrCaps(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + ops := opsPlanAccount(t, fx, "paul@example.com") |
| + opsSponsoredRow(t, fx, ops) |
| + for i := range 5 { |
| + capsApp(t, fx, ops, "app"+string(rune('a'+i))) |
| + } |
| + capsSidecar(t, fx, ops, "appa", "w1") |
| + capsSidecar(t, fx, ops, "appa", "w2") |
| + if l, err := fx.srv.EffectiveLimits(ops); err != nil || l != nil { |
| + t.Fatalf("ops limits = %+v, %v; want none", l, err) |
| + } |
| + for i := range 6 { |
| + if err := fx.st.AddMember(ops.ID, "crew"+string(rune('a'+i))+"@example.com", RoleMember, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + ctx := context.Background() |
| + for name, err := range map[string]error{ |
| + "running things": fx.srv.checkRunningThings(ctx, ops, 1), |
| + "restore": fx.srv.checkRestore(ctx, ops, "appa"), |
| + "sidecars": fx.srv.checkSidecars(ctx, ops, "appa"), |
| + "fleets": fx.srv.checkFleets(ops), |
| + "custom domains": fx.srv.checkCustomDomains(ops), |
| + "daemon": fx.srv.checkDaemon(ops, "appa"), |
| + "always on": fx.srv.checkAlwaysOnCreate(ops, "appa"), |
| + "members": fx.srv.checkMemberCap(ops, 10), |
| + } { |
| + if err != nil { |
| + t.Errorf("%s for ops: %v", name, err) |
| + } |
| + } |
| +} |
| + |
| +func TestPlanExemptOwnershipIsNotAFreeAccount(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + owner := "paul@example.com" |
| + ops := opsPlanAccount(t, fx, owner) |
| + if err := fx.srv.checkNewFreeAccount(owner); err != nil { |
| + t.Fatalf("owning ops alone counted as a free account: %v", err) |
| + } |
| + opsSponsoredRow(t, fx, ops) |
| + if err := fx.srv.checkNewFreeAccount(owner); err != nil { |
| + t.Fatalf("owning ops with a free row counted as a free account: %v", err) |
| + } |
| + // The cap itself still holds for the person's real accounts. |
| + if err := fx.st.CreateAccount(502, "bac", "mine", owner, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.srv.checkNewFreeAccount(owner); !isCap(err) { |
| + t.Fatalf("owner of ops and one free account: %v, want the cap", err) |
| + } |
| +} |
| + |
| +func TestPlanExemptHasNoGraceLapseOrWarnings(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + ops := opsPlanAccount(t, fx, "paul@example.com") |
| + row := opsSponsoredRow(t, fx, ops) |
| + for i := range 5 { |
| + capsApp(t, fx, ops, "app"+string(rune('a'+i))) |
| + } |
| + if err := fx.st.PutCapState(capState{AccountID: ops.ID, Cap: capRunningThings, Level: levelOver, Used: 5, Limit: 1, |
| + FirstOver: planNow, GraceEnds: planNow, UpdatedAt: planNow}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if fx.st.lapseEligible(row) { |
| + t.Fatal("ops's row is on the lapse path") |
| + } |
| + if lines, seen := fx.srv.planBanner(ops, RoleOwner, planNow); len(lines) != 0 || len(seen) != 0 { |
| + t.Fatalf("ops banner = %v", lines) |
| + } |
| + fx.srv.planGracePass(context.Background(), planNow) |
| + after, _ := fx.st.AccountPlan(ops.ID) |
| + if after.Revision != row.Revision || after.Throttle == nil || after.Disabled != nil { |
| + t.Fatalf("the grace pass touched the ops row: %+v", after) |
| + } |
| + states, _ := fx.st.CapStates(ops.ID) |
| + for _, st := range states { |
| + if st.UpdatedAt.After(planNow) || st.Cap != capRunningThings { |
| + t.Fatalf("the grace pass measured ops: %+v", st) |
| + } |
| + } |
| +} |
| + |
| +func TestPlanExemptPlanDoorRefuses(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + ops := opsPlanAccount(t, fx, "paul@example.com") |
| + token := planOperatorToken(t, fx, "ops@keymail.dev", "code-plan-exempt") |
| + status, out := getJSON(t, accountPlanURL(fx, ops.Sqid), token) |
| + if status != http.StatusConflict || out["error"] != planCopyExempt { |
| + t.Fatalf("GET ops plan = %d %v, want 409 %q", status, out, planCopyExempt) |
| + } |
| + status, out = postJSON(t, accountPlanURL(fx, ops.Sqid), map[string]any{"plan": "personal", "reason": "r"}, token) |
| + if status != http.StatusConflict || out["error"] != planCopyExempt { |
| + t.Fatalf("POST ops plan = %d %v, want 409 %q", status, out, planCopyExempt) |
| + } |
| + if row, _ := fx.st.AccountPlan(ops.ID); row != nil { |
| + t.Fatalf("refused POST wrote %+v", row) |
| + } |
| + if err := fx.srv.applyAccountPlan(context.Background(), ops, "personal", nil, 0, PlanSourceOperator, nil, "r", "x", planNow); err == nil { |
| + t.Fatal("a plan transition wrote ops's plan") |
| + } |
| + if row, _ := fx.st.AccountPlan(ops.ID); row != nil { |
| + t.Fatalf("a plan transition wrote %+v", row) |
| + } |
| + // Membership changes still work, and touch no plan row. |
| + if err := fx.srv.membershipTransition(context.Background(), ops, planNow, func(*sql.Tx) error { return nil }); err != nil { |
| + t.Fatalf("ops membership change: %v", err) |
| + } |
| + for _, s := range []string{planCopyExempt, billingCopy["notice.exempt"]} { |
| + if strings.Contains(s, "—") { |
| + t.Errorf("%q has an em dash", s) |
| + } |
| + } |
| + if planCopyExempt != strings.ToLower(planCopyExempt) || strings.HasSuffix(planCopyExempt, ".") { |
| + t.Errorf("door string %q is not lower case without a final full stop", planCopyExempt) |
| + } |
| +} |
| + |
| +func TestPlanExemptHasNoBilling(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.srv.billing.ready.Store(true) |
| + ops := opsPlanAccount(t, bf.consoleFixture, "paul@example.com") |
| + |
| + // The page: nothing to buy, whatever the row says. |
| + for _, row := range []*AccountPlanRow{nil, {Plan: "free", Source: PlanSourceDefault}, {Plan: "free", Source: PlanSourceSponsored}} { |
| + for _, owner := range []bool{true, false} { |
| + in := billingPageInput{Ready: true, Owner: owner, Exempt: true, Row: row} |
| + if st := decideBillingPage(in); st.Notice != "notice.exempt" || len(st.Offered) != 0 || st.OwnersOnly { |
| + t.Fatalf("exempt page (owner %v, row %+v) = %+v", owner, row, st) |
| + } |
| + } |
| + } |
| + in, err := bf.srv.billingPageInputFor(ops, RoleOwner, billingNow) |
| + if err != nil || !in.Exempt { |
| + t.Fatalf("ops page input = %+v, %v", in, err) |
| + } |
| + if in, _ := bf.srv.billingPageInputFor(bf.acct, RoleOwner, billingNow); in.Exempt { |
| + t.Fatal("another account's page is exempt") |
| + } |
| + |
| + // The doors: Checkout, change, renewal, seats, portal. |
| + c := signInPaul(t, bf.consoleFixture) |
| + csrf := sessionToken(t, bf.consoleFixture, c) |
| + for _, door := range []string{"checkout", "change", "renewal", "seats", "portal", "confirm"} { |
| + status, loc, _ := postForm(t, c, bf.ts.URL+"/a/"+ops.Sqid+"/billing/"+door, |
| + url.Values{"csrf": {csrf}, "plan": {"personal"}, "currency": {"usd"}, "renewal": {"stop"}}) |
| + if status != http.StatusSeeOther || loc != billingPagePath(ops.Sqid) { |
| + t.Errorf("%s for ops = %d -> %q, want the billing page", door, status, loc) |
| + } |
| + } |
| + if team, err := bf.srv.billingTeam(ops); err != nil || team != nil { |
| + t.Fatalf("ops billing team = %+v, %v", team, err) |
| + } |
| + bf.fake.Lock() |
| + sent := bf.fake.Calls |
| + bf.fake.Unlock() |
| + if sent != 0 { |
| + t.Fatalf("the provider got %d requests for ops", sent) |
| + } |
| +} |
| + |
| +// ---- the guard ---------------------------------------------------------------- |
| + |
| +// planExemptSites are the functions that decide plans or billing for one |
| +// account and must ask planExempt themselves. |
| +var planExemptSites = []string{ |
| + // Limits (req 1). |
| + "EnsureDefaultPlans", "publishAccountLimits", "EffectiveLimits", |
| + // Caps and lifecycle (req 2). |
| + "checkMemberCap", "lapseEligible", "planBanner", "writePlanWarnings", |
| + "transitionAccountPlan", "membershipTransition", |
| + // Free accounts (req 3). |
| + "checkNewFreeAccount", |
| + // Billing (req 4). |
| + "billingPageInputFor", |
| + "billingTeam", "handleUpgrade", "billingOwner", "holdBilling", |
| + "openBillingProblemTx", "handleAPIBillingHouse", |
| + // The plan door (req 5). |
| + "accountPlanDoor", |
| +} |
| + |
| +// asksPlanExempt is whether fd's body names planExempt or the store's |
| +// planExemptID. |
| +func asksPlanExempt(fd *ast.FuncDecl) bool { |
| + found := false |
| + ast.Inspect(fd, func(n ast.Node) bool { |
| + if id, ok := n.(*ast.Ident); ok && (id.Name == "planExempt" || id.Name == "planExemptID") { |
| + found = true |
| + } |
| + return !found |
| + }) |
| + return found |
| +} |
| + |
| +// callsAny is whether fd calls a function or method named one of names. |
| +func callsAny(fd *ast.FuncDecl, names ...string) bool { |
| + found := false |
| + ast.Inspect(fd, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return !found |
| + } |
| + switch fn := call.Fun.(type) { |
| + case *ast.Ident: |
| + found = found || slices.Contains(names, fn.Name) |
| + case *ast.SelectorExpr: |
| + found = found || slices.Contains(names, fn.Sel.Name) |
| + } |
| + return !found |
| + }) |
| + return found |
| +} |
| + |
| +// buildsPlanCap is whether fd makes a planCapError. |
| +func buildsPlanCap(fd *ast.FuncDecl) bool { |
| + found := false |
| + ast.Inspect(fd, func(n ast.Node) bool { |
| + if cl, ok := n.(*ast.CompositeLit); ok { |
| + if id, ok := cl.Type.(*ast.Ident); ok && id.Name == "planCapError" { |
| + found = true |
| + } |
| + } |
| + return !found |
| + }) |
| + return found |
| +} |
| + |
| +// planExemptFindings: every named site asks planExempt; every function that |
| +// refuses with a plan cap or writes a limits record asks planExempt or |
| +// reads EffectiveLimits (which asks it). It answers the findings and the |
| +// sites it found. |
| +func planExemptFindings(files map[string]*ast.File, sites []string) (findings, found []string) { |
| + for _, f := range files { |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok || fd.Body == nil { |
| + continue |
| + } |
| + name := fd.Name.Name |
| + if slices.Contains(sites, name) { |
| + found = append(found, name) |
| + if !asksPlanExempt(fd) { |
| + findings = append(findings, name+" does not ask planExempt") |
| + } |
| + continue |
| + } |
| + if (buildsPlanCap(fd) || callsAny(fd, "PutLimits")) && !asksPlanExempt(fd) && !callsAny(fd, "EffectiveLimits") { |
| + findings = append(findings, name+" applies a plan without asking planExempt or EffectiveLimits") |
| + } |
| + } |
| + } |
| + sort.Strings(findings) |
| + return findings, found |
| +} |
| + |
| +// TestPlanExemptConsulted pins the one predicate (req 6): the limits, caps, |
| +// lifecycle, free-account, billing and door paths all ask it, and any new |
| +// cap refusal or limits write must too. |
| +func TestPlanExemptConsulted(t *testing.T) { |
| + _, files := parsePackageSources(t) |
| + findings, found := planExemptFindings(files, planExemptSites) |
| + for _, f := range findings { |
| + t.Error(f) |
| + } |
| + for _, name := range planExemptSites { |
| + if !slices.Contains(found, name) { |
| + t.Errorf("%s is gone; update planExemptSites", name) |
| + } |
| + } |
| + fset, _ := parsePackageSources(t) |
| + planted := parsePlanted(t, fset, "planted.go", ` |
| +func (s *Server) checkNewThing(acct *Account) error { return &planCapError{msg: "x"} } |
| +func (s *Server) publishSideways(ctx int) { plans.PutLimits(nil, nil, nil, "") } |
| +func (s *Server) checkCounted(acct *Account) error { s.EffectiveLimits(acct); return &planCapError{msg: "x"} } |
| +func (s *Server) EffectiveLimits(acct *Account) {} |
| +`) |
| + got, _ := planExemptFindings(planted, planExemptSites) |
| + want := []string{ |
| + "EffectiveLimits does not ask planExempt", |
| + "checkNewThing applies a plan without asking planExempt or EffectiveLimits", |
| + "publishSideways applies a plan without asking planExempt or EffectiveLimits", |
| + } |
| + if !slices.Equal(got, want) { |
| + t.Fatalf("planted findings = %q, want %q", got, want) |
| + } |
| +} |
| + |
| +// ---- settlement: the limits record and cap rows --------------------------- |
| + |
| +// failingDelete fails Delete of one key while fail is set. |
| +type failingDelete struct { |
| + release.Store |
| + key string |
| + fail *atomic.Bool |
| +} |
| + |
| +func (f failingDelete) Delete(ctx context.Context, key string) error { |
| + if key == f.key && f.fail.Load() { |
| + return errors.New("bucket unavailable") |
| + } |
| + return f.Store.Delete(ctx, key) |
| +} |
| + |
| +// TestPlanExemptSettleClearsLimitsAndCapRows: what a plan left on ops |
| +// before the exemption, its limits record (limits, throttle, turned-off |
| +// hosts) and its cap rows (warnings, banners), is gone after one limits |
| +// pass. A failed step leaves settlement not done, and the next pass |
| +// retries. The plan row stays. |
| +func TestPlanExemptSettleClearsLimitsAndCapRows(t *testing.T) { |
| + fail := &atomic.Bool{} |
| + fail.Store(true) |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, WrapReleases: func(rs release.Store) release.Store { |
| + return failingDelete{Store: rs, key: plans.LimitsKey(opsSqid), fail: fail} |
| + }}) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + ctx := context.Background() |
| + ops := opsPlanAccount(t, fx, "paul@example.com") |
| + rowBefore := opsSponsoredRow(t, fx, ops) |
| + if err := fx.st.PutCapState(capState{AccountID: ops.ID, Cap: capEmail, Level: levelOver, Used: 200, Limit: 50, |
| + Period: capPeriod(capEmail, planNow), FirstOver: planNow, GraceEnds: planNow, UpdatedAt: planNow}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := plans.PutLimits(ctx, fx.rel, &plans.Record{Account: ops.Sqid, CatalogID: "old", Plan: "free", |
| + Throttle: &plans.Throttle{Awake: true}, Disabled: []string{"blog.example.com"}}, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // The bucket refuses the delete: not done, the record is still there. |
| + fx.srv.planLimitsPass(ctx, planNow) |
| + if fx.srv.planExemptSettled.Load() { |
| + t.Fatal("settlement finished with the limits record left") |
| + } |
| + if r, _ := readLimits(t, fx, ops.Sqid); r == nil { |
| + t.Fatal("setup: the failing delete removed the record") |
| + } |
| + |
| + // The next pass retries and finishes. |
| + fail.Store(false) |
| + fx.srv.planLimitsPass(ctx, planNow.Add(time.Minute)) |
| + if !fx.srv.planExemptSettled.Load() { |
| + t.Fatal("settlement did not finish on the retry") |
| + } |
| + if r, _ := readLimits(t, fx, ops.Sqid); r != nil { |
| + t.Errorf("limits record left: %+v", r) |
| + } |
| + if states, _ := fx.st.CapStates(ops.ID); len(states) != 0 { |
| + t.Errorf("cap rows left: %+v", states) |
| + } |
| + if rowAfter, _ := fx.st.AccountPlan(ops.ID); rowAfter == nil || rowAfter.Revision != rowBefore.Revision { |
| + t.Errorf("the ops row changed: %+v, was %+v", rowAfter, rowBefore) |
| + } |
| + |
| + // Safe when nothing is left: a second settlement finishes. |
| + fx.srv.planExemptSettled.Store(false) |
| + fx.srv.planLimitsPass(ctx, planNow.Add(2*time.Minute)) |
| + if !fx.srv.planExemptSettled.Load() { |
| + t.Fatal("a settlement with nothing to clear did not finish") |
| + } |
| +} |
| + |
| +// ---- round 1: the billing entry --------------------------------------------- |
| + |
| +// opsBillingFixture is a billing fixture, ready, with Paul (ops's owner) |
| +// signed in, and the ops account. |
| +func opsBillingFixture(t *testing.T) (*billingFixture, *http.Client, string, *Account) { |
| + t.Helper() |
| + bf := newBillingFixture(t) |
| + bf.srv.billing.ready.Store(true) |
| + ops, err := bf.st.AccountByID(OpsAccountID) |
| + if err != nil || ops == nil { |
| + t.Fatalf("ops: %v", err) |
| + } |
| + c := signInPaul(t, bf.consoleFixture) |
| + return bf, c, sessionToken(t, bf.consoleFixture, c), ops |
| +} |
| + |
| +func providerCalls(bf *billingFixture) int { |
| + bf.fake.Lock() |
| + defer bf.fake.Unlock() |
| + return bf.fake.Calls |
| +} |
| + |
| +func TestPlanExemptConfirmSendsNoLeftCheckout(t *testing.T) { |
| + bf, c, csrf, ops := opsBillingFixture(t) |
| + // Left from before the exemption: a bound customer and a create sent |
| + // without an answer, which Confirm now would look for and resend. |
| + if err := bf.st.SetBillingCustomer(ops.ID, "cus_ops", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + ci := testIntent(ops.ID, "ci_ops") |
| + ci.CreatedAt, ci.FirstSentAt, ci.ExpiresAt = time.Now(), time.Now(), time.Now().Add(time.Hour) |
| + if err := bf.st.PutCheckoutIntent(ci); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, loc, _ := postForm(t, c, bf.ts.URL+"/a/"+ops.Sqid+"/billing/confirm", url.Values{"csrf": {csrf}}) |
| + if status != http.StatusSeeOther || loc != billingPagePath(ops.Sqid) { |
| + t.Fatalf("Confirm now for ops = %d -> %q, want the billing page", status, loc) |
| + } |
| + if n := providerCalls(bf); n != 0 { |
| + t.Fatalf("Confirm now for ops made %d provider requests", n) |
| + } |
| + if ci, _ := bf.st.CheckoutIntent(ops.ID); ci == nil || ci.State != intentCreating { |
| + t.Fatalf("the left intent was acted on: %+v", ci) |
| + } |
| +} |
| + |
| +func TestPlanExemptContinueRefuses(t *testing.T) { |
| + bf, c, _, ops := opsBillingFixture(t) |
| + ci := testIntent(ops.ID, "ci_ops") |
| + ci.State, ci.Session, ci.URL = intentOpen, "cs_ops", "https://checkout.example.test/c/cs_ops" |
| + ci.ExpiresAt = time.Now().Add(time.Hour) |
| + if err := bf.st.PutCheckoutIntent(ci); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, path := range []string{"/billing/continue", "/billing/done?session=cs_ops"} { |
| + status, loc, _ := get(t, c, bf.ts.URL+"/a/"+ops.Sqid+path) |
| + if status != http.StatusSeeOther || loc != billingPagePath(ops.Sqid) { |
| + t.Fatalf("%s for ops = %d -> %q, want the billing page", path, status, loc) |
| + } |
| + } |
| + if n := providerCalls(bf); n != 0 { |
| + t.Fatalf("Continue for ops made %d provider requests", n) |
| + } |
| +} |
| + |
| +// TestPlanExemptBillingHoldRefused: no billing hold can be had for ops, so |
| +// no billing work (a pass, a webhook sync, an invite's seat) reaches it. |
| +func TestPlanExemptBillingHoldRefused(t *testing.T) { |
| + bf, _, _, ops := opsBillingFixture(t) |
| + if _, release, err := bf.srv.holdBilling(ops); err != errBillingExempt { |
| + release() |
| + t.Fatalf("holdBilling(ops) = %v, want errBillingExempt", err) |
| + } |
| + h, release, err := bf.srv.holdBilling(bf.acct) |
| + defer release() |
| + if err != nil || h.sqid != bf.acct.Sqid { |
| + t.Fatalf("holdBilling(another) = %+v, %v", h, err) |
| + } |
| +} |
| + |
| +// billingDoorRoutes is every route registered under /a/{sqid}/billing/ in |
| +// server.go, with its handler's name. |
| +func billingDoorRoutes(t *testing.T, files map[string]*ast.File) map[string]string { |
| + t.Helper() |
| + out := map[string]string{} |
| + f := files["server.go"] |
| + if f == nil { |
| + t.Fatal("no server.go") |
| + } |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok || len(call.Args) != 2 { |
| + return true |
| + } |
| + sel, ok := call.Fun.(*ast.SelectorExpr) |
| + if !ok || sel.Sel.Name != "registerRoute" { |
| + return true |
| + } |
| + lit, ok := call.Args[0].(*ast.BasicLit) |
| + if !ok || lit.Kind != token.STRING { |
| + return true |
| + } |
| + pattern, err := strconv.Unquote(lit.Value) |
| + if err != nil || !strings.Contains(pattern, "/a/{sqid}/billing/") { |
| + return true |
| + } |
| + if h, ok := call.Args[1].(*ast.SelectorExpr); ok { |
| + out[pattern] = h.Sel.Name |
| + } |
| + return true |
| + }) |
| + return out |
| +} |
| + |
| +// TestBillingDoorsEnterThroughBillingOwner: every billing door resolves its |
| +// account through billingOwner, which refuses ops before anything else, |
| +// and never through owner or account directly. |
| +func TestBillingDoorsEnterThroughBillingOwner(t *testing.T) { |
| + _, files := parsePackageSources(t) |
| + routes := billingDoorRoutes(t, files) |
| + if len(routes) < 8 { |
| + t.Fatalf("found %d billing door routes, want at least 8: %v", len(routes), routes) |
| + } |
| + decls := map[string]*ast.FuncDecl{} |
| + for _, f := range files { |
| + for _, d := range f.Decls { |
| + if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil { |
| + decls[fd.Name.Name] = fd |
| + } |
| + } |
| + } |
| + for pattern, name := range routes { |
| + fd := decls[name] |
| + if fd == nil { |
| + t.Errorf("%s: handler %s not found", pattern, name) |
| + continue |
| + } |
| + if !callsAny(fd, "billingOwner") || callsAny(fd, "owner", "account") { |
| + t.Errorf("%s: %s does not enter through billingOwner alone", pattern, name) |
| + } |
| + } |
| + if fd := decls["billingOwner"]; fd == nil || !asksPlanExempt(fd) { |
| + t.Error("billingOwner does not ask planExempt") |
| + } |
| +} |
| + |
| +// ---- round 2: no billing problem and no house flag for ops ------------------- |
| + |
| +// TestPlanExemptOpensNoBillingProblem: the webhook's two problem paths that |
| +// run outside the billing hold (a subscription the provider no longer has, |
| +// and a customer bound to no account) open nothing for ops, and the store's |
| +// one problem-opening statement refuses it; other accounts still get theirs. |
| +func TestPlanExemptOpensNoBillingProblem(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + ctx := context.Background() |
| + ops, err := bf.st.AccountByID(OpsAccountID) |
| + if err != nil || ops == nil { |
| + t.Fatalf("ops: %v", err) |
| + } |
| + |
| + // Before the exemption: ops bought a plan, so its subscription is live. |
| + governOps(bf.consoleFixture) |
| + if err := bf.st.SetBillingCustomer(ops.ID, "cus_ops", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + live := testPersonalSub("sub_ops", "cus_ops", ops.Sqid, "active", nil) |
| + bf.put(live) |
| + if err := bf.srv.syncSubscription(ctx, "sub_ops", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if b, _ := bf.st.BillingAccount(ops.ID); b == nil || b.Subscription != "sub_ops" || !liveState(b.State) { |
| + t.Fatalf("setup: ops billing row = %+v", b) |
| + } |
| + |
| + // The exemption ships; the provider loses the subscription, and an |
| + // unbound customer's subscription names ops. |
| + bf.st.planExemptID = OpsAccountID |
| + bf.fake.Lock() |
| + delete(bf.fake.Subs, "sub_ops") |
| + bf.fake.Unlock() |
| + if err := bf.srv.syncSubscription(ctx, "sub_ops", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + stranger := testPersonalSub("sub_stranger", "cus_stranger", ops.Sqid, "active", nil) |
| + bf.put(stranger) |
| + if err := bf.srv.syncSubscription(ctx, "sub_stranger", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if opened, err := bf.st.OpenBillingProblem(ops.ID, "sub_x", problemOperationUnresolved, "x", billingNow); err != nil || opened { |
| + t.Fatalf("OpenBillingProblem(ops) = %v, %v", opened, err) |
| + } |
| + open, _ := bf.st.BillingProblems(false) |
| + for _, p := range open { |
| + if p.AccountID == ops.ID { |
| + t.Errorf("a problem was opened for ops: %+v", p) |
| + } |
| + } |
| + |
| + // Another account's problems still open. |
| + other := testPersonalSub("sub_other", "cus_other", bf.acct.Sqid, "active", nil) |
| + bf.put(other) |
| + if err := bf.srv.syncSubscription(ctx, "sub_other", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if reasons, _ := bf.st.OpenBillingProblemReasons(bf.acct.ID); !slices.Contains(reasons, problemUnknownCustomer) { |
| + t.Fatalf("another account's unknown-customer problem = %v", reasons) |
| + } |
| +} |
| + |
| +func TestPlanExemptHouseDoorRefuses(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-house-exempt") |
| + status, out := postJSON(t, billingHouseURL(bf.consoleFixture), map[string]any{"account": opsSqid, "on": true, "note": "ours"}, op) |
| + if status != http.StatusConflict || out["error"] != planCopyExempt { |
| + t.Fatalf("house for ops = %d %v, want 409 %q", status, out, planCopyExempt) |
| + } |
| + if house, err := bf.st.BillingHouse(OpsAccountID); err != nil || house { |
| + t.Fatalf("ops marked as a house account: %v %v", house, err) |
| + } |
| +} |
diff --git a/internal/console/plangrace_cli_test.go b/internal/console/plangrace_cli_test.go| index bcf98a152..c736aa1cd 100644 |
| --- a/internal/console/plangrace_cli_test.go |
| +++ b/internal/console/plangrace_cli_test.go |
| @@ -103,6 +103,7 @@ func TestCLIWarningOnAppScopedDoors(t *testing.T) { |
| func TestCLIWarningSaysStorageWritesDenied(t *testing.T) { |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, _ := fx.st.AccountBySqid(fx.sqid) |
| st := evaluateCap(nil, capStorage, 3_000_000_000, 1_000_000_000, time.Now().Add(-time.Hour)) |
| st.AccountID = acct.ID |
diff --git a/internal/console/plangrace_view_test.go b/internal/console/plangrace_view_test.go| index e0a928082..75118c7d5 100644 |
| --- a/internal/console/plangrace_view_test.go |
| +++ b/internal/console/plangrace_view_test.go |
| @@ -13,6 +13,7 @@ import ( |
| func overRow(t *testing.T, fx *consoleFixture) *Account { |
| t.Helper() |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, _ := fx.st.AccountBySqid(fx.sqid) |
| // The real clock: page views and CLI requests record notice at |
| // time.Now(), which must not fall before the first over. |
| @@ -93,6 +94,7 @@ func TestBannerNoticeOnlyWhenRendered(t *testing.T) { |
| func TestBannerSaysEmailPaused(t *testing.T) { |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, _ := fx.st.AccountBySqid(fx.sqid) |
| st := evaluateCap(nil, capEmail, 100, 50, time.Now()) // free: 50 a day, paused at 100 |
| st.AccountID = acct.ID |
| @@ -108,6 +110,7 @@ func TestBannerSaysEmailPaused(t *testing.T) { |
| func TestBannerSaysStorageWritesDenied(t *testing.T) { |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, _ := fx.st.AccountBySqid(fx.sqid) |
| st := evaluateCap(nil, capStorage, 3_000_000_000, 1_000_000_000, time.Now().Add(-time.Hour)) // 3x: the hard ceiling |
| st.AccountID = acct.ID |
| @@ -123,6 +126,7 @@ func TestBannerSaysStorageWritesDenied(t *testing.T) { |
| func TestBannerSaysBandwidthThrottled(t *testing.T) { |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, _ := fx.st.AccountBySqid(fx.sqid) |
| st := evaluateCap(nil, capBandwidth, 25_000_000_000, 10_737_418_240, time.Now()) // free: 10 GiB a month, 2x and over |
| st.AccountID = acct.ID |
| @@ -140,6 +144,7 @@ func TestBannerSaysBandwidthThrottled(t *testing.T) { |
| func lapsedOps(t *testing.T, fx *consoleFixture) (*Account, capState) { |
| t.Helper() |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, _ := fx.st.AccountBySqid(fx.sqid) |
| if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", time.Now()); err != nil { |
| t.Fatal(err) |
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go| index 11d958505..949ff2fe6 100644 |
| --- a/internal/console/plangracepass.go |
| +++ b/internal/console/plangracepass.go |
| @@ -98,7 +98,7 @@ func (s *Server) planGraceAccountLocked(ctx context.Context, acct *Account, now |
| measures, errs := s.measureCaps(ctx, acct, l, now) |
| // Plans 4d: an eligible account's leftovers. An inventory that cannot |
| // be read keeps both leftover rows and changes nothing turned off. |
| - eligible := lapseEligible(row) |
| + eligible := s.store.lapseEligible(row) |
| var inv *lapseInventory |
| if eligible { |
| var invErr error |
| @@ -345,7 +345,7 @@ func humanGB(b int64) string { |
| // the page is written (Astra plans-4a finding 3). A store error shows no |
| // banner and never fails the page. |
| func (s *Server) planBanner(acct *Account, role string, now time.Time) ([]string, []capState) { |
| - if s.cfg.PlanCatalog == nil { |
| + if s.cfg.PlanCatalog == nil || s.store.planExempt(acct.ID) { |
| return nil, nil |
| } |
| states, err := s.store.CapStates(acct.ID) |
| @@ -397,7 +397,7 @@ const ( |
| // header, and must earn no notice. A person who owns the account receiving |
| // a cap that is over is notice received (spec §6); a service is not. |
| func (s *Server) writePlanWarnings(w http.ResponseWriter, r *http.Request, p Principal, acct *Account) { |
| - if s.cfg.PlanCatalog == nil || r.Header.Get(planWarningsAccept) != "1" { |
| + if s.cfg.PlanCatalog == nil || s.store.planExempt(acct.ID) || r.Header.Get(planWarningsAccept) != "1" { |
| return |
| } |
| states, err := s.store.CapStates(acct.ID) |
diff --git a/internal/console/planlapse.go b/internal/console/planlapse.go| index 3ad466483..4523e3bc0 100644 |
| --- a/internal/console/planlapse.go |
| +++ b/internal/console/planlapse.go |
| @@ -12,9 +12,9 @@ import ( |
| // lapseEligible reports whether an account is on the lapse path (plans 4d): |
| // its limits fell from a paid assignment and it is not sponsored. Sponsored |
| -// accounts never are (spec §9.2). |
| -func lapseEligible(row *AccountPlanRow) bool { |
| - return row != nil && !row.LapseSince.IsZero() && !planRowSponsored(row) |
| +// accounts never are (spec §9.2), and nor is the exempt account. |
| +func (s *Store) lapseEligible(row *AccountPlanRow) bool { |
| + return row != nil && !s.planExempt(row.AccountID) && !row.LapseSince.IsZero() && !planRowSponsored(row) |
| } |
| func planRowSponsored(row *AccountPlanRow) bool { |
| @@ -176,6 +176,9 @@ func (s *Server) applyBillingPlan(ctx context.Context, acct *Account, next *bill |
| // once and the limits record is published best-effort. |
| func (s *Server) transitionAccountPlan(ctx context.Context, acct *Account, now time.Time, |
| write func(old *AccountPlanRow) (bool, error)) error { |
| + if s.store.planExempt(acct.ID) { |
| + return errPlanExempt // no plan change, operator's or billing's, reaches it |
| + } |
| defer s.lapseLock(acct.ID)() |
| old, err := s.store.AccountPlan(acct.ID) |
| if err != nil { |
| @@ -384,7 +387,7 @@ func lapseCapOf(kind string) capID { |
| func (s *Server) lapseStages(acct *Account) func(capState) string { |
| none := func(capState) string { return "" } |
| row, err := s.store.AccountPlan(acct.ID) |
| - if err != nil || !lapseEligible(row) { |
| + if err != nil || !s.store.lapseEligible(row) { |
| return none |
| } |
| items, err := s.store.LapseItems(acct.ID) |
diff --git a/internal/console/planlapse_keep.go b/internal/console/planlapse_keep.go| index 082e7a5f5..6bcba2153 100644 |
| --- a/internal/console/planlapse_keep.go |
| +++ b/internal/console/planlapse_keep.go |
| @@ -36,7 +36,7 @@ func (s *Server) planKeepOffered(acct *Account) bool { |
| return false |
| } |
| row, err := s.store.AccountPlan(acct.ID) |
| - if err != nil || !lapseEligible(row) { |
| + if err != nil || !s.store.lapseEligible(row) { |
| return false |
| } |
| states, err := s.store.CapStates(acct.ID) |
| @@ -72,7 +72,7 @@ func (s *Server) handlePlanKeep(w http.ResponseWriter, r *http.Request) { |
| view := &planKeepView{Title: planKeepCopy["keep.title"], Save: planKeepCopy["keep.save"]} |
| p.PlanKeep = view |
| row, err := s.store.AccountPlan(acct.ID) |
| - if err != nil || !lapseEligible(row) { |
| + if err != nil || !s.store.lapseEligible(row) { |
| if err != nil { |
| log.Printf("console: plan keep %s: %v", acct.Sqid, err) |
| } |
| @@ -186,7 +186,7 @@ func (s *Server) handlePlanKeepSave(w http.ResponseWriter, r *http.Request) { |
| http.Redirect(w, r, back, http.StatusSeeOther) |
| } |
| row, err := s.store.AccountPlan(acct.ID) |
| - if err != nil || !lapseEligible(row) { |
| + if err != nil || !s.store.lapseEligible(row) { |
| fail(planKeepCopy["keep.nothing"]) |
| return |
| } |
diff --git a/internal/console/planlapse_test.go b/internal/console/planlapse_test.go| index 41d405b5a..3b0e61ae8 100644 |
| --- a/internal/console/planlapse_test.go |
| +++ b/internal/console/planlapse_test.go |
| @@ -126,6 +126,8 @@ func TestApplyAccountPlanSponsoredIsNoLapse(t *testing.T) { |
| } |
| func TestLapseEligible(t *testing.T) { |
| + st := &Store{planExemptID: OpsAccountID} |
| + lapseEligible := st.lapseEligible |
| marked := &AccountPlanRow{Plan: "free", Source: PlanSourceOperator, LapseSince: planNow} |
| if !lapseEligible(marked) { |
| t.Fatal("a marked operator row is not eligible") |
diff --git a/internal/console/planlimits.go b/internal/console/planlimits.go| index 0e9a20ab7..3e5e61b44 100644 |
| --- a/internal/console/planlimits.go |
| +++ b/internal/console/planlimits.go |
| @@ -49,6 +49,7 @@ func (s *Server) planLimitsPass(ctx context.Context, now time.Time) { |
| jobFailed(ctx, fmt.Errorf("plan limits: default plans: %w", err)) |
| return |
| } |
| + s.settlePlanExempt(ctx, now) |
| // Page by account id: a row that cannot be published (an orphaned |
| // assignment) stays due, but never holds a later account back. |
| var after int64 |
| @@ -79,11 +80,16 @@ func (s *Server) planLimitsPass(ctx context.Context, now time.Time) { |
| // record. An assignment the catalog cannot price (a plan or pack it no |
| // longer has) writes nothing, so boxes keep the last good record. A record |
| // already at this revision or newer, under this catalog, is left alone. |
| +// The exempt account's row writes nothing and is not marked: it has no |
| +// record, which boxes read as no limits. |
| func (s *Server) publishAccountLimits(ctx context.Context, row AccountPlanRow, now time.Time) error { |
| cat := s.cfg.PlanCatalog |
| if cat == nil { |
| return errors.New("no plan catalog") |
| } |
| + if s.store.planExempt(row.AccountID) { |
| + return nil |
| + } |
| members, err := s.planMembers(&row, row.AccountID) |
| if err != nil { |
| return err |
| @@ -124,11 +130,12 @@ func (s *Server) publishAccountLimits(ctx context.Context, row AccountPlanRow, n |
| } |
| // EffectiveLimits is acct's limits under the configured catalog, or nil |
| -// when plans are off. An account with no row is on the default plan. A |
| -// team plan is limited at planMembers' count. |
| +// when plans are off or the account is exempt (planExempt). An account |
| +// with no row is on the default plan. A team plan is limited at |
| +// planMembers' count. |
| func (s *Server) EffectiveLimits(acct *Account) (*plans.Limits, error) { |
| cat := s.cfg.PlanCatalog |
| - if cat == nil { |
| + if cat == nil || s.store.planExempt(acct.ID) { |
| return nil, nil |
| } |
| row, err := s.store.AccountPlan(acct.ID) |
diff --git a/internal/console/planmail_test.go b/internal/console/planmail_test.go| index 9a774e97f..b79c59047 100644 |
| --- a/internal/console/planmail_test.go |
| +++ b/internal/console/planmail_test.go |
| @@ -42,6 +42,7 @@ func planMailFixture(t *testing.T) *consoleFixture { |
| fx := newConsoleFixture(t) |
| fx.srv.cfg.MailProvisioner = mail.NewMemProvisioner("1") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| addMailApp(t, fx, "blog") |
| addMailApp(t, fx, "shop") |
| return fx |
diff --git a/internal/console/planmembers.go b/internal/console/planmembers.go| index 38d00d09a..02310e4ce 100644 |
| --- a/internal/console/planmembers.go |
| +++ b/internal/console/planmembers.go |
| @@ -150,10 +150,11 @@ func (s *Store) MembershipTransition(accountID int64, cat *plans.Catalog, old *A |
| // (transitionAccountPlan), so a change that moves a team's limits |
| // re-converges the account and publishes its record at once (the limits |
| // pass retries a failed publication). Callers hold the account's member |
| -// lock. Without a catalog it is just the membership write. |
| +// lock. Without a catalog, or for the exempt account (planExempt), it is |
| +// just the membership write. |
| func (s *Server) membershipTransition(ctx context.Context, acct *Account, now time.Time, write func(tx *sql.Tx) error) error { |
| cat := s.cfg.PlanCatalog |
| - if cat == nil { |
| + if cat == nil || s.store.planExempt(acct.ID) { |
| _, err := s.store.MembershipTransition(acct.ID, nil, nil, write, now) |
| return err |
| } |
| @@ -164,11 +165,11 @@ func (s *Server) membershipTransition(ctx context.Context, acct *Account, now ti |
| // checkMemberCap refuses adding more people to an account whose plan caps |
| // its members (max_members, Call 14) when they would pass the cap. Team |
| -// plans, sponsored rows, plans with no cap and consoles with no catalog |
| -// pass. Callers hold the account's member lock. |
| +// plans, sponsored rows, plans with no cap, the exempt account and consoles |
| +// with no catalog pass. Callers hold the account's member lock. |
| func (s *Server) checkMemberCap(acct *Account, adding int) error { |
| cat := s.cfg.PlanCatalog |
| - if cat == nil { |
| + if cat == nil || s.store.planExempt(acct.ID) { |
| return nil |
| } |
| row, err := s.store.AccountPlan(acct.ID) |
diff --git a/internal/console/planmembers_test.go b/internal/console/planmembers_test.go| index 38899a1b7..25302ac2b 100644 |
| --- a/internal/console/planmembers_test.go |
| +++ b/internal/console/planmembers_test.go |
| @@ -149,6 +149,7 @@ func TestMembershipRiseReconvergesAndPublishes(t *testing.T) { |
| sam := newBrowser(t) |
| signUp(t, fx, sam, "code-sam") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct := opsAccount(t, fx) |
| fillMembers(t, fx, acct.ID, 10) |
| applyPlan(t, fx, acct, "community", nil, nil, planNow) |
| @@ -299,6 +300,7 @@ func TestConcurrentInvitesRespectCap(t *testing.T) { |
| owner := newBrowser(t) |
| signUp(t, fx, owner, "code-owner") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct := opsAccount(t, fx) |
| fillMembers(t, fx, acct.ID, 2) |
| applyPlan(t, fx, acct, "personal", nil, nil, planNow) |
| @@ -348,6 +350,7 @@ func TestConcurrentAcceptsRespectCap(t *testing.T) { |
| fx := newConsoleFixture(t) |
| browsers, tokens := acceptInvitees(t, fx, "kim@keymail.dev", "lee@keymail.dev") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct := opsAccount(t, fx) |
| fillMembers(t, fx, acct.ID, 2) |
| applyPlan(t, fx, acct, "personal", nil, nil, planNow) |
| @@ -426,6 +429,7 @@ func TestMemberCapAtInvite(t *testing.T) { |
| owner := newBrowser(t) |
| signUp(t, fx, owner, "code-owner") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct := opsAccount(t, fx) |
| fillMembers(t, fx, acct.ID, 2) |
| if _, err := fx.st.CreateInvite(acct.ID, "waiting@keymail.dev", "paul@keymail.dev", time.Now()); err != nil { |
| @@ -505,6 +509,7 @@ func TestMembershipRemoveDoorUnderLock(t *testing.T) { |
| owner := newBrowser(t) |
| signUp(t, fx, owner, "code-owner") |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct := opsAccount(t, fx) |
| fillMembers(t, fx, acct.ID, 11) |
| applyPlan(t, fx, acct, "community", nil, nil, planNow) |
diff --git a/internal/console/planstorage_test.go b/internal/console/planstorage_test.go| index 313098b86..73d02661a 100644 |
| --- a/internal/console/planstorage_test.go |
| +++ b/internal/console/planstorage_test.go |
| @@ -21,6 +21,7 @@ func deniedStoreFixture(t *testing.T, code string) (*consoleFixture, *objstore.M |
| fx, fake, token, _ := storeArmed(t, code) |
| grantStore(t, fx, token) |
| fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + governOps(fx) // the fixture account is ops |
| acct, _ := fx.st.AccountBySqid(fx.sqid) |
| return fx, fake, acct |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 004be63f5..97316bf34 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -975,7 +975,10 @@ type Server struct { |
| // lapseLocks serialises, per account, everything that changes what a |
| // lapse turns off (plans 4d, Astra finding 1): a plan change, the grace |
| // pass's convergence and a keep save. Account id to *sync.Mutex. |
| - lapseLocks sync.Map |
| + lapseLocks sync.Map |
| + // planExemptSettled is set once settlePlanExempt has cleared what plans |
| + // left on the exempt account in this process (planexempt.go). |
| + planExemptSettled atomic.Bool |
| claimLossPageMu sync.Mutex |
| claimLossPageDone chan struct{} |
| @@ -3225,7 +3228,11 @@ func (s *Server) createInviteLocked(ctx context.Context, acct *Account, addr, to |
| } |
| var auth *seatAuthorisation |
| if team != nil { |
| - h, release := s.holdBilling(acct.Sqid) |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + back("err", changeText(acct.Sqid, err)) |
| + return "", nil, false |
| + } |
| defer release() |
| q, a, err := s.inviteSeatLocked(h, s.billingClock(ctx), acct, n, to, addr, confirmed, time.Now()) |
| if err != nil { |
| @@ -3360,8 +3367,14 @@ func (s *Server) handleRevokeInvite(w http.ResponseWriter, r *http.Request) { |
| // With billing configured, under the billing hold too (Invariant 7): an |
| // invite whose seat operation is outstanding (sending, unresolved or |
| // pending) is not revoked until that settles. |
| - if s.billing != nil { |
| - _, release := s.holdBilling(acct.Sqid) |
| + // The exempt ops account gets no hold and has no seat operations to |
| + // wait for. |
| + if s.billing != nil && !s.store.planExempt(acct.ID) { |
| + _, release, herr := s.holdBilling(acct) |
| + if herr != nil { |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read the invitations.") |
| + return |
| + } |
| defer release() |
| op, err := s.store.LatestOpForInvite(tok) |
| if err != nil { |
diff --git a/internal/console/store.go b/internal/console/store.go| index 3764cc2d7..c6643a55d 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -56,6 +56,11 @@ type Store struct { |
| gate *claimGate |
| bound *claimBinding |
| + // planExemptID is the account plans never govern: always OpsAccountID |
| + // (planexempt.go). A field only so a test whose fixture account is ops |
| + // can put that account under a plan. |
| + planExemptID int64 |
| + |
| // mailEventsPruned is when mail_events was last trimmed to its |
| // retention window, as unix seconds (mailevents.go). Zero means not yet |
| // this process, which is what makes the first event after a restart |
| @@ -85,7 +90,8 @@ func newStore(db *sql.DB) *Store { |
| _, _ = rand.Read(key) |
| ep := make([]byte, 8) |
| _, _ = rand.Read(ep) |
| - return &Store{codeEpoch: hex.EncodeToString(ep), db: db, rawPool: db, rawBoot: db, mailEventsPruned: new(atomic.Int64), mailPushPruned: new(atomic.Int64), codeKey: key, names: &appNameLocks{}} |
| + return &Store{codeEpoch: hex.EncodeToString(ep), db: db, rawPool: db, rawBoot: db, mailEventsPruned: new(atomic.Int64), mailPushPruned: new(atomic.Int64), codeKey: key, names: &appNameLocks{}, |
| + planExemptID: OpsAccountID} |
| } |
| // Open opens (creating if needed) the console DB at path. |