package abonotest_test import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "errors" "fmt" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "reflect" "strings" "sync" "testing" "time" "gorm.io/gorm" "amadan.net/rastrillo/rastrillo/csrf" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" "amadan.net/rastrillo/rastrillo/sessions" "amadan.net/rastrillo/abono" "amadan.net/rastrillo/abono/abonotest" ) const day = 24 * time.Hour // roles is Patrix's role move, as an app's Holder and OnChange. Holder // makes an account (the subject is the address) for whoever pays. // OnChange is told a subject's holdings moved; a staff subject it // declines to move, so staff keep their role whatever they pay for. // Roles are worked out from HasPlan afterwards, as Patrix's settle did, // because OnChange runs inside abono's transaction and HasPlan does not. type roles struct { mu sync.Mutex accounts map[string]bool staff map[string]bool told []string declined []string } func (r *roles) Holder(_ context.Context, _ *gorm.DB, email, _ string) (string, error) { r.mu.Lock() defer r.mu.Unlock() r.accounts[email] = true return email, nil } func (r *roles) OnChange(_ context.Context, _ *gorm.DB, subject string) error { r.mu.Lock() defer r.mu.Unlock() if r.staff[subject] { r.declined = append(r.declined, subject) return nil } r.told = append(r.told, subject) return nil } // take returns who OnChange moved and declined since the last take. func (r *roles) take() (told, declined []string) { r.mu.Lock() defer r.mu.Unlock() told, declined = r.told, r.declined r.told, r.declined = nil, nil return told, declined } func (r *roles) hasAccount(email string) bool { r.mu.Lock() defer r.mu.Unlock() return r.accounts[email] } // app is an app wired to abono the way the example will be: the webhook // and the tick mounted behind csrf.Protect with both exempted. type app struct { t *testing.T stripe *abonotest.Stripe // nil with no Stripe s *abono.Service url string roles *roles } const owner = "owner@example.com" // newApp is an app over a fresh database, selling annual (price_annual, // with the old site's price_pmpro_annual as legacy) and monthly // (price_monthly), through abonotest's Stripe when stripe is set. func newApp(t *testing.T, stripe bool) *app { t.Helper() d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), nil) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) if _, err := migrate.Apply(context.Background(), d, migrate.Merge(sessions.Schema, abono.Schema)); err != nil { t.Fatalf("migrate.Apply: %v", err) } srv := httptest.NewUnstartedServer(nil) origin := "http://" + srv.Listener.Addr().String() r := &roles{accounts: map[string]bool{}, staff: map[string]bool{owner: true}} a := &app{t: t, url: origin, roles: r} cfg := abono.Config{ DB: d.G, Origin: origin, Holder: r.Holder, OnChange: r.OnChange, Logger: slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil)), } if stripe { a.stripe = abonotest.New(t) a.stripe.AddPrice("price_annual", "annual", 6000, "eur", "year") a.stripe.AddPrice("price_pmpro_annual", "annual", 4000, "eur", "year") a.stripe.AddPrice("price_monthly", "monthly", 600, "eur", "month") cfg = a.stripe.Config(cfg) } if a.s, err = abono.New(cfg); err != nil { t.Fatalf("abono.New: %v", err) } if err := a.s.SeedPlans(context.Background(), []abono.PlanSpec{ {Plan: "annual", Sold: "price_annual", Legacy: []string{"price_pmpro_annual"}}, {Plan: "monthly", Sold: "price_monthly"}, }); err != nil { t.Fatalf("SeedPlans: %v", err) } mux := http.NewServeMux() mux.HandleFunc("POST "+abono.WebhookPath, a.s.ServeWebhook) mux.HandleFunc("POST "+abono.SyncPath, a.s.ServeSync) srv.Config.Handler = csrf.Protect(origin, csrf.Exempt(abono.WebhookPath, abono.SyncPath))(mux) srv.Start() t.Cleanup(srv.Close) if a.stripe != nil { a.stripe.SetWebhookURL(origin + abono.WebhookPath) } return a } func (a *app) now() time.Time { if a.stripe != nil { return a.stripe.Now() } return time.Now() } func (a *app) hasPlan(subject, plan string) bool { a.t.Helper() ok, err := a.s.HasPlan(context.Background(), subject, plan) if err != nil { a.t.Fatalf("HasPlan(%q, %q): %v", subject, plan, err) } return ok } // role is what Patrix would make subject: staff stay staff, anyone holding // a plan is a subscriber, anyone else a spectator. func (a *app) role(subject string) string { a.t.Helper() switch { case a.roles.staff[subject]: return "owner" case a.hasPlan(subject, "annual") || a.hasPlan(subject, "monthly"): return "subscriber" } return "spectator" } func (a *app) wantRoles(when string, want map[string]string) { a.t.Helper() for subject, role := range want { if got := a.role(subject); got != role { a.t.Errorf("%s: %s is %s, want %s", when, subject, got, role) } } } // customer is subject's one Stripe customer. func (a *app) customer(subject string) string { a.t.Helper() cs, err := a.s.Customers(context.Background(), subject) if err != nil || len(cs) != 1 { a.t.Fatalf("Customers(%s) = %q, %v; want one", subject, cs, err) } return cs[0] } func (a *app) holdings(subject string) []abono.Holding { a.t.Helper() hs, err := a.s.Holdings(context.Background(), subject) if err != nil { a.t.Fatalf("Holdings(%q): %v", subject, err) } return hs } // webhook posts body to the app's webhook with signature. func (a *app) webhook(body []byte, signature string) int { a.t.Helper() req, _ := http.NewRequest(http.MethodPost, a.url+abono.WebhookPath, bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") if signature != "" { req.Header.Set("Stripe-Signature", signature) } resp, err := http.DefaultClient.Do(req) if err != nil { a.t.Fatalf("POST webhook: %v", err) } resp.Body.Close() return resp.StatusCode } func sign(secret string, body []byte, at time.Time) string { mac := hmac.New(sha256.New, []byte(secret)) fmt.Fprintf(mac, "%d.", at.Unix()) mac.Write(body) return fmt.Sprintf("t=%d,v1=%s", at.Unix(), hex.EncodeToString(mac.Sum(nil))) } func eq(t *testing.T, what string, got, want []string) { t.Helper() if len(got) == 0 && len(want) == 0 { return } if !reflect.DeepEqual(got, want) { t.Errorf("%s = %q, want %q", what, got, want) } } // TestAbonotestEndToEnd is Farshad's six end-to-end tests from Patrix, // against abonotest's Stripe. func TestAbonotestEndToEnd(t *testing.T) { ctx := context.Background() t.Run("checkout to holder to cancel", func(t *testing.T) { a := newApp(t, true) const reader = "new@example.com" u, err := a.s.Checkout(ctx, abono.CheckoutRequest{Plan: "annual", SuccessPath: "/subscribe/done", CancelPath: "/subscribe/annual"}) if err != nil { t.Fatalf("Checkout: %v", err) } if !strings.HasPrefix(u, a.stripe.URL+"/checkout/") { t.Fatalf("Checkout URL = %q, want the fake's page", u) } // Paying sends the webhook, which makes the account. done := a.stripe.Pay(t, u, "New@Example.com") if !a.roles.hasAccount(reader) { t.Fatal("Holder made no account for the reader") } if !a.hasPlan(reader, "annual") { t.Fatal("HasPlan is false after paying") } told, _ := a.roles.take() eq(t, "OnChange after paying", told, []string{reader}) a.wantRoles("after paying", map[string]string{reader: "subscriber"}) // Checkout's return changes nothing more. back, err := url.Parse(done) if err != nil || !strings.HasPrefix(done, a.url+"/subscribe/done?") { t.Fatalf("success URL = %q", done) } f, err := a.s.Finish(ctx, back.Query().Get("session_id")) if err != nil { t.Fatalf("Finish: %v", err) } if want := (abono.Finished{Email: reader, Subject: reader, Paid: true}); f != want { t.Errorf("Finish = %+v, want %+v", f, want) } hs := a.holdings(reader) if len(hs) != 1 { t.Fatalf("holdings = %+v, want one", hs) } if told, _ := a.roles.take(); len(told) != 0 { t.Errorf("OnChange after Finish: %q, want nobody", told) } if got := abono.Describe(hs[0], a.now()).Key; got != abono.StatusRenews { t.Errorf("status = %s, want renews", got) } // They cancel in the portal: still theirs until the period ends. pu, err := a.s.Portal(ctx, reader, a.customer(reader), "/account") if err != nil { t.Fatalf("Portal: %v", err) } a.stripe.Cancel(t, pu, hs[0].SubscriptionID) hs = a.holdings(reader) if got := abono.Describe(hs[0], a.now()).Key; got != abono.StatusCancelling { t.Errorf("after cancelling, status = %s, want %s", got, abono.StatusCancelling) } a.wantRoles("cancelling", map[string]string{reader: "subscriber"}) // The period ends: Stripe ends it, and they are a spectator. a.stripe.Advance(366 * day) if a.hasPlan(reader, "annual") { t.Error("HasPlan is true past the period end") } if hs = a.holdings(reader); hs[0].Status != "canceled" { t.Errorf("status past the period end = %s, want canceled", hs[0].Status) } a.wantRoles("after it ended", map[string]string{reader: "spectator"}) if told, _ := a.roles.take(); len(told) == 0 || told[len(told)-1] != reader { t.Errorf("OnChange was not told it ended: %q", told) } }) t.Run("refused signatures", func(t *testing.T) { a := newApp(t, true) body := []byte(`{"id":"evt_x","type":"customer.subscription.updated","data":{"object":{"id":"sub_x"}}}`) now := a.now() for name, sig := range map[string]string{ "wrong secret": sign("whsec_wrong", body, now), "stale": sign(a.stripe.Secret, body, now.Add(-time.Hour)), "none": "", } { if code := a.webhook(body, sig); code != http.StatusBadRequest { t.Errorf("%s: status %d, want 400", name, code) } } // Signed, about a subscription Stripe does not have: taken, since // a retry cannot bring it back (Patrix answered 500 here). if code := a.webhook(body, sign(a.stripe.Secret, body, now)); code != http.StatusOK { t.Errorf("signed, unknown subscription: status %d, want 200", code) } // An event abono does not read is taken and ignored. other := []byte(`{"id":"evt_y","type":"customer.created","data":{"object":{"id":"cus_y"}}}`) if code := a.webhook(other, sign(a.stripe.Secret, other, now)); code != http.StatusOK { t.Errorf("an unread event: status %d, want 200", code) } // The tick is the platform's alone. resp, err := http.Post(a.url+abono.SyncPath, "", nil) if err != nil { t.Fatal(err) } resp.Body.Close() if resp.StatusCode != http.StatusForbidden { t.Errorf("the tick without carlos's token: status %d, want 403", resp.StatusCode) } if told, declined := a.roles.take(); len(told)+len(declined) != 0 { t.Errorf("OnChange ran: %q %q", told, declined) } }) t.Run("no Stripe", func(t *testing.T) { a := newApp(t, false) if a.s.On() { t.Fatal("On() with nothing configured") } if _, err := a.s.Checkout(ctx, abono.CheckoutRequest{Plan: "annual"}); err == nil { t.Error("Checkout succeeded with no Stripe") } if _, err := a.s.Portal(ctx, "someone@example.com", "cus_1", "/account"); err == nil { t.Error("Portal succeeded with no Stripe") } body := []byte(`{"id":"evt_1","type":"customer.subscription.updated","data":{"object":{"id":"sub_1"}}}`) if code := a.webhook(body, sign("whsec_any", body, time.Now())); code != http.StatusNotFound { t.Errorf("webhook with no Stripe: status %d, want 404", code) } }) t.Run("staff untouched", func(t *testing.T) { a := newApp(t, true) u, err := a.s.Checkout(ctx, abono.CheckoutRequest{Plan: "monthly", Subject: owner, Email: owner}) if err != nil { t.Fatalf("Checkout: %v", err) } a.stripe.Pay(t, u, "") if !a.hasPlan(owner, "monthly") { t.Error("the owner's own subscription does not hold") } told, declined := a.roles.take() eq(t, "moved", told, nil) eq(t, "declined", declined, []string{owner}) a.wantRoles("subscribed", map[string]string{owner: "owner"}) pu, err := a.s.Portal(ctx, owner, a.customer(owner), "/account") if err != nil { t.Fatalf("Portal: %v", err) } a.stripe.Cancel(t, pu, a.holdings(owner)[0].SubscriptionID) a.stripe.Advance(32 * day) if a.hasPlan(owner, "monthly") { t.Error("the owner's ended subscription still holds") } told, declined = a.roles.take() eq(t, "moved after it ended", told, nil) if len(declined) == 0 { t.Error("OnChange was not told the owner's subscription ended") } a.wantRoles("after it ended", map[string]string{owner: "owner"}) // A cancelled subscription nobody here holds makes no account. a.stripe.AddSubscription(abonotest.Subscription{ID: "sub_gone", Email: "gone@example.com", Price: "price_monthly", Status: "canceled", PeriodEnd: a.now()}) a.stripe.SendEvent("customer.subscription.deleted", "sub_gone") if a.roles.hasAccount("gone@example.com") { t.Error("a lapsed stranger got an account") } if hs := a.holdings("gone@example.com"); len(hs) != 0 { t.Errorf("a lapsed stranger holds %+v", hs) } }) t.Run("import and reconcile", func(t *testing.T) { a := newApp(t, true) now := a.now() const paid, comp, lapsing = "paid@example.com", "comp@example.com", "lapsing@example.com" // The old site's members: one paying through Stripe on its own // price, two given a membership, and the owner. a.stripe.AddSubscription(abonotest.Subscription{ID: "sub_p", Customer: "cus_p", Email: paid, Name: "Paid Reader", Price: "price_pmpro_annual", Status: "active", PeriodEnd: now.AddDate(0, 3, 0)}) if err := a.s.Adopt(ctx, "sub_p", "", "annual"); err != nil { t.Fatalf("Adopt: %v", err) } compEnds, lapsingEnds := now.Add(70*day), now.Add(day) for _, c := range []struct { subject, plan string ends *time.Time }{{comp, "monthly", &compEnds}, {lapsing, "monthly", &lapsingEnds}, {owner, "annual", nil}} { if _, err := a.s.Comp(ctx, c.subject, c.plan, c.ends, "imported"); err != nil { t.Fatalf("Comp %s: %v", c.subject, err) } } a.wantRoles("imported", map[string]string{paid: "subscriber", comp: "subscriber", lapsing: "subscriber", owner: "owner"}) a.roles.take() // Again: nothing new. if err := a.s.Adopt(ctx, "sub_p", "", "annual"); err != nil { t.Fatalf("Adopt again: %v", err) } if hs := a.holdings(paid); len(hs) != 1 { t.Errorf("after adopting twice, holdings = %+v", hs) } if told, _ := a.roles.take(); len(told) != 0 { t.Errorf("adopting again told %q", told) } // Two days on, the reconcile reads Stripe and ends what ran out: // the lapsing comp, and the paid one Stripe now says is unpaid. a.stripe.Advance(2 * day) a.stripe.AddSubscription(abonotest.Subscription{ID: "sub_p", Customer: "cus_p", Email: paid, Name: "Paid Reader", Price: "price_pmpro_annual", Status: "unpaid", PeriodEnd: now.AddDate(0, 3, 0)}) rep, err := a.s.Reconcile(ctx) if err != nil { t.Fatalf("Reconcile: %v", err) } if rep.Subscriptions != 1 || rep.Subjects != 4 { t.Errorf("Reconcile = %+v, want 1 subscription and 4 subjects", rep) } a.wantRoles("reconciled", map[string]string{paid: "spectator", comp: "subscriber", lapsing: "spectator", owner: "owner"}) hs := a.holdings(paid) if len(hs) != 1 || hs[0].Plan != "annual" || hs[0].Status != "unpaid" { t.Errorf("paid's holdings = %+v, want annual, unpaid", hs) } told, declined := a.roles.take() // paid twice (its sync moved it, then the sweep), the other two // members once, and the owner declined. if len(told) != 4 || len(declined) != 1 { t.Errorf("Reconcile told %q and declined %q, want paid twice, comp, lapsing, and the owner declined", told, declined) } }) t.Run("comps", func(t *testing.T) { a := newApp(t, false) // a comp needs no Stripe const friend = "friend@example.com" ends := a.now().Add(90 * day) id, err := a.s.Comp(ctx, friend, "annual", &ends, "a friend") if err != nil { t.Fatalf("Comp: %v", err) } a.wantRoles("given", map[string]string{friend: "subscriber"}) if hs := a.holdings(friend); len(hs) != 1 || abono.Describe(hs[0], a.now()).Key != abono.StatusCompUntil { t.Errorf("holdings = %+v, want one comp until a date", hs) } if err := a.s.EndComp(ctx, id); err != nil { t.Fatalf("EndComp: %v", err) } a.wantRoles("ended", map[string]string{friend: "spectator"}) told, _ := a.roles.take() eq(t, "OnChange", told, []string{friend, friend}) if err := a.s.EndComp(ctx, id); err != nil { t.Errorf("ending it again: %v", err) } if told, _ := a.roles.take(); len(told) != 0 { t.Errorf("ending it again told %q", told) } if err := a.s.EndComp(ctx, id+100); !errors.Is(err, abono.ErrNotFound) { t.Errorf("ending a comp that does not exist: %v, want ErrNotFound", err) } }) } // TestAbonotestDecline: a declined payment makes nothing. func TestAbonotestDecline(t *testing.T) { a := newApp(t, true) u, err := a.s.Checkout(context.Background(), abono.CheckoutRequest{Plan: "annual", CancelPath: "/subscribe/annual"}) if err != nil { t.Fatalf("Checkout: %v", err) } if back := a.stripe.Decline(t, u); back != a.url+"/subscribe/annual" { t.Errorf("Decline came back to %q", back) } if told, _ := a.roles.take(); len(told) != 0 { t.Errorf("OnChange after declining: %q", told) } }