plans: the ops exemption clears every plan-enforced state and is checked at the billing entry (ops-plan-exempt round 1)
Astra round 1 (NOT READY at e492e431), all three findings fixed, each
invariant enforced at one shared point:
1. Ops has no plan-enforced state. settlePlanExempt is the one place
that clears, once per console start, everything a plan stage left on
ops: the limits record (limits, 4c throttle, 4d turned-off hosts),
storage denies on every app including trashed ones, plan mail pauses
(PauseKindPlan only; manual, cap and rate pauses stay), cap rows
behind warnings and banners, and lapse items. Each step is
conditional; the plan row is left as it is.
2. No billing action reaches ops. holdBilling now takes the account and
refuses ops (errBillingExempt), so no door, pass, webhook sync, invite
seat or recovery can act on its billing state; the per-function
checks it replaces are gone. billingOwner is every billing door's
entry and refuses ops before any state or form is read;
TestBillingDoorsEnterThroughBillingOwner pins every route under
/a/{sqid}/billing/ to it.
Regressions: a plan-paused ops sender resumes; deny, trash, settle,
restore leaves uploads allowed; Confirm now with a left Checkout create
sends nothing; Continue and the return refuse.
docs/site/plans.md: "The ops account".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
19 files changed,
+552
−118
docs/site/plans.md+4 −0internal/console/apibilling.go+4 −1internal/console/billingchange.go+14 −20internal/console/billingcheckout.go+22 −22internal/console/billinghold.go+44 −5internal/console/billinglate.go+4 −1internal/console/billinglate_test.go+8 −1internal/console/billingops.go+6 −6internal/console/billingops_test.go+7 −1internal/console/billingpass.go+12 −3internal/console/billingportal.go+1 −10internal/console/billingretire.go+13 −5internal/console/billingseats.go+15 −11internal/console/billingsync.go+5 −1internal/console/ownership.go+4 −1internal/console/planexempt.go+111 −13internal/console/planexempt_test.go+257 −14internal/console/planstorage.go+8 −0internal/console/server.go+13 −3
diff --git a/docs/site/plans.md b/docs/site/plans.md| index 8654bd99b..d9f62526f 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. Turning plans on also undoes anything an earlier plan left on it. |
| + |
| ## 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/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/billingchange.go b/internal/console/billingchange.go| index 6af3fd4c1..b0e4f3151 100644 |
| --- a/internal/console/billingchange.go |
| +++ b/internal/console/billingchange.go |
| @@ -143,11 +143,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 |
| } |
| @@ -167,7 +163,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 { |
| @@ -216,13 +216,10 @@ func (s *Server) renderChangeConfirm(w http.ResponseWriter, r *http.Request, add |
| } |
| // changeRefusalsLocked are the refusals a change needs no provider request |
| -// for: the exempt account, a retiring account, an open billing problem, a |
| -// plan billing does not own. |
| +// for: a retiring account, an open billing problem, a plan billing does not |
| +// own. |
| func (s *Server) changeRefusalsLocked(h billingHold, acct *Account, now time.Time) error { |
| _ = h |
| - if s.store.planExempt(acct.ID) { |
| - return errBillingExempt |
| - } |
| if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil { |
| return err |
| } else if retiring { |
| @@ -541,11 +538,7 @@ func (s *Server) settleChangeLocked(h billingHold, ctx context.Context, acct *Ac |
| // 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 |
| } |
| @@ -562,7 +555,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 { |
| @@ -587,9 +584,6 @@ func renewalText(renew bool, periodEnd time.Time) changeReply { |
| // problem never refuses it: renewal prepares no charge or quantity raise |
| // (refuseOnProblemLocked is only for flows that can). |
| func (s *Server) renewalLocked(h billingHold, ctx context.Context, acct *Account, renew bool, now time.Time) (changeReply, error) { |
| - if s.store.planExempt(acct.ID) { |
| - return changeReply{}, errBillingExempt |
| - } |
| if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil { |
| return changeReply{}, err |
| } else if retiring { |
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go| index 611212fd5..9be8de759 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 { |
| @@ -195,9 +195,6 @@ func (s *Server) handleBillingCheckout(w http.ResponseWriter, r *http.Request) { |
| func (s *Server) checkoutLocked(h billingHold, ctx context.Context, acct *Account, ask checkoutAsk, now time.Time) (string, error) { |
| cfg := s.billing.cfg |
| // Refusals that need no provider request. |
| - if s.store.planExempt(acct.ID) { |
| - return "", errBillingExempt |
| - } |
| if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil { |
| return "", err |
| } else if retiring { |
| @@ -1015,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 |
| } |
| @@ -1031,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 { |
| @@ -1083,11 +1080,7 @@ func (s *Server) continueLocked(h billingHold, ctx context.Context, acct *Accoun |
| // observed (a completed session syncs its subscription), then the billing |
| // page, saying which plan the account is on when it is paid. |
| 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 |
| } |
| @@ -1098,7 +1091,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 { |
| @@ -1181,7 +1178,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..adaef288a 100644 |
| --- a/internal/console/billinglate.go |
| +++ b/internal/console/billinglate.go |
| @@ -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/billingpass.go b/internal/console/billingpass.go| index 8da4b401c..3023d30e8 100644 |
| --- a/internal/console/billingpass.go |
| +++ b/internal/console/billingpass.go |
| @@ -194,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) { |
| @@ -240,7 +243,10 @@ func (s *Server) observeOp(ctx context.Context, op billingOp, now time.Time, syn |
| 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 { |
| @@ -295,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 { |
diff --git a/internal/console/billingportal.go b/internal/console/billingportal.go| index c4d50ca87..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 |
| } |
| @@ -44,11 +40,6 @@ func (s *Server) handleBillingPortal(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| back := billingPagePath(acct.Sqid) |
| - if s.store.planExempt(acct.ID) { |
| - s.setFlash(w, "err", billingCopy["notice.exempt"]) |
| - http.Redirect(w, r, back, http.StatusSeeOther) |
| - return |
| - } |
| if !s.billing.ready.Load() { |
| s.setFlash(w, "err", billingCopy["portal.failed"]) |
| http.Redirect(w, r, back, http.StatusSeeOther) |
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 1150cd964..78cb46aab 100644 |
| --- a/internal/console/billingseats.go |
| +++ b/internal/console/billingseats.go |
| @@ -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) |
| } |
| @@ -531,9 +534,6 @@ func (s *Server) observeSeatsLocked(h billingHold, acct *Account, members int, d |
| // the refresh after it; then the seat observation. It answers the |
| // reduction's outcome, with a zero State when nothing was sent. |
| func (s *Server) reconcileSeatsLocked(h billingHold, ctx context.Context, acct *Account, members int, now time.Time) (opOutcome, error) { |
| - if s.store.planExempt(acct.ID) { |
| - return opOutcome{}, errBillingExempt |
| - } |
| if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil { |
| return opOutcome{}, err |
| } else if retiring { |
| @@ -597,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 { |
| @@ -705,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 |
| } |
| @@ -726,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/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/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/planexempt.go b/internal/console/planexempt.go| index 5d0baf15b..d1ee68175 100644 |
| --- a/internal/console/planexempt.go |
| +++ b/internal/console/planexempt.go |
| @@ -6,8 +6,10 @@ import ( |
| "fmt" |
| "log" |
| "os" |
| + "slices" |
| "time" |
| + "github.com/carlosframework/platform/internal/mail" |
| "github.com/carlosframework/platform/internal/plans" |
| ) |
| @@ -20,8 +22,10 @@ import ( |
| // 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: nothing to buy, and no Checkout, change, seat or portal |
| -// path starts for it; the billing passes skip it; |
| +// - 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, |
| @@ -38,11 +42,27 @@ var errPlanExempt = errors.New("console: " + planCopyExempt) |
| // errBillingExempt refuses a billing door for the exempt account. |
| var errBillingExempt = billingRefusal{Key: "notice.exempt"} |
| -// settlePlanExempt removes, once per console start, what plans left on the |
| -// exempt account from before it was exempt: its limits record, so the |
| -// boxes stop applying it, and a storage deny the grace pass set. It reads |
| -// and writes nothing of the account's plan row. A failure is retried on |
| -// the next limits pass. |
| +// settlePlanExempt is the one place that clears what plan stages put on |
| +// the exempt account before it was exempt. It runs once per console start, |
| +// from the first limits pass, and is done only when every step succeeded; |
| +// a failure is retried on the next pass. Each step is conditional, and |
| +// 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; |
| +// - storage denies (4b) on the stores of every app, live or trashed: |
| +// lifted, so a restored app takes uploads again; |
| +// - plan mail pauses (4b, mail.PauseKindPlan) on the senders of every |
| +// app, live or trashed: resumed. Manual, cap and rate pauses stay; |
| +// - cap rows (4a), behind warning emails, banners, CLI warning headers |
| +// and the after-grace stages: deleted; |
| +// - lapse items (4d), behind the turned-off list, its banners and the keep |
| +// page: deleted, for every app the account still has a row for. |
| +// |
| +// 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 |
| @@ -58,17 +78,95 @@ func (s *Server) settlePlanExempt(ctx context.Context, now time.Time) { |
| return |
| } |
| defer s.lapseLock(acct.ID)() |
| + if err := s.clearPlanState(ctx, acct, now); 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 steps, in its order. Every step runs |
| +// whatever the others did. |
| +func (s *Server) clearPlanState(ctx context.Context, acct *Account, now time.Time) 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)) |
| } |
| - if err := s.clearStorageDeny(ctx, acct, now); err != nil { |
| + apps, err := s.store.AppsIn(acct.ID) |
| + if err != nil { |
| + return errors.Join(append(errs, fmt.Errorf("apps: %w", err))...) |
| + } |
| + trashed, err := s.store.TrashedAppsIn(acct.ID) |
| + if err != nil { |
| + return errors.Join(append(errs, fmt.Errorf("trashed apps: %w", err))...) |
| + } |
| + for _, t := range trashed { |
| + apps = append(apps, t.App) |
| + } |
| + if err := s.convergeStoresOf(ctx, acct, apps, false, capState{}, now); err != nil { |
| errs = append(errs, fmt.Errorf("storage deny: %w", err)) |
| } |
| - if err := errors.Join(errs...); 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 |
| + if err := s.resumePlanPauses(ctx, acct, apps, now); err != nil { |
| + errs = append(errs, fmt.Errorf("mail: %w", err)) |
| } |
| - s.planExemptSettled.Store(true) |
| + 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)) |
| + } |
| + } |
| + items, err := s.store.LapseItems(acct.ID) |
| + if err != nil { |
| + errs = append(errs, fmt.Errorf("lapse items: %w", err)) |
| + } |
| + for _, it := range items { |
| + // An item of an app with no row at all cannot be admitted, and |
| + // with the record gone it turns nothing off. |
| + if !slices.Contains(apps, it.App) { |
| + continue |
| + } |
| + if err := s.store.DeleteLapseItem(ctx, acct.ID, it.App, it.Kind, it.Ref); err != nil { |
| + errs = append(errs, fmt.Errorf("lapse item %s %s: %w", it.Kind, it.Ref, err)) |
| + } |
| + } |
| + return errors.Join(errs...) |
| +} |
| + |
| +// resumePlanPauses resumes every sender of the apps that a plan paused |
| +// (mail.PauseKindPlan), whatever the day. The pause kind is asked again of |
| +// the sender as read inside the mutation, so a pause taken since (manual, |
| +// cap, rate) stays. |
| +func (s *Server) resumePlanPauses(ctx context.Context, acct *Account, apps []string, now time.Time) error { |
| + if s.cfg.MailProvisioner == nil { |
| + return nil |
| + } |
| + planPaused := func(sn *mail.Sender) bool { |
| + return sn != nil && sn.Provisioned != nil && !sn.Provisioned.Active && sn.Provisioned.PauseKind == mail.PauseKindPlan |
| + } |
| + var errs []error |
| + for _, app := range apps { |
| + senders, err := mail.ListSenders(ctx, s.cfg.Releases, acct.Sqid, app) |
| + if err != nil { |
| + errs = append(errs, fmt.Errorf("%s: %w", app, err)) |
| + continue |
| + } |
| + for _, sn := range senders { |
| + if !planPaused(sn) { |
| + continue |
| + } |
| + _, err := mail.SetSenderPausedIf(ctx, s.claimMailStore(), s.cfg.MailProvisioner, acct.Sqid, app, sn.ID, false, "", now, planPaused) |
| + switch { |
| + case errors.Is(err, mail.ErrNotEligible): |
| + case err != nil: |
| + errs = append(errs, fmt.Errorf("%s/%s: %w", app, sn.ID, err)) |
| + default: |
| + s.audit(acct, app, "ses", "mail.resumed", fmt.Sprintf("%s: plan pause lifted; this account is exempt from plans", mailAuditSubject(app, sn.ID))) |
| + } |
| + } |
| + } |
| + return errors.Join(errs...) |
| } |
diff --git a/internal/console/planexempt_test.go b/internal/console/planexempt_test.go| index e66ad0d76..f123f8cb9 100644 |
| --- a/internal/console/planexempt_test.go |
| +++ b/internal/console/planexempt_test.go |
| @@ -4,13 +4,19 @@ import ( |
| "context" |
| "database/sql" |
| "go/ast" |
| + "go/token" |
| "net/http" |
| + "net/url" |
| "slices" |
| "sort" |
| + "strconv" |
| "strings" |
| "testing" |
| + "time" |
| + "github.com/carlosframework/platform/internal/mail" |
| "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 |
| @@ -264,17 +270,14 @@ func TestPlanExemptHasNoBilling(t *testing.T) { |
| t.Fatal("another account's page is exempt") |
| } |
| - // The doors: Checkout, change, renewal, seats. |
| - ctx := bf.srv.billingClock(context.Background()) |
| - h, release := bf.srv.holdBilling(ops.Sqid) |
| - _, cerr := bf.srv.checkoutLocked(h, ctx, ops, checkoutAsk{Plan: "personal", Currency: "usd"}, billingNow) |
| - chErr := bf.srv.changeRefusalsLocked(h, ops, billingNow) |
| - _, rErr := bf.srv.renewalLocked(h, ctx, ops, false, billingNow) |
| - _, sErr := bf.srv.reconcileSeatsLocked(h, ctx, ops, 3, billingNow) |
| - release() |
| - for name, err := range map[string]error{"checkout": cerr, "change": chErr, "renewal": rErr, "seats": sErr} { |
| - if err != errBillingExempt { |
| - t.Errorf("%s for ops = %v, want errBillingExempt", name, err) |
| + // 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 { |
| @@ -301,9 +304,8 @@ var planExemptSites = []string{ |
| // Free accounts (req 3). |
| "checkNewFreeAccount", |
| // Billing (req 4). |
| - "billingPageInputFor", "checkoutLocked", "changeRefusalsLocked", "renewalLocked", |
| - "reconcileSeatsLocked", "billingTeam", "handleBillingPortal", "handleUpgrade", |
| - "billingSyncPass", "observeIntent", "observeOp", "billingRestorePass", "billingDiscoveryPass", |
| + "billingPageInputFor", |
| + "billingTeam", "handleUpgrade", "billingOwner", "holdBilling", |
| // The plan door (req 5). |
| "accountPlanDoor", |
| } |
| @@ -413,3 +415,244 @@ func (s *Server) EffectiveLimits(acct *Account) {} |
| t.Fatalf("planted findings = %q, want %q", got, want) |
| } |
| } |
| + |
| +// ---- round 1: settlement clears every plan-enforced state --------------------- |
| + |
| +// TestPlanExemptSettleClearsEveryPlanState: everything a plan stage put on |
| +// ops before the exemption is gone after one limits pass: the limits record |
| +// (with its throttle and turned-off hosts), a storage deny, even on an app |
| +// trashed since, a plan mail pause, cap rows behind warnings and banners, |
| +// and lapse items. Manual and cap mail pauses stay; the plan row stays. |
| +func TestPlanExemptSettleClearsEveryPlanState(t *testing.T) { |
| + fx, fake, ops := deniedStoreFixture(t, "code-plan-exempt-settle") // ops governed |
| + ctx := context.Background() |
| + fx.srv.cfg.MailProvisioner = mail.NewMemProvisioner("1") |
| + addMailApp(t, fx, "blog") |
| + addMailApp(t, fx, "shop") |
| + |
| + // Under a plan: a storage deny on titogo, a plan pause on every sender. |
| + st := storageRow(ops, 3_000_000_000, 1_000_000_000, planNow) |
| + if err := fx.srv.convergeStorageDeny(ctx, ops, st, true, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec := titogoStore(t, fx); rec.WritesDenied == nil || !hasWriteDeny(t, fake.PolicyFor(rec.Provisioned.IAMUser)) { |
| + t.Fatal("setup: no deny") |
| + } |
| + sends(t, fx, "blog", 200, planMailNow) |
| + if paused, err := fx.srv.enforceAccountMail(ctx, release.OpsAccount, planMailNow); err != nil || !paused { |
| + t.Fatalf("setup: plan pause = %v, %v", paused, err) |
| + } |
| + // shop's pause is an operator's (no kind): settlement keeps it. |
| + if _, err := mail.SetSenderPausedIf(ctx, fx.srv.claimMailStore(), fx.srv.cfg.MailProvisioner, release.OpsAccount, "shop", |
| + mail.SenderAppID, true, "", planMailNow, func(*mail.Sender) bool { return true }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if p := senderState(t, fx, "shop"); p.Active || p.PauseKind != "" { |
| + t.Fatalf("setup: shop = %+v, want a manual pause", p) |
| + } |
| + 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 := fx.st.PutLapseItem(ctx, lapseItem{AccountID: ops.ID, App: "blog", Kind: lapseApp, Ref: "blog", |
| + ThingCreated: planNow, DisabledAt: 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) |
| + } |
| + rowBefore := opsSponsoredRow(t, fx, ops) |
| + // titogo is trashed before the exemption ships. |
| + if err := fx.st.TrashAppRow(ops.ID, "titogo", planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // The exemption ships: one limits pass. |
| + fx.st.planExemptID = OpsAccountID |
| + fx.srv.planLimitsPass(ctx, planNow.Add(time.Minute)) |
| + if !fx.srv.planExemptSettled.Load() { |
| + t.Fatal("settlement did not finish") |
| + } |
| + |
| + if r, _ := readLimits(t, fx, ops.Sqid); r != nil { |
| + t.Errorf("limits record left: %+v", r) |
| + } |
| + if p := senderState(t, fx, "blog"); !p.Active { |
| + t.Errorf("blog's plan pause left: %+v", p) |
| + } |
| + if p := senderState(t, fx, "shop"); p.Active { |
| + t.Errorf("shop's manual pause was lifted: %+v", p) |
| + } |
| + if states, _ := fx.st.CapStates(ops.ID); len(states) != 0 { |
| + t.Errorf("cap rows left: %+v", states) |
| + } |
| + if items, _ := fx.st.LapseItems(ops.ID); len(items) != 0 { |
| + t.Errorf("lapse items left: %+v", items) |
| + } |
| + if err := fx.st.RestoreAppRow(ops.ID, "titogo"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec := titogoStore(t, fx); rec.WritesDenied != nil || hasWriteDeny(t, fake.PolicyFor(rec.Provisioned.IAMUser)) { |
| + t.Errorf("restored titogo still refuses uploads: %+v", rec.WritesDenied) |
| + } |
| + 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 changes nothing. |
| + 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") |
| + } |
| + if p := senderState(t, fx, "shop"); p.Active { |
| + t.Errorf("shop's manual pause was lifted on the second pass: %+v", p) |
| + } |
| +} |
| + |
| +// ---- 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") |
| + } |
| +} |
diff --git a/internal/console/planstorage.go b/internal/console/planstorage.go| index 3fb8dcf49..3a3454da4 100644 |
| --- a/internal/console/planstorage.go |
| +++ b/internal/console/planstorage.go |
| @@ -49,6 +49,14 @@ func (s *Server) convergeStores(ctx context.Context, acct *Account, want bool, s |
| if err != nil { |
| return err |
| } |
| + return s.convergeStoresOf(ctx, acct, apps, want, st, now) |
| +} |
| + |
| +// convergeStoresOf is convergeStores over the named apps. |
| +func (s *Server) convergeStoresOf(ctx context.Context, acct *Account, apps []string, want bool, st capState, now time.Time) error { |
| + if s.cfg.PlanCatalog == nil || s.cfg.StoreProvisioner == nil { |
| + return nil |
| + } |
| var errs []error |
| for _, app := range apps { |
| envs, err := objstore.StoreEnvironments(ctx, s.cfg.Releases, acct.Sqid, app) |
diff --git a/internal/console/server.go b/internal/console/server.go| index 9578cce68..4dbec8fac 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -3152,7 +3152,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 { |
| @@ -3287,8 +3291,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 { |