carlos / platform Public

console: upgrades keep every still-paid pack; a problem found by the request's own read stops it; refusal copy in the map (plans 6b task 10 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 2cdfb74cf337c38bbfdd732a50257d58f6bce036 parent e5c1774
4 files changed, +145 −32
  • internal/console/billingchange.go +57 −11
  • internal/console/billingchange_test.go +82 −0
  • internal/console/billingpage_copy.go +3 −0
  • internal/console/billingseats.go +3 −21
diff --git a/internal/console/billingchange.go b/internal/console/billingchange.go
index 56cb7d3f1..16fea112b 100644
--- a/internal/console/billingchange.go
+++ b/internal/console/billingchange.go
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"log"
+ "maps"
"net/http"
"slices"
"strconv"
@@ -151,7 +152,7 @@ func (s *Server) handleBillingChange(w http.ResponseWriter, r *http.Request) {
return
}
if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
- s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
+ s.billingCSRFRefused(w, r)
return
}
back := billingPagePath(acct.Sqid)
@@ -180,6 +181,12 @@ func (s *Server) handleBillingChange(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, back, http.StatusSeeOther)
}
+// billingCSRFRefused answers a billing POST whose CSRF token is missing or
+// wrong: 403 with the copy map's refusal.
+func (s *Server) billingCSRFRefused(w http.ResponseWriter, r *http.Request) {
+ s.renderMessage(w, r, http.StatusForbidden, billingCopy["refused.title"], billingCopy["refused.csrf"])
+}
+
// renderChangeConfirm is the confirm page for a charge: the estimate, and a
// form posting the same change with confirmed=1.
func (s *Server) renderChangeConfirm(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, ask changeAsk, q changeQuote) {
@@ -218,10 +225,8 @@ func (s *Server) changeRefusalsLocked(h billingHold, acct *Account, now time.Tim
} else if retiring {
return errBillingRetiring
}
- if problems, err := s.store.OpenBillingProblemReasons(acct.ID); err != nil {
+ if err := s.refuseOnProblemLocked(h, acct); err != nil {
return err
- } else if len(problems) > 0 {
- return errCheckoutProblem
}
row, err := s.store.AccountPlan(acct.ID)
if err != nil {
@@ -233,6 +238,25 @@ func (s *Server) changeRefusalsLocked(h billingHold, acct *Account, now time.Tim
return nil
}
+// refuseOnProblemLocked refuses (notice.problem) while the account has an
+// open billing problem: a local read, no provider request. A request checks
+// it before it starts and again after its own fresh reads (finishing an
+// operation, the allowance or refresh), which can open a problem without
+// failing (restore_after_renewal, an unrecognised read, a second
+// subscription), and before preparing anything to send: a problem found by
+// the request's own read stops it.
+func (s *Server) refuseOnProblemLocked(h billingHold, acct *Account) error {
+ _ = h
+ problems, err := s.store.OpenBillingProblemReasons(acct.ID)
+ if err != nil {
+ return err
+ }
+ if len(problems) > 0 {
+ return errCheckoutProblem
+ }
+ return nil
+}
+
// finishOutstandingLocked finishes the operation outstanding on the
// account's recorded subscription, if any: one left sending or unresolved
// gets finishOpLocked (a read, and at most one resend of its stored bytes); a
@@ -275,8 +299,13 @@ func (s *Server) changeLocked(h billingHold, ctx context.Context, acct *Account,
if err != nil {
return changeReply{}, err
}
+ // The reads above can open a problem without failing: it stops the
+ // request before anything is prepared.
+ if err := s.refuseOnProblemLocked(h, acct); err != nil {
+ return changeReply{}, err
+ }
if ask.Plan != "" {
- return s.upgradeLocked(h, ctx, acct, sub, purchase, ask, now)
+ return s.upgradeLocked(h, ctx, acct, b, sub, purchase, ask, now)
}
return s.packChangeLocked(h, ctx, acct, b, sub, purchase, ask, now)
}
@@ -371,6 +400,10 @@ func (s *Server) packChangeLocked(h billingHold, ctx context.Context, acct *Acco
return changeFlash("err", "change.uncertain"), nil
}
item, has, start, sub = it, true, it.Quantity, rsub
+ if err := s.refuseOnProblemLocked(h, acct); err != nil {
+ s.settleChangeLocked(h, ctx, acct, out, now)
+ return changeReply{}, err
+ }
}
out, _, err := s.sendChangeLocked(h, ctx, acct, sub, opPack, []billing.ItemChange{lineTo(item, has, chargeTo)},
map[string]int64{price: chargeTo}, start, billing.ProrateNow, now)
@@ -382,15 +415,24 @@ func (s *Server) packChangeLocked(h billingHold, ctx context.Context, acct *Acco
// upgradeLocked is a plan upgrade (Call 4) on the fresh allowance read: one
// ProrateNow swap of the plan item's price, at the team's billed members or 1.
-func (s *Server) upgradeLocked(h billingHold, ctx context.Context, acct *Account, sub *billing.Subscription, purchase billing.Purchase, ask changeAsk, now time.Time) (changeReply, error) {
+func (s *Server) upgradeLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, sub *billing.Subscription, purchase billing.Purchase, ask changeAsk, now time.Time) (changeReply, error) {
cat, prices, book := s.cfg.PlanCatalog, s.billing.cfg.Prices, s.billing.cfg.Book
if ask.Plan == purchase.Plan {
return changeReply{}, errChangeNone
}
- // Higher in the configured book, and offering every pack held.
+ // Higher in the configured book, and offering every pack held: on the
+ // subscription now, or still paid for until renewal (a pack reduced to
+ // 0 keeps its paid quantity on the refreshed row).
+ held := maps.Clone(b.PaidPacks)
+ if held == nil {
+ held = map[string]int{}
+ }
+ for name, q := range purchase.Packs {
+ held[name] = max(held[name], q)
+ }
floor, okFrom := lowestTotal(cat, book, purchase.Plan, sub.Currency)
total, okTo := lowestTotal(cat, book, ask.Plan, sub.Currency)
- if !okFrom || !okTo || total <= floor || !offersAll(cat.Plans[ask.Plan], heldPacks(purchase.Packs)) {
+ if !okFrom || !okTo || total <= floor || !offersAll(cat.Plans[ask.Plan], heldPacks(held)) {
return changeReply{}, errChangeBook
}
// Priced from the subscription's own book.
@@ -503,7 +545,7 @@ func (s *Server) handleBillingRenewal(w http.ResponseWriter, r *http.Request) {
return
}
if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
- s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
+ s.billingCSRFRefused(w, r)
return
}
back := billingPagePath(acct.Sqid)
@@ -535,8 +577,9 @@ func renewalText(renew bool, periodEnd time.Time) changeReply {
// renewalLocked is stopping (renew false) or resuming renewal under the
// hold: refused while retiring; an outstanding operation is finished first;
-// then a refresh, and one renewal operation unless the subscription is
-// already as asked; then the subscription is refreshed again.
+// then a refresh, refused if the account has an open problem by then, and
+// one renewal operation unless the subscription is already as asked; then the
+// subscription is refreshed again.
func (s *Server) renewalLocked(h billingHold, ctx context.Context, acct *Account, renew bool, now time.Time) (changeReply, error) {
if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil {
return changeReply{}, err
@@ -550,6 +593,9 @@ func (s *Server) renewalLocked(h billingHold, ctx context.Context, acct *Account
if err != nil {
return changeReply{}, err
}
+ if err := s.refuseOnProblemLocked(h, acct); err != nil {
+ return changeReply{}, err
+ }
if sub == nil || !sub.Live {
return changeReply{}, errChangeFailed
}
diff --git a/internal/console/billingchange_test.go b/internal/console/billingchange_test.go
index c8c063a49..4fa8a4db8 100644
--- a/internal/console/billingchange_test.go
+++ b/internal/console/billingchange_test.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"html"
+ "io"
"net/http"
"net/url"
"strings"
@@ -696,6 +697,26 @@ func TestUpgradeRefusedWhenPackNotOffered(t *testing.T) {
}
// A plan that offers it is fine.
o.wantFlash(t, o.change(t, "plan", "community", "confirmed", "1"), "ok", billingCopy["change.done"])
+
+ // A pack reduced to 0 is still paid for until renewal, so it is still
+ // held: the upgrade is refused with nothing sent.
+ o = newChangeFixture(t, map[string]int64{"email": 1})
+ cat = o.srv.cfg.PlanCatalog
+ business = cat.Plans["business"]
+ business.Packs = []string{"apps", "disk", "storage", "bandwidth"}
+ cat.Plans["business"] = business
+ o.wantFlash(t, o.change(t, "pack", "email", "quantity", "0"), "ok", billingCopy["change.done"])
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.PaidPacks["email"] != 1 {
+ t.Fatalf("billing row = %+v, want email still paid", b)
+ }
+ o.stepUp(t)
+ o.reset()
+ o.wantFlash(t, o.change(t, "plan", "business", "confirmed", "1"), "err", billingCopy["change.book"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ o.wantFlash(t, o.change(t, "plan", "business"), "err", billingCopy["change.book"])
+ if n := o.counts()["Send"]; n != 0 {
+ t.Fatalf("sends = %d, want 0", n)
+ }
}
// subscriptionsBookPrices is the example price map plus an earlier book,
@@ -859,6 +880,67 @@ func TestPackChangeRefusesOperatorPlanAndProblems(t *testing.T) {
wantCounts(t, o.counts(), map[string]int{})
}
+// TestChangeStopsOnAProblemItsOwnReadFinds: the request's own fresh read
+// (finishing a restore that applied after renewal) opens
+// restore_after_renewal, so nothing more is prepared or sent.
+func TestChangeStopsOnAProblemItsOwnReadFinds(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ do func(t *testing.T, o *opsFixture) billingReply
+ }{
+ {"change", func(t *testing.T, o *opsFixture) billingReply {
+ return o.change(t, "pack", "apps", "quantity", "4", "confirmed", "1")
+ }},
+ {"renewal", func(t *testing.T, o *opsFixture) billingReply { return o.renewal(t, "stop") }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ o := newRestoreFixture(t)
+ o.heldRestore(t, "op_1", "sub_1")
+ if err := o.fake.Renew("sub_1"); err != nil { // the renewal bills 1, then the held restore applies
+ t.Fatal(err)
+ }
+ if probs := o.openProblems(t); len(probs) != 0 {
+ t.Fatalf("problems before the request = %v", probs)
+ }
+ o.signInOwner(t)
+ o.stepUp(t)
+ o.reset()
+ o.wantFlash(t, c.do(t, o), "err", billingCopy["notice.problem"])
+ if got := o.openProblems(t); len(got) != 1 || got[0] != problemRestoreAfterRenewal {
+ t.Fatalf("problems = %v, want restore_after_renewal", got)
+ }
+ if n := o.counts()["Send"]; n != 0 {
+ t.Fatalf("sends = %d, want 0", n)
+ }
+ if all := o.ops(t); len(all) != 1 || all[0].ID != "op_1" {
+ t.Fatalf("ops = %+v, want only the restore", all)
+ }
+ })
+ }
+}
+
+// TestChangeCSRFRefusalCopy: the cross-site refusal's text is the copy map's.
+func TestChangeCSRFRefusalCopy(t *testing.T) {
+ if billingCopy["refused.csrf"] == "" || billingCopy["refused.title"] == "" {
+ t.Fatal("the cross-site refusal has no copy in billingCopy")
+ }
+ o := newChangeFixture(t, nil)
+ for _, path := range []string{"/change", "/renewal"} {
+ req, _ := http.NewRequest(http.MethodPost, o.ts.URL+o.billingBase()+path, strings.NewReader("renewal=stop"))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ resp, err := o.owner.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusForbidden || !strings.Contains(string(body), html.EscapeString(billingCopy["refused.csrf"])) ||
+ !strings.Contains(string(body), html.EscapeString(billingCopy["refused.title"])) {
+ t.Fatalf("%s without CSRF = %d %s", path, resp.StatusCode, body)
+ }
+ }
+}
+
// httpPostNoCSRF posts form as the owner without the CSRF field.
func httpPostNoCSRF(t *testing.T, o *opsFixture, path string, form url.Values) int {
t.Helper()
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index c2e287d46..86880a801 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -28,6 +28,9 @@ var billingCopy = map[string]string{
"change.near_renewal": "Your plan renews within a day. Try again after it renews; the pack will then be a normal purchase.",
"renewal.stopped": "Renewal stopped. Your plan ends on %s.",
"renewal.resumed": "Renewal is back on.",
+ // The billing doors' cross-site refusal.
+ "refused.title": "Refused",
+ "refused.csrf": "Cross-site request blocked.",
// Team seats (Task 11).
"seats.invite_line": "When %s joins, the account pays about %s now for the rest of the year, plus any tax.",
diff --git a/internal/console/billingseats.go b/internal/console/billingseats.go
index af707d87a..c76cf4f6f 100644
--- a/internal/console/billingseats.go
+++ b/internal/console/billingseats.go
@@ -153,24 +153,6 @@ func (s *Server) billingTeam(acct *Account) (*plans.Team, error) {
return p.Team, nil
}
-// seatProblemLocked is the controller's ruling for Task 11: a problem
-// discovered by the request's own reads stops it. It runs after the finish
-// and allowance reads and before any seat operation is prepared or any seat
-// authorisation recorded, refusing with notice.problem. (Task 10's fix round
-// adds the same check as refuseOnProblemLocked; the controller merges the
-// two.)
-func (s *Server) seatProblemLocked(h billingHold, acct *Account) error {
- _ = h
- problems, err := s.store.OpenBillingProblemReasons(acct.ID)
- if err != nil {
- return err
- }
- if len(problems) > 0 {
- return errCheckoutProblem
- }
- return nil
-}
-
// sendSeatOpLocked prepares one change of the plan item to qty, its
// proration timestamp the request's provider time, and sends it through
// sendOpLocked. invite is the join it is for ("" for a reduction) and
@@ -333,7 +315,7 @@ func (s *Server) admitSeatLocked(h billingHold, ctx context.Context, acct *Accou
return admitNearRenewal, nil
}
}
- if err := s.seatProblemLocked(h, acct); err != nil {
+ if err := s.refuseOnProblemLocked(h, acct); err != nil {
return admitOutstanding, err
}
@@ -518,7 +500,7 @@ func (s *Server) reconcileSeatsLocked(h billingHold, ctx context.Context, acct *
}
var out opOutcome
if want := int64(team.Billed(members)); item.Quantity > want {
- if err := s.seatProblemLocked(h, acct); err != nil {
+ if err := s.refuseOnProblemLocked(h, acct); err != nil {
return opOutcome{}, err
}
if out, _, err = s.sendSeatOpLocked(h, ctx, acct, sub, opSeat, item, want, billing.ProrateNone, "", "", now); err != nil {
@@ -604,7 +586,7 @@ func (s *Server) inviteSeatLocked(h billingHold, ctx context.Context, acct *Acco
if int64(team.Billed(members+pending+1)) <= max(item.Quantity, int64(b.PaidSeats)) {
return nil, nil, nil
}
- if err := s.seatProblemLocked(h, acct); err != nil {
+ if err := s.refuseOnProblemLocked(h, acct); err != nil {
return nil, nil, err
}
price, known := s.configuredPrice(purchase.Book, billing.KindPlan, purchase.Plan, sub.Currency)