rastrillo / abono Public

Clone
git clone https://amadan.net/rastrillo/abono

Plain git — no account needed to clone.

Download

Download this file

1package abonotest_test
2
3import (
4 "bytes"
5 "context"
6 "crypto/hmac"
7 "crypto/sha256"
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "log/slog"
12 "net/http"
13 "net/http/httptest"
14 "net/url"
15 "path/filepath"
16 "reflect"
17 "strings"
18 "sync"
19 "testing"
20 "time"
21
22 "gorm.io/gorm"
23
24 "amadan.net/rastrillo/rastrillo/csrf"
25 "amadan.net/rastrillo/rastrillo/db"
26 "amadan.net/rastrillo/rastrillo/migrate"
27 "amadan.net/rastrillo/rastrillo/sessions"
28
29 "amadan.net/rastrillo/abono"
30 "amadan.net/rastrillo/abono/abonotest"
31)
32
33const day = 24 * time.Hour
34
35// roles is Patrix's role move, as an app's Holder and OnChange. Holder
36// makes an account (the subject is the address) for whoever pays.
37// OnChange is told a subject's holdings moved; a staff subject it
38// declines to move, so staff keep their role whatever they pay for.
39// Roles are worked out from HasPlan afterwards, as Patrix's settle did,
40// because OnChange runs inside abono's transaction and HasPlan does not.
41type roles struct {
42 mu sync.Mutex
43 accounts map[string]bool
44 staff map[string]bool
45 told []string
46 declined []string
47}
48
49func (r *roles) Holder(_ context.Context, _ *gorm.DB, email, _ string) (string, error) {
50 r.mu.Lock()
51 defer r.mu.Unlock()
52 r.accounts[email] = true
53 return email, nil
54}
55
56func (r *roles) OnChange(_ context.Context, _ *gorm.DB, subject string) error {
57 r.mu.Lock()
58 defer r.mu.Unlock()
59 if r.staff[subject] {
60 r.declined = append(r.declined, subject)
61 return nil
62 }
63 r.told = append(r.told, subject)
64 return nil
65}
66
67// take returns who OnChange moved and declined since the last take.
68func (r *roles) take() (told, declined []string) {
69 r.mu.Lock()
70 defer r.mu.Unlock()
71 told, declined = r.told, r.declined
72 r.told, r.declined = nil, nil
73 return told, declined
74}
75
76func (r *roles) hasAccount(email string) bool {
77 r.mu.Lock()
78 defer r.mu.Unlock()
79 return r.accounts[email]
80}
81
82// app is an app wired to abono the way the example will be: the webhook
83// and the tick mounted behind csrf.Protect with both exempted.
84type app struct {
85 t *testing.T
86 stripe *abonotest.Stripe // nil with no Stripe
87 s *abono.Service
88 url string
89 roles *roles
90}
91
92const owner = "owner@example.com"
93
94// newApp is an app over a fresh database, selling annual (price_annual,
95// with the old site's price_pmpro_annual as legacy) and monthly
96// (price_monthly), through abonotest's Stripe when stripe is set.
97func newApp(t *testing.T, stripe bool) *app {
98 t.Helper()
99 d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), nil)
100 if err != nil {
101 t.Fatalf("db.Open: %v", err)
102 }
103 t.Cleanup(func() { d.Close() })
104 if _, err := migrate.Apply(context.Background(), d, migrate.Merge(sessions.Schema, abono.Schema)); err != nil {
105 t.Fatalf("migrate.Apply: %v", err)
106 }
107
108 srv := httptest.NewUnstartedServer(nil)
109 origin := "http://" + srv.Listener.Addr().String()
110 r := &roles{accounts: map[string]bool{}, staff: map[string]bool{owner: true}}
111 a := &app{t: t, url: origin, roles: r}
112 cfg := abono.Config{
113 DB: d.G, Origin: origin, Holder: r.Holder, OnChange: r.OnChange,
114 Logger: slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil)),
115 }
116 if stripe {
117 a.stripe = abonotest.New(t)
118 a.stripe.AddPrice("price_annual", "annual", 6000, "eur", "year")
119 a.stripe.AddPrice("price_pmpro_annual", "annual", 4000, "eur", "year")
120 a.stripe.AddPrice("price_monthly", "monthly", 600, "eur", "month")
121 cfg = a.stripe.Config(cfg)
122 }
123 if a.s, err = abono.New(cfg); err != nil {
124 t.Fatalf("abono.New: %v", err)
125 }
126 if err := a.s.SeedPlans(context.Background(), []abono.PlanSpec{
127 {Plan: "annual", Sold: "price_annual", Legacy: []string{"price_pmpro_annual"}},
128 {Plan: "monthly", Sold: "price_monthly"},
129 }); err != nil {
130 t.Fatalf("SeedPlans: %v", err)
131 }
132
133 mux := http.NewServeMux()
134 mux.HandleFunc("POST "+abono.WebhookPath, a.s.ServeWebhook)
135 mux.HandleFunc("POST "+abono.SyncPath, a.s.ServeSync)
136 srv.Config.Handler = csrf.Protect(origin, csrf.Exempt(abono.WebhookPath, abono.SyncPath))(mux)
137 srv.Start()
138 t.Cleanup(srv.Close)
139 if a.stripe != nil {
140 a.stripe.SetWebhookURL(origin + abono.WebhookPath)
141 }
142 return a
143}
144
145func (a *app) now() time.Time {
146 if a.stripe != nil {
147 return a.stripe.Now()
148 }
149 return time.Now()
150}
151
152func (a *app) hasPlan(subject, plan string) bool {
153 a.t.Helper()
154 ok, err := a.s.HasPlan(context.Background(), subject, plan)
155 if err != nil {
156 a.t.Fatalf("HasPlan(%q, %q): %v", subject, plan, err)
157 }
158 return ok
159}
160
161// role is what Patrix would make subject: staff stay staff, anyone holding
162// a plan is a subscriber, anyone else a spectator.
163func (a *app) role(subject string) string {
164 a.t.Helper()
165 switch {
166 case a.roles.staff[subject]:
167 return "owner"
168 case a.hasPlan(subject, "annual") || a.hasPlan(subject, "monthly"):
169 return "subscriber"
170 }
171 return "spectator"
172}
173
174func (a *app) wantRoles(when string, want map[string]string) {
175 a.t.Helper()
176 for subject, role := range want {
177 if got := a.role(subject); got != role {
178 a.t.Errorf("%s: %s is %s, want %s", when, subject, got, role)
179 }
180 }
181}
182
183// customer is subject's one Stripe customer.
184func (a *app) customer(subject string) string {
185 a.t.Helper()
186 cs, err := a.s.Customers(context.Background(), subject)
187 if err != nil || len(cs) != 1 {
188 a.t.Fatalf("Customers(%s) = %q, %v; want one", subject, cs, err)
189 }
190 return cs[0]
191}
192
193func (a *app) holdings(subject string) []abono.Holding {
194 a.t.Helper()
195 hs, err := a.s.Holdings(context.Background(), subject)
196 if err != nil {
197 a.t.Fatalf("Holdings(%q): %v", subject, err)
198 }
199 return hs
200}
201
202// webhook posts body to the app's webhook with signature.
203func (a *app) webhook(body []byte, signature string) int {
204 a.t.Helper()
205 req, _ := http.NewRequest(http.MethodPost, a.url+abono.WebhookPath, bytes.NewReader(body))
206 req.Header.Set("Content-Type", "application/json")
207 if signature != "" {
208 req.Header.Set("Stripe-Signature", signature)
209 }
210 resp, err := http.DefaultClient.Do(req)
211 if err != nil {
212 a.t.Fatalf("POST webhook: %v", err)
213 }
214 resp.Body.Close()
215 return resp.StatusCode
216}
217
218func sign(secret string, body []byte, at time.Time) string {
219 mac := hmac.New(sha256.New, []byte(secret))
220 fmt.Fprintf(mac, "%d.", at.Unix())
221 mac.Write(body)
222 return fmt.Sprintf("t=%d,v1=%s", at.Unix(), hex.EncodeToString(mac.Sum(nil)))
223}
224
225func eq(t *testing.T, what string, got, want []string) {
226 t.Helper()
227 if len(got) == 0 && len(want) == 0 {
228 return
229 }
230 if !reflect.DeepEqual(got, want) {
231 t.Errorf("%s = %q, want %q", what, got, want)
232 }
233}
234
235// TestAbonotestEndToEnd is Farshad's six end-to-end tests from Patrix,
236// against abonotest's Stripe.
237func TestAbonotestEndToEnd(t *testing.T) {
238 ctx := context.Background()
239
240 t.Run("checkout to holder to cancel", func(t *testing.T) {
241 a := newApp(t, true)
242 const reader = "new@example.com"
243
244 u, err := a.s.Checkout(ctx, abono.CheckoutRequest{Plan: "annual", SuccessPath: "/subscribe/done", CancelPath: "/subscribe/annual"})
245 if err != nil {
246 t.Fatalf("Checkout: %v", err)
247 }
248 if !strings.HasPrefix(u, a.stripe.URL+"/checkout/") {
249 t.Fatalf("Checkout URL = %q, want the fake's page", u)
250 }
251
252 // Paying sends the webhook, which makes the account.
253 done := a.stripe.Pay(t, u, "New@Example.com")
254 if !a.roles.hasAccount(reader) {
255 t.Fatal("Holder made no account for the reader")
256 }
257 if !a.hasPlan(reader, "annual") {
258 t.Fatal("HasPlan is false after paying")
259 }
260 told, _ := a.roles.take()
261 eq(t, "OnChange after paying", told, []string{reader})
262 a.wantRoles("after paying", map[string]string{reader: "subscriber"})
263
264 // Checkout's return changes nothing more.
265 back, err := url.Parse(done)
266 if err != nil || !strings.HasPrefix(done, a.url+"/subscribe/done?") {
267 t.Fatalf("success URL = %q", done)
268 }
269 f, err := a.s.Finish(ctx, back.Query().Get("session_id"))
270 if err != nil {
271 t.Fatalf("Finish: %v", err)
272 }
273 if want := (abono.Finished{Email: reader, Subject: reader, Paid: true}); f != want {
274 t.Errorf("Finish = %+v, want %+v", f, want)
275 }
276 hs := a.holdings(reader)
277 if len(hs) != 1 {
278 t.Fatalf("holdings = %+v, want one", hs)
279 }
280 if told, _ := a.roles.take(); len(told) != 0 {
281 t.Errorf("OnChange after Finish: %q, want nobody", told)
282 }
283 if got := abono.Describe(hs[0], a.now()).Key; got != abono.StatusRenews {
284 t.Errorf("status = %s, want renews", got)
285 }
286
287 // They cancel in the portal: still theirs until the period ends.
288 pu, err := a.s.Portal(ctx, reader, a.customer(reader), "/account")
289 if err != nil {
290 t.Fatalf("Portal: %v", err)
291 }
292 a.stripe.Cancel(t, pu, hs[0].SubscriptionID)
293 hs = a.holdings(reader)
294 if got := abono.Describe(hs[0], a.now()).Key; got != abono.StatusCancelling {
295 t.Errorf("after cancelling, status = %s, want %s", got, abono.StatusCancelling)
296 }
297 a.wantRoles("cancelling", map[string]string{reader: "subscriber"})
298
299 // The period ends: Stripe ends it, and they are a spectator.
300 a.stripe.Advance(366 * day)
301 if a.hasPlan(reader, "annual") {
302 t.Error("HasPlan is true past the period end")
303 }
304 if hs = a.holdings(reader); hs[0].Status != "canceled" {
305 t.Errorf("status past the period end = %s, want canceled", hs[0].Status)
306 }
307 a.wantRoles("after it ended", map[string]string{reader: "spectator"})
308 if told, _ := a.roles.take(); len(told) == 0 || told[len(told)-1] != reader {
309 t.Errorf("OnChange was not told it ended: %q", told)
310 }
311 })
312
313 t.Run("refused signatures", func(t *testing.T) {
314 a := newApp(t, true)
315 body := []byte(`{"id":"evt_x","type":"customer.subscription.updated","data":{"object":{"id":"sub_x"}}}`)
316 now := a.now()
317 for name, sig := range map[string]string{
318 "wrong secret": sign("whsec_wrong", body, now),
319 "stale": sign(a.stripe.Secret, body, now.Add(-time.Hour)),
320 "none": "",
321 } {
322 if code := a.webhook(body, sig); code != http.StatusBadRequest {
323 t.Errorf("%s: status %d, want 400", name, code)
324 }
325 }
326 // Signed, about a subscription Stripe does not have: taken, since
327 // a retry cannot bring it back (Patrix answered 500 here).
328 if code := a.webhook(body, sign(a.stripe.Secret, body, now)); code != http.StatusOK {
329 t.Errorf("signed, unknown subscription: status %d, want 200", code)
330 }
331 // An event abono does not read is taken and ignored.
332 other := []byte(`{"id":"evt_y","type":"customer.created","data":{"object":{"id":"cus_y"}}}`)
333 if code := a.webhook(other, sign(a.stripe.Secret, other, now)); code != http.StatusOK {
334 t.Errorf("an unread event: status %d, want 200", code)
335 }
336 // The tick is the platform's alone.
337 resp, err := http.Post(a.url+abono.SyncPath, "", nil)
338 if err != nil {
339 t.Fatal(err)
340 }
341 resp.Body.Close()
342 if resp.StatusCode != http.StatusForbidden {
343 t.Errorf("the tick without carlos's token: status %d, want 403", resp.StatusCode)
344 }
345 if told, declined := a.roles.take(); len(told)+len(declined) != 0 {
346 t.Errorf("OnChange ran: %q %q", told, declined)
347 }
348 })
349
350 t.Run("no Stripe", func(t *testing.T) {
351 a := newApp(t, false)
352 if a.s.On() {
353 t.Fatal("On() with nothing configured")
354 }
355 if _, err := a.s.Checkout(ctx, abono.CheckoutRequest{Plan: "annual"}); err == nil {
356 t.Error("Checkout succeeded with no Stripe")
357 }
358 if _, err := a.s.Portal(ctx, "someone@example.com", "cus_1", "/account"); err == nil {
359 t.Error("Portal succeeded with no Stripe")
360 }
361 body := []byte(`{"id":"evt_1","type":"customer.subscription.updated","data":{"object":{"id":"sub_1"}}}`)
362 if code := a.webhook(body, sign("whsec_any", body, time.Now())); code != http.StatusNotFound {
363 t.Errorf("webhook with no Stripe: status %d, want 404", code)
364 }
365 })
366
367 t.Run("staff untouched", func(t *testing.T) {
368 a := newApp(t, true)
369 u, err := a.s.Checkout(ctx, abono.CheckoutRequest{Plan: "monthly", Subject: owner, Email: owner})
370 if err != nil {
371 t.Fatalf("Checkout: %v", err)
372 }
373 a.stripe.Pay(t, u, "")
374 if !a.hasPlan(owner, "monthly") {
375 t.Error("the owner's own subscription does not hold")
376 }
377 told, declined := a.roles.take()
378 eq(t, "moved", told, nil)
379 eq(t, "declined", declined, []string{owner})
380 a.wantRoles("subscribed", map[string]string{owner: "owner"})
381
382 pu, err := a.s.Portal(ctx, owner, a.customer(owner), "/account")
383 if err != nil {
384 t.Fatalf("Portal: %v", err)
385 }
386 a.stripe.Cancel(t, pu, a.holdings(owner)[0].SubscriptionID)
387 a.stripe.Advance(32 * day)
388 if a.hasPlan(owner, "monthly") {
389 t.Error("the owner's ended subscription still holds")
390 }
391 told, declined = a.roles.take()
392 eq(t, "moved after it ended", told, nil)
393 if len(declined) == 0 {
394 t.Error("OnChange was not told the owner's subscription ended")
395 }
396 a.wantRoles("after it ended", map[string]string{owner: "owner"})
397
398 // A cancelled subscription nobody here holds makes no account.
399 a.stripe.AddSubscription(abonotest.Subscription{ID: "sub_gone", Email: "gone@example.com",
400 Price: "price_monthly", Status: "canceled", PeriodEnd: a.now()})
401 a.stripe.SendEvent("customer.subscription.deleted", "sub_gone")
402 if a.roles.hasAccount("gone@example.com") {
403 t.Error("a lapsed stranger got an account")
404 }
405 if hs := a.holdings("gone@example.com"); len(hs) != 0 {
406 t.Errorf("a lapsed stranger holds %+v", hs)
407 }
408 })
409
410 t.Run("import and reconcile", func(t *testing.T) {
411 a := newApp(t, true)
412 now := a.now()
413 const paid, comp, lapsing = "paid@example.com", "comp@example.com", "lapsing@example.com"
414
415 // The old site's members: one paying through Stripe on its own
416 // price, two given a membership, and the owner.
417 a.stripe.AddSubscription(abonotest.Subscription{ID: "sub_p", Customer: "cus_p", Email: paid, Name: "Paid Reader",
418 Price: "price_pmpro_annual", Status: "active", PeriodEnd: now.AddDate(0, 3, 0)})
419 if err := a.s.Adopt(ctx, "sub_p", "", "annual"); err != nil {
420 t.Fatalf("Adopt: %v", err)
421 }
422 compEnds, lapsingEnds := now.Add(70*day), now.Add(day)
423 for _, c := range []struct {
424 subject, plan string
425 ends *time.Time
426 }{{comp, "monthly", &compEnds}, {lapsing, "monthly", &lapsingEnds}, {owner, "annual", nil}} {
427 if _, err := a.s.Comp(ctx, c.subject, c.plan, c.ends, "imported"); err != nil {
428 t.Fatalf("Comp %s: %v", c.subject, err)
429 }
430 }
431 a.wantRoles("imported", map[string]string{paid: "subscriber", comp: "subscriber", lapsing: "subscriber", owner: "owner"})
432 a.roles.take()
433
434 // Again: nothing new.
435 if err := a.s.Adopt(ctx, "sub_p", "", "annual"); err != nil {
436 t.Fatalf("Adopt again: %v", err)
437 }
438 if hs := a.holdings(paid); len(hs) != 1 {
439 t.Errorf("after adopting twice, holdings = %+v", hs)
440 }
441 if told, _ := a.roles.take(); len(told) != 0 {
442 t.Errorf("adopting again told %q", told)
443 }
444
445 // Two days on, the reconcile reads Stripe and ends what ran out:
446 // the lapsing comp, and the paid one Stripe now says is unpaid.
447 a.stripe.Advance(2 * day)
448 a.stripe.AddSubscription(abonotest.Subscription{ID: "sub_p", Customer: "cus_p", Email: paid, Name: "Paid Reader",
449 Price: "price_pmpro_annual", Status: "unpaid", PeriodEnd: now.AddDate(0, 3, 0)})
450 rep, err := a.s.Reconcile(ctx)
451 if err != nil {
452 t.Fatalf("Reconcile: %v", err)
453 }
454 if rep.Subscriptions != 1 || rep.Subjects != 4 {
455 t.Errorf("Reconcile = %+v, want 1 subscription and 4 subjects", rep)
456 }
457 a.wantRoles("reconciled", map[string]string{paid: "spectator", comp: "subscriber", lapsing: "spectator", owner: "owner"})
458 hs := a.holdings(paid)
459 if len(hs) != 1 || hs[0].Plan != "annual" || hs[0].Status != "unpaid" {
460 t.Errorf("paid's holdings = %+v, want annual, unpaid", hs)
461 }
462 told, declined := a.roles.take()
463 // paid twice (its sync moved it, then the sweep), the other two
464 // members once, and the owner declined.
465 if len(told) != 4 || len(declined) != 1 {
466 t.Errorf("Reconcile told %q and declined %q, want paid twice, comp, lapsing, and the owner declined", told, declined)
467 }
468 })
469
470 t.Run("comps", func(t *testing.T) {
471 a := newApp(t, false) // a comp needs no Stripe
472 const friend = "friend@example.com"
473 ends := a.now().Add(90 * day)
474 id, err := a.s.Comp(ctx, friend, "annual", &ends, "a friend")
475 if err != nil {
476 t.Fatalf("Comp: %v", err)
477 }
478 a.wantRoles("given", map[string]string{friend: "subscriber"})
479 if hs := a.holdings(friend); len(hs) != 1 || abono.Describe(hs[0], a.now()).Key != abono.StatusCompUntil {
480 t.Errorf("holdings = %+v, want one comp until a date", hs)
481 }
482 if err := a.s.EndComp(ctx, id); err != nil {
483 t.Fatalf("EndComp: %v", err)
484 }
485 a.wantRoles("ended", map[string]string{friend: "spectator"})
486 told, _ := a.roles.take()
487 eq(t, "OnChange", told, []string{friend, friend})
488 if err := a.s.EndComp(ctx, id); err != nil {
489 t.Errorf("ending it again: %v", err)
490 }
491 if told, _ := a.roles.take(); len(told) != 0 {
492 t.Errorf("ending it again told %q", told)
493 }
494 if err := a.s.EndComp(ctx, id+100); !errors.Is(err, abono.ErrNotFound) {
495 t.Errorf("ending a comp that does not exist: %v, want ErrNotFound", err)
496 }
497 })
498}
499
500// TestAbonotestDecline: a declined payment makes nothing.
501func TestAbonotestDecline(t *testing.T) {
502 a := newApp(t, true)
503 u, err := a.s.Checkout(context.Background(), abono.CheckoutRequest{Plan: "annual", CancelPath: "/subscribe/annual"})
504 if err != nil {
505 t.Fatalf("Checkout: %v", err)
506 }
507 if back := a.stripe.Decline(t, u); back != a.url+"/subscribe/annual" {
508 t.Errorf("Decline came back to %q", back)
509 }
510 if told, _ := a.roles.take(); len(told) != 0 {
511 t.Errorf("OnChange after declining: %q", told)
512 }
513}
514