console: owners reach the locked portal for cards and invoices (plans 6b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+233
−0
internal/console/billingpage_copy.go+4 −0internal/console/billingportal.go+76 −0internal/console/billingportal_test.go+131 −0internal/console/claim_invariant_fixtures_test.go+3 −0internal/console/claim_invariant_probes_nonapp_test.go+15 −0internal/console/server.go+3 −0internal/console/testdata/claim-routes.txt+1 −0
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go| index 86880a801..930bd3df4 100644 |
| --- a/internal/console/billingpage_copy.go |
| +++ b/internal/console/billingpage_copy.go |
| @@ -32,6 +32,10 @@ var billingCopy = map[string]string{ |
| "refused.title": "Refused", |
| "refused.csrf": "Cross-site request blocked.", |
| + // The locked portal (Task 12). |
| + "portal.none": "This account hasn't bought anything yet.", |
| + "portal.failed": "We couldn't open Payment and invoices. Try again in a minute.", |
| + |
| // 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.", |
| "seats.join_wait_title": "Not yet", |
diff --git a/internal/console/billingportal.go b/internal/console/billingportal.go| new file mode 100644 |
| index 000000000..3ae012949 |
| --- /dev/null |
| +++ b/internal/console/billingportal.go |
| @@ -0,0 +1,76 @@ |
| +package console |
| + |
| +import ( |
| + "crypto/rand" |
| + "crypto/subtle" |
| + "encoding/hex" |
| + "log" |
| + "net/http" |
| +) |
| + |
| +// The locked portal (plans 6b, Task 12): an owner's way to the provider's |
| +// hosted page for cards and invoices. The portal configuration is fixed on |
| +// the provider's side to payment methods and invoices (no plan or quantity |
| +// changes), so opening it changes nothing here: the handler takes no billing |
| +// hold and writes nothing locally. |
| + |
| +// newPortalNonce is a fresh nonce for one portal request's idempotency key, |
| +// so two opens never share a key. |
| +func newPortalNonce() string { |
| + var b [8]byte |
| + if _, err := rand.Read(b[:]); err != nil { |
| + panic(err) |
| + } |
| + return hex.EncodeToString(b[:]) |
| +} |
| + |
| +// handleBillingPortal is POST /a/{sqid}/billing/portal. Billing off answers |
| +// 404, a member the owner gate's 404, no CSRF 403. A billing system that is |
| +// not ready, an account with no provider customer, and a provider failure |
| +// each go back to the billing page with a flash. Otherwise a fresh sign-in |
| +// 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) |
| + if !ok { |
| + return |
| + } |
| + if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 { |
| + s.billingCSRFRefused(w, r) |
| + return |
| + } |
| + back := billingPagePath(acct.Sqid) |
| + if !s.billing.ready.Load() { |
| + s.setFlash(w, "err", billingCopy["portal.failed"]) |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| + return |
| + } |
| + b, err := s.store.BillingAccount(acct.ID) |
| + if err != nil { |
| + log.Printf("console: billing portal %s: %v", acct.Sqid, err) |
| + s.setFlash(w, "err", billingCopy["portal.failed"]) |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| + return |
| + } |
| + if b == nil || b.Customer == "" { |
| + s.setFlash(w, "err", billingCopy["portal.none"]) |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| + return |
| + } |
| + if !s.requireFreshAuth(w, r, addr, raw) { |
| + return |
| + } |
| + to, err := s.billing.cfg.Provider.PortalURL(r.Context(), b.Customer, s.cfg.Origin+back, |
| + "portal:"+b.Customer+":"+newPortalNonce()) |
| + if err != nil { |
| + log.Printf("console: billing portal %s: %v", acct.Sqid, err) |
| + s.setFlash(w, "err", billingCopy["portal.failed"]) |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| + return |
| + } |
| + http.Redirect(w, r, to, http.StatusSeeOther) |
| +} |
diff --git a/internal/console/billingportal_test.go b/internal/console/billingportal_test.go| new file mode 100644 |
| index 000000000..e92103d48 |
| --- /dev/null |
| +++ b/internal/console/billingportal_test.go |
| @@ -0,0 +1,131 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// portalSpy records the arguments of each PortalURL call and passes it on. |
| +type portalSpy struct { |
| + billing.Provider |
| + mu sync.Mutex |
| + calls []portalCall |
| +} |
| + |
| +type portalCall struct{ Customer, Return, Key string } |
| + |
| +func (p *portalSpy) PortalURL(ctx context.Context, customer, returnURL, key string) (string, error) { |
| + p.mu.Lock() |
| + p.calls = append(p.calls, portalCall{customer, returnURL, key}) |
| + p.mu.Unlock() |
| + return p.Provider.PortalURL(ctx, customer, returnURL, key) |
| +} |
| + |
| +func (p *portalSpy) all() []portalCall { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + return append([]portalCall(nil), p.calls...) |
| +} |
| + |
| +func (o *opsFixture) portal(t *testing.T) billingReply { |
| + t.Helper() |
| + return o.request(t, http.MethodPost, o.billingBase()+"/portal", nil) |
| +} |
| + |
| +// spyPortal puts a spy in front of the Fake. |
| +func (o *opsFixture) spyPortal() *portalSpy { |
| + spy := &portalSpy{Provider: o.srv.billing.cfg.Provider} |
| + o.srv.billing.cfg.Provider = spy |
| + return spy |
| +} |
| + |
| +func TestPortalOpens(t *testing.T) { |
| + o := newChangeFixture(t, map[string]int64{"apps": 1}) |
| + spy := o.spyPortal() |
| + o.stepUp(t) |
| + o.reset() |
| + r := o.portal(t) |
| + if r.Status != http.StatusSeeOther || !strings.HasPrefix(r.Loc, "https://billing.example.test/portal/cus_1/") { |
| + t.Fatalf("portal = %d %q, want a 303 to the provider's portal", r.Status, r.Loc) |
| + } |
| + calls := spy.all() |
| + if len(calls) != 1 { |
| + t.Fatalf("PortalURL calls = %v, want 1", calls) |
| + } |
| + c := calls[0] |
| + if want := o.srv.cfg.Origin + o.billingBase(); c.Customer != "cus_1" || c.Return != want { |
| + t.Fatalf("call = %+v, want customer cus_1 and return %s", c, want) |
| + } |
| + if !strings.HasPrefix(c.Key, "portal:cus_1:") || len(c.Key) <= len("portal:cus_1:") { |
| + t.Fatalf("idempotency key = %q, want portal:cus_1:<nonce>", c.Key) |
| + } |
| + // The nonce is fresh per request: a second open sends a different key. |
| + if r := o.portal(t); r.Status != http.StatusSeeOther { |
| + t.Fatalf("second portal = %d", r.Status) |
| + } |
| + calls = spy.all() |
| + if len(calls) != 2 || calls[0].Key == calls[1].Key { |
| + t.Fatalf("keys = %v, want two different keys", calls) |
| + } |
| + // Opening the portal writes nothing locally. |
| + if n := len(o.ops(t)); n != 0 { |
| + t.Fatalf("the portal wrote %d operations", n) |
| + } |
| +} |
| + |
| +func TestPortalGates(t *testing.T) { |
| + // A member is not an owner: the unrouted 404. |
| + o := newChangeFixture(t, nil) |
| + spy := o.spyPortal() |
| + if err := o.st.AddMember(o.acct.ID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + kim := newBrowser(t) |
| + o.setUser("kim@keymail.dev") |
| + signUp(t, o.consoleFixture, kim, "code-kim-portal") |
| + if status, _, _ := postForm(t, kim, o.ts.URL+o.billingBase()+"/portal", url.Values{"csrf": {sessionToken(t, o.consoleFixture, kim)}}); status != http.StatusNotFound { |
| + t.Fatalf("member = %d, want 404", status) |
| + } |
| + // No CSRF: 403. |
| + if status := httpPostNoCSRF(t, o, o.billingBase()+"/portal", url.Values{}); status != http.StatusForbidden { |
| + t.Fatalf("no csrf = %d, want 403", status) |
| + } |
| + // Stale sign-in proof: the step-up gate, no provider call. |
| + r := o.portal(t) |
| + if r.Status != http.StatusSeeOther || strings.HasPrefix(r.Loc, o.billingBase()) || strings.HasPrefix(r.Loc, "https://") { |
| + t.Fatalf("stale auth = %d %q, want the step-up redirect", r.Status, r.Loc) |
| + } |
| + // Not ready: portal.failed, no call. |
| + o.stepUp(t) |
| + o.srv.billing.ready.Store(false) |
| + o.wantFlash(t, o.portal(t), "err", billingCopy["portal.failed"]) |
| + o.srv.billing.ready.Store(true) |
| + // No bound customer: portal.none, no call. |
| + if _, err := o.st.db.Exec(`UPDATE billing_accounts SET customer = '' WHERE account_id = ?`, o.acct.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.wantFlash(t, o.portal(t), "err", billingCopy["portal.none"]) |
| + if got := spy.all(); len(got) != 0 { |
| + t.Fatalf("PortalURL called %v through the gates", got) |
| + } |
| + // A provider error flashes portal.failed. |
| + if _, err := o.st.db.Exec(`UPDATE billing_accounts SET customer = 'cus_1' WHERE account_id = ?`, o.acct.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.fake.Lock() |
| + o.fake.Err = billing.ErrNoResponse |
| + o.fake.Unlock() |
| + o.wantFlash(t, o.portal(t), "err", billingCopy["portal.failed"]) |
| + // Billing off: 404. |
| + o.srv.billing = nil |
| + if r := o.portal(t); r.Status != http.StatusNotFound { |
| + t.Fatalf("billing off = %d, want 404", r.Status) |
| + } |
| +} |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 244b2e9d4..1cb3cb19f 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1301,6 +1301,9 @@ var claimFixtures = map[string]claimFixture{ |
| // The billing webhook re-reads a subscription and writes the account's |
| // plan row and billing state (plans 6a). |
| "route POST /billing/webhook": claimNonApp("re-reads a billing subscription and writes the account's plan row, billing state and billing problems; names no app"), |
| + // Plans 6b: the locked portal opens a provider portal session for the |
| + // account's customer and writes nothing locally. |
| + "route POST /a/{sqid}/billing/portal": claimNonApp("opens a provider portal session for the account's customer and redirects the owner to it, writing nothing locally; names no app"), |
| // Plans 6b: an owner's Confirm now finishes an outstanding billing |
| // operation under the account's billing hold and refreshes the |
| // subscription. |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 469b10f43..92f0d4fd2 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -699,6 +699,21 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return claimBillingPlanIs(t, cx, "personal") |
| }, |
| }, |
| + "route POST /a/{sqid}/billing/portal": { |
| + setup: claimBillingWorld, |
| + do: claimFormReply("/a/bab/billing/portal"), |
| + status: http.StatusSeeOther, loc: "https://billing.example.test/portal/cus_claim/", |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake) |
| + fake.Lock() |
| + opened := fake.CallsBy["PortalURL"] |
| + fake.Unlock() |
| + if opened != 1 { |
| + return fmt.Sprintf("the portal was opened %d times, want 1", opened) |
| + } |
| + return "" |
| + }, |
| + }, |
| "route POST /a/{sqid}/billing/checkout": { |
| setup: claimCheckoutWorld, |
| do: claimFormReply("/a/bab/billing/checkout", "plan", "personal", "currency", "usd"), |
diff --git a/internal/console/server.go b/internal/console/server.go| index cfb988d31..4786f2269 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1579,6 +1579,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // Plans 6b: an owner's Match seats to members (billingseats.go). 404 |
| // with billing off. |
| s.registerRoute("POST /a/{sqid}/billing/seats", s.handleBillingSeats) |
| + // Plans 6b: an owner's way to the provider's locked portal for cards |
| + // and invoices (billingportal.go). 404 with billing off. |
| + s.registerRoute("POST /a/{sqid}/billing/portal", s.handleBillingPortal) |
| // The billing page (billingpage.go): member-readable, its forms the |
| // owner's. 404 with billing off. |
| s.registerRoute("GET /a/{sqid}/billing", s.handleBilling) |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 8adce85ce..f6134edce 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -157,6 +157,7 @@ route POST /a/{sqid}/apps/{app}/swap |
| route POST /a/{sqid}/billing/change |
| route POST /a/{sqid}/billing/checkout |
| route POST /a/{sqid}/billing/confirm |
| +route POST /a/{sqid}/billing/portal |
| route POST /a/{sqid}/billing/renewal |
| route POST /a/{sqid}/billing/seats |
| route POST /a/{sqid}/delete |