carlos / platform Public

console: seat consent needs a known price; a failed read never admits; refusal copy in the map (plans 6b task 11 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev f5f6b50fbc3185a01dd1e56e23d6a8d1c208a28d parent 0c6f998
2 files changed, +154 −29
  • internal/console/billingseats.go +36 −24
  • internal/console/billingseats_test.go +118 −5
diff --git a/internal/console/billingseats.go b/internal/console/billingseats.go
index c76cf4f6f..9d17861ba 100644
--- a/internal/console/billingseats.go
+++ b/internal/console/billingseats.go
@@ -95,24 +95,21 @@ func (s *Store) InviteSeatAuthorisation(token string) (*seatAuthorisation, error
}
// seatCovered is an authorisation that covers a new seat on the account's
-// subscription now: unconsumed, for the same plan, book and currency, at a
-// price not above what the owner agreed. The price is checked when the
-// console holds the authorised book; a book version never changes its
-// prices (ErrPriceBookEdited), so the same book is the same price.
+// subscription now: unconsumed, for the same plan, book and currency, with a
+// recorded price the console can verify (Calls 6 and 11): the authorised
+// book is the configured one, which prices the plan at no more than the
+// owner agreed. An authorisation with no recorded price, or on a book the
+// console does not hold, never covers a charge: an unverifiable ceiling is
+// no consent.
func seatCovered(a *seatAuthorisation, row *billingAccount, book *plans.PriceBook) bool {
- if a == nil || row == nil || !a.ConsumedAt.IsZero() {
+ if a == nil || row == nil || book == nil || !a.ConsumedAt.IsZero() || a.PriceMinor <= 0 {
return false
}
- if a.Plan != row.Plan || a.Book != row.Book || a.Currency != row.Currency {
+ if a.Plan != row.Plan || a.Book != row.Book || a.Currency != row.Currency || a.Book != book.Version {
return false
}
- if book != nil && book.Version == a.Book {
- price, ok := book.PlanPrice(a.Plan, a.Currency)
- if !ok || price > a.PriceMinor {
- return false
- }
- }
- return true
+ price, ok := book.PlanPrice(a.Plan, a.Currency)
+ return ok && price > 0 && price <= a.PriceMinor
}
// consumeSeatAuthorisationTx spends the invite's seat authorisation in the
@@ -273,7 +270,10 @@ func (s *Server) admitSeatLocked(h billingHold, ctx context.Context, acct *Accou
return admitRefused, errBillingRetiring
}
if out, err := s.finishSeatOpsLocked(h, ctx, acct, token, now); err != nil || out != admitJoined {
- return out, err
+ if err != nil {
+ return admitUncertain, err
+ }
+ return out, nil
}
b, sub, purchase, err := s.allowanceLocked(h, ctx, acct, now)
if err != nil {
@@ -355,15 +355,23 @@ func (s *Server) admitSeatLocked(h billingHold, ctx context.Context, acct *Accou
// finishSeatOpsLocked finishes the operation outstanding on the account's
// subscription, if any, and answers admitJoined when nothing is outstanding
-// afterwards (admission goes on), or the outcome that refuses it.
+// afterwards (admission goes on), or the outcome that refuses it. A failed
+// read is admitUncertain with its error, never admitJoined, which goes on
+// only after a clean read.
func (s *Server) finishSeatOpsLocked(h billingHold, ctx context.Context, acct *Account, token string, now time.Time) (admitOutcome, error) {
b, err := s.store.BillingAccount(acct.ID)
- if err != nil || b == nil || b.Subscription == "" {
- return admitJoined, err
+ if err != nil {
+ return admitUncertain, err
+ }
+ if b == nil || b.Subscription == "" {
+ return admitJoined, nil
}
op, err := s.store.OutstandingOp(b.Subscription)
- if err != nil || op == nil {
- return admitJoined, err
+ if err != nil {
+ return admitUncertain, err
+ }
+ if op == nil {
+ return admitJoined, nil
}
if op.State == opPending {
_, _, err = s.refreshLocked(h, ctx, acct, now)
@@ -589,13 +597,17 @@ func (s *Server) inviteSeatLocked(h billingHold, ctx context.Context, acct *Acco
if err := s.refuseOnProblemLocked(h, acct); err != nil {
return nil, nil, err
}
+ // Consent needs the per-seat price it agrees to (Calls 6 and 11). The
+ // console holds only the configured book's amounts, so a subscription on
+ // another book records none and the invite is refused (change.book).
price, known := s.configuredPrice(purchase.Book, billing.KindPlan, purchase.Plan, sub.Currency)
+ if !known || price <= 0 {
+ return nil, nil, errChangeBook
+ }
if !confirmed {
q := &seatQuote{To: to, Currency: sub.Currency}
- if known {
- if pnow, err := s.providerNow(ctx); err == nil {
- q.Estimate, q.Known = prorateEstimate(price, 1, pnow, sub.PeriodEnd), true
- }
+ if pnow, err := s.providerNow(ctx); err == nil {
+ q.Estimate, q.Known = prorateEstimate(price, 1, pnow, sub.PeriodEnd), true
}
return q, nil, nil
}
@@ -641,7 +653,7 @@ func (s *Server) handleBillingSeats(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)
diff --git a/internal/console/billingseats_test.go b/internal/console/billingseats_test.go
index 3cc3ab321..a284cbd61 100644
--- a/internal/console/billingseats_test.go
+++ b/internal/console/billingseats_test.go
@@ -777,10 +777,14 @@ func TestMatchSeatsReduces(t *testing.T) {
for _, ck := range o.owner.Jar.Cookies(u) {
req.AddCookie(ck)
}
+ // The refusal's text comes from the copy map: a changed entry shows.
+ saved := billingCopy["refused.csrf"]
+ billingCopy["refused.csrf"] = "copy-map refusal"
rr := httptest.NewRecorder()
o.srv.ServeHTTP(rr, req)
- if rr.Code != http.StatusForbidden {
- t.Fatalf("no csrf = %d", rr.Code)
+ billingCopy["refused.csrf"] = saved
+ if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "copy-map refusal") {
+ t.Fatalf("no csrf = %d, want 403 with the copy map's refusal\n%s", rr.Code, rr.Body.String())
}
rt := o.srv.billing
o.srv.billing = nil
@@ -790,15 +794,42 @@ func TestMatchSeatsReduces(t *testing.T) {
o.srv.billing = rt
}
+// TestMatchSeatsRefusedByAProblemItsReadOpens: a seat restore held until
+// the renewal applies after it (Risk R1). Nothing is open before the
+// request; Match seats' own reads (finishing the restore, the allowance)
+// flag restore_after_renewal, and that stops the reduction before anything
+// is prepared.
func TestMatchSeatsRefusedByAProblemItsReadOpens(t *testing.T) {
- o := newSeatsFixture(t, 10, 13)
- if _, err := o.st.OpenBillingProblem(o.acct.ID, "sub_1", problemRestoreAfterRenewal, "test", time.Now()); err != nil {
+ o := newSeatsFixture(t, 10, 11)
+ o.setSeats(t, 10) // paid 11, the plan item at 10
+ o.observe()
+ item := o.sub("sub_1").Items[0]
+ p, err := o.fake.PrepareChange(billing.ChangeRequest{Subscription: "sub_1", Items: []billing.ItemChange{{ItemID: item.ItemID, Quantity: 11}},
+ Proration: billing.ProrateNone, ProrationDate: o.providerClock(), IdempotencyKey: "op:op_held"})
+ if err != nil {
t.Fatal(err)
}
+ o.fake.ApplyAfterRenewal(p.Key)
+ h, release := o.hold()
+ out, _, err := o.srv.sendOpLocked(h, o.ctx, billingOp{ID: "op_held", AccountID: o.acct.ID, Subscription: "sub_1", Kind: opRestore,
+ PeriodEnd: periodEnd, Target: opTarget{Quantities: map[string]int64{communityPrice(): 11}}, Prepared: p, StartQuantity: knownStart(10)}, billingNow)
+ release()
+ if err != nil || out.State != opUnresolved {
+ t.Fatalf("held restore: %+v %v", out, err)
+ }
+ if err := o.fake.Renew("sub_1"); err != nil { // the renewal bills 10, 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.reset()
r := o.request(t, http.MethodPost, o.billingBase()+"/seats", nil)
o.wantFlash(t, r, "err", billingCopy[errCheckoutProblem.Key])
- if c := o.counts(); c["Send"] != 0 || o.seatQty(t) != 13 {
+ if got := o.openProblems(t); len(got) != 1 || got[0] != problemRestoreAfterRenewal {
+ t.Fatalf("problems = %v, want restore_after_renewal from the request's own read", got)
+ }
+ if c := o.counts(); c["Send"] != 0 || o.seatQty(t) != 11 {
t.Fatalf("counts %v seats %d", c, o.seatQty(t))
}
}
@@ -929,6 +960,81 @@ func TestAcceptAndRemoveReturnUnderTimeout(t *testing.T) {
})
}
+// TestSeatConsentNeedsAKnownPrice: on a subscription whose book is not the
+// configured one the console holds no per-seat price, so an invite that
+// needs a new paid seat records no consent (change.book), and an
+// authorisation with no known price never covers a charge.
+func TestSeatConsentNeedsAKnownPrice(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ o.srv.billing.cfg.Prices = subscriptionsBookPrices(t, o.srv.billing.cfg.Book)
+ s := o.teamSub("sub_1", "community", "active", 10)
+ s.Items[0].PriceID = testPriceID("example-v0/community/usd")
+ o.put(s)
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if b := o.billingRow(t); b.Book != "example-v0" || b.Plan != "community" {
+ t.Fatalf("billing row = %+v", b)
+ }
+ o.stepUp(t)
+ for _, confirmed := range []bool{false, true} {
+ form := url.Values{"address": {"new@example.com"}}
+ if confirmed {
+ form.Set("confirmed", "1")
+ }
+ r := o.request(t, http.MethodPost, o.teamPath("/invite"), form)
+ if r.Status != http.StatusSeeOther || r.Flash != "err" || r.FlashMsg != billingCopy["change.book"] {
+ t.Fatalf("confirmed=%v: invite = %+v, want the change.book refusal", confirmed, r)
+ }
+ if inv, _ := o.st.PendingInvites(o.acct.ID); len(inv) != 0 {
+ t.Fatalf("confirmed=%v: an invite with no known seat price: %+v", confirmed, inv)
+ }
+ }
+ // An authorisation on that book (however recorded) with no price the
+ // console can verify covers nothing: zero, or any amount off the
+ // configured book.
+ for _, price := range []int64{0, 1_000_000} {
+ in := o.invitee(t, fmt.Sprintf("p%d@example.com", price))
+ tok := o.plainInvite(t, in.addr)
+ if err := o.st.SetInviteSeatAuthorisation(tok, seatAuthorisation{Plan: "community", Book: "example-v0", Currency: "usd",
+ PriceMinor: price, By: o.ownerAddr(), At: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ wantAdmit(t, o.accept(in, tok), "seats.join_consent")
+ if n := o.counts()["Send"]; n != 0 || o.members(t) != 10 {
+ t.Fatalf("price %d: sends %d members %d", price, n, o.members(t))
+ }
+ }
+}
+
+// TestAdmissionReadFailureNeverJoins: a failed read while finishing the
+// subscription's outstanding work answers join_uncertain, never the joined
+// flow, and writes no membership.
+func TestAdmissionReadFailureNeverJoins(t *testing.T) {
+ for _, table := range []string{"billing_accounts", "billing_operations"} {
+ t.Run(table, func(t *testing.T) {
+ o := newSeatsFixture(t, 10, 11)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.plainInvite(t, in.addr)
+ // The read fails: the table is not there for this request.
+ if _, err := o.st.db.Exec(`ALTER TABLE ` + table + ` RENAME TO hidden_` + table); err != nil {
+ t.Fatal(err)
+ }
+ r := o.accept(in, tok)
+ if _, err := o.st.db.Exec(`ALTER TABLE hidden_` + table + ` RENAME TO ` + table); err != nil {
+ t.Fatal(err)
+ }
+ wantAdmit(t, r, "seats.join_uncertain")
+ if o.members(t) != 10 || !o.pendingInvite(t, tok) {
+ t.Fatalf("members %d invite pending %v", o.members(t), o.pendingInvite(t, tok))
+ }
+ // The same accept with the reads back joins.
+ o.wantJoined(t, o.accept(in, tok))
+ })
+ }
+}
+
// ---- unit --------------------------------------------------------------------------
func TestSeatCovered(t *testing.T) {
@@ -949,6 +1055,7 @@ func TestSeatCovered(t *testing.T) {
{"other currency", func(a *seatAuthorisation) { a.Currency = "eur" }, false},
{"price above what was agreed", func(a *seatAuthorisation) { a.PriceMinor = price - 1 }, false},
{"agreed above the price", func(a *seatAuthorisation) { a.PriceMinor = price + 1 }, true},
+ {"no recorded price", func(a *seatAuthorisation) { a.PriceMinor = 0 }, false},
} {
a := good
c.edit(&a)
@@ -959,4 +1066,10 @@ func TestSeatCovered(t *testing.T) {
if seatCovered(nil, row, book) {
t.Error("no authorisation covered a seat")
}
+ // A subscription and authorisation on a book the console no longer
+ // holds: no verifiable price, so not covered.
+ old := &billingAccount{Plan: "community", Book: "example-v0", Currency: "usd"}
+ if a := (seatAuthorisation{Plan: "community", Book: "example-v0", Currency: "usd", PriceMinor: price}); seatCovered(&a, old, book) {
+ t.Error("an authorisation off the configured book covered a seat")
+ }
}