billingstripe: harvest the stdlib Stripe client from the integration branch, items-based checkout, billing.Provider adapter (plans 6a)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+5,354
−0
internal/billingstripe/adapter.go+287 −0internal/billingstripe/adapter_test.go+427 −0internal/billingstripe/catalog.go+287 −0internal/billingstripe/catalog_test.go+743 −0internal/billingstripe/client.go+875 −0internal/billingstripe/client_test.go+1,005 −0internal/billingstripe/customer.go+208 −0internal/billingstripe/customer_test.go+489 −0internal/billingstripe/merchant.go+74 −0internal/billingstripe/merchant_test.go+97 −0internal/billingstripe/portal.go+127 −0internal/billingstripe/portal_test.go+309 −0internal/billingstripe/webhook.go+162 −0internal/billingstripe/webhook_test.go+264 −0
diff --git a/internal/billingstripe/adapter.go b/internal/billingstripe/adapter.go| new file mode 100644 |
| index 000000000..e4dfcadfd |
| --- /dev/null |
| +++ b/internal/billingstripe/adapter.go |
| @@ -0,0 +1,287 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +// ProviderConfig is what NewProvider needs. The secret key and the webhook |
| +// secrets come from the console's EnvironmentFile and never appear in a |
| +// log line: Provider's String and GoString redact them. |
| +type ProviderConfig struct { |
| + SecretKey string |
| + Account string // acct_... |
| + WebhookSecrets []string // primary first, up to 3 |
| + LiveMode bool |
| + BaseURL string // tests only; "" is api.stripe.com |
| +} |
| + |
| +// maxWebhookSecrets is the primary plus two previous secrets during a |
| +// rotation. |
| +const maxWebhookSecrets = 3 |
| + |
| +// Provider is Stripe as a billing.Provider. |
| +type Provider struct { |
| + client *Client |
| + account string |
| + secrets []string |
| + liveMode bool |
| +} |
| + |
| +var _ billing.Provider = (*Provider)(nil) |
| + |
| +// NewProvider checks cfg and builds a Provider. A test-mode provider needs |
| +// an rk_test_ key and a live one an rk_live_ key. |
| +func NewProvider(cfg ProviderConfig) (*Provider, error) { |
| + prefix := "rk_test_" |
| + if cfg.LiveMode { |
| + prefix = "rk_live_" |
| + } |
| + if !strings.HasPrefix(cfg.SecretKey, prefix) { |
| + return nil, errors.New("billingstripe: the secret key is not a restricted key for this mode") |
| + } |
| + if !strings.HasPrefix(cfg.Account, "acct_") || !validID(cfg.Account) { |
| + return nil, errors.New("billingstripe: the account is not an acct_ id") |
| + } |
| + if len(cfg.WebhookSecrets) == 0 || len(cfg.WebhookSecrets) > maxWebhookSecrets { |
| + return nil, fmt.Errorf("billingstripe: 1 to %d webhook secrets are needed", maxWebhookSecrets) |
| + } |
| + for _, s := range cfg.WebhookSecrets { |
| + if s == "" { |
| + return nil, errors.New("billingstripe: a webhook secret is empty") |
| + } |
| + } |
| + var opts []Option |
| + if cfg.BaseURL != "" { |
| + opts = append(opts, WithBaseURL(cfg.BaseURL)) |
| + } |
| + c, err := NewClient(cfg.SecretKey, opts...) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &Provider{client: c, account: cfg.Account, secrets: append([]string(nil), cfg.WebhookSecrets...), liveMode: cfg.LiveMode}, nil |
| +} |
| + |
| +// String and GoString keep the key and secrets out of any formatted value. |
| +func (p *Provider) String() string { |
| + return fmt.Sprintf("billingstripe.Provider{account:%q, live:%v}", p.account, p.liveMode) |
| +} |
| + |
| +func (p *Provider) GoString() string { return p.String() } |
| + |
| +// Client is the underlying API client, for the calls Plan 6b adds. |
| +func (p *Provider) Client() *Client { return p.client } |
| + |
| +// stateOf maps a Stripe subscription status onto what the plan does with |
| +// it: active, trialing and past due keep paid limits while Stripe retries; |
| +// incomplete changes nothing; everything else, an unknown word included, |
| +// has ended. |
| +func stateOf(status string) billing.State { |
| + switch status { |
| + case "active", "trialing", "past_due": |
| + return billing.StatePaid |
| + case "incomplete": |
| + return billing.StatePending |
| + default: |
| + return billing.StateEnded |
| + } |
| +} |
| + |
| +// ParseEvent verifies a delivery's signature and reduces it to what to |
| +// read. Nothing else from the body is used. |
| +func (p *Provider) ParseEvent(raw []byte, header http.Header, now time.Time) (billing.Event, error) { |
| + ev, err := VerifyEvent(raw, header.Get("Stripe-Signature"), p.secrets, now) |
| + if err != nil { |
| + return billing.Event{}, fmt.Errorf("%w: %v", billing.ErrBadEvent, err) |
| + } |
| + out := billing.Event{ID: ev.ID, LiveMode: ev.LiveMode, Kind: billing.EventIgnored} |
| + var obj struct { |
| + ID string `json:"id"` |
| + Subscription idOrExpanded `json:"subscription"` |
| + } |
| + switch ev.Type { |
| + case "customer.subscription.created", "customer.subscription.updated", "customer.subscription.deleted", |
| + "checkout.session.completed": |
| + if err := json.Unmarshal(ev.Object, &obj); err != nil || !validID(obj.ID) { |
| + return billing.Event{}, fmt.Errorf("%w: %s has no usable object id", billing.ErrBadEvent, ev.Type) |
| + } |
| + out.Object = obj.ID |
| + out.Kind = billing.EventSubscription |
| + if ev.Type == "checkout.session.completed" { |
| + out.Kind = billing.EventCheckout |
| + } |
| + case "invoice.paid", "invoice.payment_failed": |
| + if err := json.Unmarshal(ev.Object, &obj); err != nil { |
| + return billing.Event{}, fmt.Errorf("%w: %s object does not decode", billing.ErrBadEvent, ev.Type) |
| + } |
| + if obj.Subscription.ID == "" { |
| + return out, nil // an invoice for no subscription: nothing to read |
| + } |
| + if !validID(obj.Subscription.ID) { |
| + return billing.Event{}, fmt.Errorf("%w: %s names an unusable subscription id", billing.ErrBadEvent, ev.Type) |
| + } |
| + out.Object = obj.Subscription.ID |
| + out.Kind = billing.EventSubscription |
| + } |
| + return out, nil |
| +} |
| + |
| +// notFound reports Stripe's 404. |
| +func notFound(err error) bool { |
| + var e *Error |
| + return errors.As(err, &e) && e.Code == CodeAPIError && e.HTTPStatus == http.StatusNotFound |
| +} |
| + |
| +// Subscription reads one subscription. |
| +func (p *Provider) Subscription(ctx context.Context, id string) (*billing.Subscription, error) { |
| + s, err := p.client.GetSubscription(ctx, id) |
| + if notFound(err) { |
| + return nil, billing.ErrNotFound |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + out := &billing.Subscription{ |
| + ID: s.ID, |
| + Customer: s.CustomerID, |
| + Account: s.Metadata["account_sqid"], |
| + ProviderStatus: s.Status, |
| + State: stateOf(s.Status), |
| + Currency: s.Currency, |
| + LiveMode: s.LiveMode, |
| + PeriodEnd: s.CurrentPeriodEnd, |
| + CancelAtPeriodEnd: s.CancelAtPeriodEnd, |
| + ItemsComplete: !s.ItemsHasMore, |
| + } |
| + for _, it := range s.Items { |
| + out.Items = append(out.Items, billing.Item{PriceID: it.PriceID, Quantity: it.Quantity, Currency: it.PriceCurrency}) |
| + } |
| + return out, nil |
| +} |
| + |
| +// CheckoutSubscription is the subscription a checkout session made. |
| +func (p *Provider) CheckoutSubscription(ctx context.Context, checkoutID string) (string, error) { |
| + s, err := p.client.GetCheckout(ctx, checkoutID) |
| + if notFound(err) { |
| + return "", billing.ErrNotFound |
| + } |
| + if err != nil { |
| + return "", err |
| + } |
| + return s.SubscriptionID, nil |
| +} |
| + |
| +// Check is the readiness check. The credential belongs to the configured |
| +// account, and every price of the book the price map names is exactly what |
| +// the book says: active, in this mode and currency, at the book's amount, |
| +// yearly, licensed, per unit, tax exclusive, with no quantity transform, no |
| +// currency but its own, and its own key in metadata[price_key]. Each |
| +// price's product is active. The first failure is returned naming the key, |
| +// with no ids or amounts. |
| +func (p *Provider) Check(ctx context.Context, book *plans.PriceBook, prices billing.PriceMap) error { |
| + acct, err := p.client.MerchantAccount(ctx) |
| + if err != nil { |
| + return fmt.Errorf("billing check: reading the account: %w", err) |
| + } |
| + if acct != p.account { |
| + return errors.New("billing check: the secret key belongs to another account") |
| + } |
| + products := map[string]bool{} |
| + for _, ref := range prices.Refs(book.Version) { |
| + key := ref.Key() |
| + id, _ := prices.ID(ref) |
| + price, err := p.client.GetPrice(ctx, id) |
| + if err != nil { |
| + return fmt.Errorf("billing check: price %s: %w", key, err) |
| + } |
| + if why := p.priceProblem(price, ref, book); why != "" { |
| + return fmt.Errorf("billing check: price %s: %s", key, why) |
| + } |
| + if products[price.ProductID] { |
| + continue |
| + } |
| + product, err := p.client.GetProduct(ctx, price.ProductID) |
| + if err != nil { |
| + return fmt.Errorf("billing check: price %s: reading its product: %w", key, err) |
| + } |
| + if !product.Active || product.LiveMode != p.liveMode { |
| + return fmt.Errorf("billing check: price %s: its product is archived or in the other mode", key) |
| + } |
| + products[price.ProductID] = true |
| + } |
| + return nil |
| +} |
| + |
| +func (p *Provider) priceProblem(price *Price, ref billing.PriceRef, book *plans.PriceBook) string { |
| + var want int64 |
| + var ok bool |
| + if ref.Kind == billing.KindPack { |
| + want, ok = book.PackPrice(ref.Name, ref.Currency) |
| + } else { |
| + want, ok = book.PlanPrice(ref.Name, ref.Currency) |
| + } |
| + switch { |
| + case !ok: |
| + return "the book does not price it" |
| + case !price.Active: |
| + return "not active" |
| + case price.LiveMode != p.liveMode: |
| + return "in the other mode" |
| + case price.Currency != ref.Currency: |
| + return "in another currency" |
| + case price.UnitAmount != want: |
| + return "its amount is not the book's" |
| + case price.Recurring.Interval != "year" || price.Recurring.IntervalCount != 1: |
| + return "not billed once a year" |
| + case price.Recurring.UsageType != "licensed": |
| + return "not licensed" |
| + case price.BillingScheme != "per_unit": |
| + return "not per unit" |
| + case price.TaxBehavior != "exclusive": |
| + return "not tax exclusive" |
| + case len(price.TransformQuantity) > 0 && string(price.TransformQuantity) != "null": |
| + return "has a quantity transform" |
| + case !priceCurrencyOptionsAreOwn(price): |
| + return "has another currency option" |
| + case price.Metadata["price_key"] != ref.Key(): |
| + return "its metadata price_key is not its key" |
| + } |
| + return "" |
| +} |
| + |
| +// priceCurrencyOptionsAreOwn reports whether a price has no currency option |
| +// but its own. A price here is in one currency: a second currency on it |
| +// would let a session be presented and charged in that one. Stripe, asked |
| +// to expand currency_options, is understood to answer with the price's own |
| +// currency among them, so an entry under the price's currency, saying the |
| +// price's own amount and tax behaviour, is the price itself and not an |
| +// option. Which shape Stripe returns for a single-currency price is on the |
| +// test-mode rehearsal list; either passes, and a second currency never does. |
| +func priceCurrencyOptionsAreOwn(price *Price) bool { |
| + if len(price.CurrencyOptions) == 0 { |
| + return true |
| + } |
| + if len(price.CurrencyOptions) != 1 { |
| + return false |
| + } |
| + raw, ok := price.CurrencyOptions[price.Currency] |
| + if !ok { |
| + return false |
| + } |
| + var own struct { |
| + UnitAmount *int64 `json:"unit_amount"` |
| + TaxBehavior string `json:"tax_behavior"` |
| + } |
| + if err := json.Unmarshal(raw, &own); err != nil || own.UnitAmount == nil || *own.UnitAmount != price.UnitAmount { |
| + return false |
| + } |
| + return own.TaxBehavior == "" || own.TaxBehavior == price.TaxBehavior |
| +} |
diff --git a/internal/billingstripe/adapter_test.go b/internal/billingstripe/adapter_test.go| new file mode 100644 |
| index 000000000..8eea087af |
| --- /dev/null |
| +++ b/internal/billingstripe/adapter_test.go |
| @@ -0,0 +1,427 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/plans" |
| +) |
| + |
| +func TestStateOf(t *testing.T) { |
| + for status, want := range map[string]billing.State{ |
| + "active": billing.StatePaid, "trialing": billing.StatePaid, "past_due": billing.StatePaid, |
| + "incomplete": billing.StatePending, |
| + "canceled": billing.StateEnded, "incomplete_expired": billing.StateEnded, "unpaid": billing.StateEnded, |
| + "paused": billing.StateEnded, "weird": billing.StateEnded, "": billing.StateEnded, |
| + } { |
| + if got := stateOf(status); got != want { |
| + t.Errorf("stateOf(%q) = %q, want %q", status, got, want) |
| + } |
| + } |
| +} |
| + |
| +func testProvider(t *testing.T, base string, live bool, secrets ...string) *Provider { |
| + t.Helper() |
| + key := "rk_test_abc" |
| + if live { |
| + key = "rk_live_abc" |
| + } |
| + if len(secrets) == 0 { |
| + secrets = []string{"whsec_primary"} |
| + } |
| + p, err := NewProvider(ProviderConfig{SecretKey: key, Account: "acct_1", WebhookSecrets: secrets, LiveMode: live, BaseURL: base}) |
| + if err != nil { |
| + t.Fatalf("NewProvider: %v", err) |
| + } |
| + return p |
| +} |
| + |
| +func TestNewProviderRefuses(t *testing.T) { |
| + good := ProviderConfig{SecretKey: "rk_test_abc", Account: "acct_1", WebhookSecrets: []string{"whsec_a"}} |
| + for name, edit := range map[string]func(*ProviderConfig){ |
| + "full secret key": func(c *ProviderConfig) { c.SecretKey = "sk_test_abc" }, |
| + "live key in test": func(c *ProviderConfig) { c.SecretKey = "rk_live_abc" }, |
| + "test key in live": func(c *ProviderConfig) { c.LiveMode = true }, |
| + "no account": func(c *ProviderConfig) { c.Account = "" }, |
| + "bad account": func(c *ProviderConfig) { c.Account = "cus_1" }, |
| + "no secrets": func(c *ProviderConfig) { c.WebhookSecrets = nil }, |
| + "empty secret": func(c *ProviderConfig) { c.WebhookSecrets = []string{""} }, |
| + "four secrets": func(c *ProviderConfig) { c.WebhookSecrets = []string{"whsec_a", "whsec_b", "whsec_c", "whsec_d"} }, |
| + } { |
| + c := good |
| + edit(&c) |
| + if _, err := NewProvider(c); err == nil { |
| + t.Errorf("%s: accepted", name) |
| + } |
| + } |
| + if _, err := NewProvider(good); err != nil { |
| + t.Errorf("good config: %v", err) |
| + } |
| +} |
| + |
| +func TestProviderStringRedactsKey(t *testing.T) { |
| + p := testProvider(t, "http://127.0.0.1:1", false) |
| + for _, s := range []string{fmt.Sprint(p), fmt.Sprintf("%+v", p), fmt.Sprintf("%#v", p)} { |
| + if strings.Contains(s, "rk_test_abc") || strings.Contains(s, "whsec_primary") { |
| + t.Errorf("formatted provider leaks a secret: %s", s) |
| + } |
| + } |
| +} |
| + |
| +func signedEvent(t *testing.T, secret string, now time.Time, typ string, live bool, object string) ([]byte, http.Header) { |
| + t.Helper() |
| + payload := []byte(fmt.Sprintf(`{"id":"evt_1","type":%q,"created":%d,"livemode":%v,"data":{"object":%s}}`, typ, now.Unix(), live, object)) |
| + h := http.Header{} |
| + h.Set("Stripe-Signature", header(now.Unix(), sign(secret, now.Unix(), payload))) |
| + return payload, h |
| +} |
| + |
| +func TestParseEventKinds(t *testing.T) { |
| + now := time.Unix(1_800_000_000, 0) |
| + p := testProvider(t, "http://127.0.0.1:1", false, "whsec_primary", "whsec_previous") |
| + cases := []struct { |
| + typ, object string |
| + kind billing.EventKind |
| + want string |
| + }{ |
| + {"customer.subscription.created", `{"id":"sub_1","object":"subscription"}`, billing.EventSubscription, "sub_1"}, |
| + {"customer.subscription.updated", `{"id":"sub_2"}`, billing.EventSubscription, "sub_2"}, |
| + {"customer.subscription.deleted", `{"id":"sub_3"}`, billing.EventSubscription, "sub_3"}, |
| + {"invoice.paid", `{"id":"in_1","subscription":"sub_4"}`, billing.EventSubscription, "sub_4"}, |
| + {"invoice.payment_failed", `{"id":"in_2","subscription":"sub_5"}`, billing.EventSubscription, "sub_5"}, |
| + {"invoice.paid", `{"id":"in_3","subscription":{"id":"sub_6","object":"subscription"}}`, billing.EventSubscription, "sub_6"}, |
| + {"invoice.paid", `{"id":"in_4","subscription":null}`, billing.EventIgnored, ""}, |
| + {"invoice.payment_failed", `{"id":"in_5"}`, billing.EventIgnored, ""}, |
| + {"checkout.session.completed", `{"id":"cs_1"}`, billing.EventCheckout, "cs_1"}, |
| + {"charge.refunded", `{"id":"ch_1"}`, billing.EventIgnored, ""}, |
| + } |
| + for _, tc := range cases { |
| + raw, h := signedEvent(t, "whsec_primary", now, tc.typ, false, tc.object) |
| + ev, err := p.ParseEvent(raw, h, now) |
| + if err != nil { |
| + t.Errorf("%s %s: %v", tc.typ, tc.object, err) |
| + continue |
| + } |
| + if ev.Kind != tc.kind || ev.Object != tc.want || ev.ID != "evt_1" || ev.LiveMode { |
| + t.Errorf("%s %s: got %+v, want kind %s object %q", tc.typ, tc.object, ev, tc.kind, tc.want) |
| + } |
| + } |
| + |
| + // Signed with the previous secret: accepted during rotation. |
| + raw, h := signedEvent(t, "whsec_previous", now, "customer.subscription.updated", true, `{"id":"sub_7"}`) |
| + if ev, err := p.ParseEvent(raw, h, now); err != nil || ev.Object != "sub_7" || !ev.LiveMode { |
| + t.Errorf("previous secret: %+v, %v", ev, err) |
| + } |
| + |
| + // Refusals are all ErrBadEvent. |
| + bad := map[string]func() ([]byte, http.Header){ |
| + "wrong secret": func() ([]byte, http.Header) { |
| + return signedEvent(t, "whsec_other", now, "customer.subscription.updated", false, `{"id":"sub_1"}`) |
| + }, |
| + "no header": func() ([]byte, http.Header) { |
| + raw, _ := signedEvent(t, "whsec_primary", now, "customer.subscription.updated", false, `{"id":"sub_1"}`) |
| + return raw, http.Header{} |
| + }, |
| + "stale": func() ([]byte, http.Header) { |
| + return signedEvent(t, "whsec_primary", now.Add(-time.Hour), "customer.subscription.updated", false, `{"id":"sub_1"}`) |
| + }, |
| + "subscription id with a slash": func() ([]byte, http.Header) { |
| + return signedEvent(t, "whsec_primary", now, "customer.subscription.updated", false, `{"id":"../sub_1"}`) |
| + }, |
| + "subscription with no id": func() ([]byte, http.Header) { |
| + return signedEvent(t, "whsec_primary", now, "customer.subscription.updated", false, `{"object":"subscription"}`) |
| + }, |
| + "checkout with a bad id": func() ([]byte, http.Header) { |
| + return signedEvent(t, "whsec_primary", now, "checkout.session.completed", false, `{"id":"cs 1"}`) |
| + }, |
| + } |
| + for name, mk := range bad { |
| + raw, h := mk() |
| + if _, err := p.ParseEvent(raw, h, now); !errors.Is(err, billing.ErrBadEvent) { |
| + t.Errorf("%s: err = %v, want ErrBadEvent", name, err) |
| + } |
| + } |
| + // A previously separate adversarial case: a timestamp centuries ahead. |
| + raw, h = signedEvent(t, "whsec_primary", now.AddDate(400, 0, 0), "invoice.paid", false, `{"id":"in_1","subscription":"sub_1"}`) |
| + if _, err := p.ParseEvent(raw, h, now); !errors.Is(err, billing.ErrBadEvent) { |
| + t.Errorf("future timestamp: err = %v", err) |
| + } |
| +} |
| + |
| +func TestSubscriptionMapsFields(t *testing.T) { |
| + end := time.Date(2027, 10, 25, 12, 0, 0, 0, time.UTC) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch r.URL.Path { |
| + case "/v1/subscriptions/sub_1": |
| + fmt.Fprintf(w, `{"id":"sub_1","customer":"cus_1","status":"past_due","livemode":false,"currency":"usd", |
| + "current_period_end":%d,"cancel_at_period_end":true,"metadata":{"account_sqid":"bab"}, |
| + "items":{"has_more":false,"data":[ |
| + {"id":"si_1","quantity":1,"price":{"id":"price_p","currency":"usd"}}, |
| + {"id":"si_2","quantity":3,"price":{"id":"price_a","currency":"usd"}}]}}`, end.Unix()) |
| + case "/v1/subscriptions/sub_more": |
| + fmt.Fprint(w, `{"id":"sub_more","customer":"cus_1","status":"active","livemode":false,"currency":"usd","items":{"has_more":true,"data":[]}}`) |
| + default: |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprint(w, `{"error":{"type":"invalid_request_error","code":"resource_missing"}}`) |
| + } |
| + })) |
| + defer srv.Close() |
| + p := testProvider(t, srv.URL, false) |
| + |
| + sub, err := p.Subscription(context.Background(), "sub_1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := billing.Subscription{ |
| + ID: "sub_1", Customer: "cus_1", Account: "bab", ProviderStatus: "past_due", State: billing.StatePaid, |
| + Currency: "usd", LiveMode: false, PeriodEnd: end, CancelAtPeriodEnd: true, ItemsComplete: true, |
| + Items: []billing.Item{{PriceID: "price_p", Quantity: 1, Currency: "usd"}, {PriceID: "price_a", Quantity: 3, Currency: "usd"}}, |
| + } |
| + got, _ := json.Marshal(sub) |
| + exp, _ := json.Marshal(want) |
| + if string(got) != string(exp) { |
| + t.Errorf("Subscription =\n %s\nwant\n %s", got, exp) |
| + } |
| + more, err := p.Subscription(context.Background(), "sub_more") |
| + if err != nil || more.ItemsComplete { |
| + t.Errorf("has_more: ItemsComplete = %v, %v", more != nil && more.ItemsComplete, err) |
| + } |
| + if _, err := p.Subscription(context.Background(), "sub_gone"); !errors.Is(err, billing.ErrNotFound) { |
| + t.Errorf("404: err = %v, want ErrNotFound", err) |
| + } |
| + if _, err := p.Subscription(context.Background(), "../x"); err == nil || errors.Is(err, billing.ErrNotFound) { |
| + t.Errorf("bad id: err = %v", err) |
| + } |
| +} |
| + |
| +func TestCheckoutSubscription(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch r.URL.Path { |
| + case "/v1/checkout/sessions/cs_1": |
| + fmt.Fprint(w, `{"id":"cs_1","livemode":false,"subscription":{"id":"sub_9","customer":"cus_1","status":"active","livemode":false}}`) |
| + case "/v1/checkout/sessions/cs_none": |
| + fmt.Fprint(w, `{"id":"cs_none","livemode":false,"subscription":null}`) |
| + default: |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprint(w, `{"error":{"type":"invalid_request_error"}}`) |
| + } |
| + })) |
| + defer srv.Close() |
| + p := testProvider(t, srv.URL, false) |
| + if id, err := p.CheckoutSubscription(context.Background(), "cs_1"); err != nil || id != "sub_9" { |
| + t.Errorf("cs_1 = %q, %v", id, err) |
| + } |
| + if id, err := p.CheckoutSubscription(context.Background(), "cs_none"); err != nil || id != "" { |
| + t.Errorf("cs_none = %q, %v", id, err) |
| + } |
| + if _, err := p.CheckoutSubscription(context.Background(), "cs_gone"); !errors.Is(err, billing.ErrNotFound) { |
| + t.Errorf("404: %v", err) |
| + } |
| +} |
| + |
| +// fakeStripe answers the readiness check's reads from in-memory prices. |
| +type fakeStripe struct { |
| + mu sync.Mutex |
| + account string |
| + prices map[string]map[string]any // price id -> JSON object |
| + products map[string]map[string]any |
| + reads int |
| +} |
| + |
| +func (f *fakeStripe) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.reads++ |
| + var obj any |
| + switch { |
| + case r.URL.Path == "/v1/account": |
| + obj = map[string]any{"id": f.account} |
| + case strings.HasPrefix(r.URL.Path, "/v1/prices/"): |
| + if p, ok := f.prices[strings.TrimPrefix(r.URL.Path, "/v1/prices/")]; ok { |
| + obj = p |
| + } |
| + case strings.HasPrefix(r.URL.Path, "/v1/products/"): |
| + if p, ok := f.products[strings.TrimPrefix(r.URL.Path, "/v1/products/")]; ok { |
| + obj = p |
| + } |
| + } |
| + if obj == nil { |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprint(w, `{"error":{"type":"invalid_request_error","code":"resource_missing"}}`) |
| + return |
| + } |
| + _ = json.NewEncoder(w).Encode(obj) |
| +} |
| + |
| +var nonAlnum = regexp.MustCompile(`[^A-Za-z0-9]`) |
| + |
| +func checkFixture(t *testing.T) (*plans.PriceBook, billing.PriceMap, *fakeStripe) { |
| + t.Helper() |
| + cat, err := plans.LoadCatalog("../plans/testdata/example-catalog.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + book, err := plans.LoadPriceBook("../plans/testdata/example-pricebook.json", cat) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw := map[string]string{} |
| + fs := &fakeStripe{account: "acct_1", prices: map[string]map[string]any{}, products: map[string]map[string]any{}} |
| + add := func(r billing.PriceRef, amount int64) { |
| + id := "price_" + nonAlnum.ReplaceAllString(r.Key(), "") |
| + prod := "prod_" + r.Kind + r.Name |
| + raw[r.Key()] = id |
| + fs.prices[id] = map[string]any{ |
| + "id": id, "object": "price", "active": true, "livemode": false, "currency": r.Currency, |
| + "unit_amount": amount, "product": prod, "tax_behavior": "exclusive", "billing_scheme": "per_unit", |
| + "transform_quantity": nil, "metadata": map[string]string{"price_key": r.Key()}, |
| + "recurring": map[string]any{"interval": "year", "interval_count": 1, "usage_type": "licensed"}, |
| + "currency_options": map[string]any{r.Currency: map[string]any{"unit_amount": amount, "tax_behavior": "exclusive"}}, |
| + } |
| + fs.products[prod] = map[string]any{"id": prod, "active": true, "livemode": false} |
| + } |
| + for plan, byCur := range book.Plans { |
| + for cur, amount := range byCur { |
| + add(billing.PriceRef{Book: book.Version, Kind: billing.KindPlan, Name: plan, Currency: cur}, amount) |
| + } |
| + } |
| + for pack, byCur := range book.Packs { |
| + for cur, amount := range byCur { |
| + add(billing.PriceRef{Book: book.Version, Kind: billing.KindPack, Name: pack, Currency: cur}, amount) |
| + } |
| + } |
| + b, _ := json.Marshal(raw) |
| + pm, err := billing.ParsePriceMap(string(b), book) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return book, pm, fs |
| +} |
| + |
| +func TestCheckRefusesMismatchedPrices(t *testing.T) { |
| + const key = "example-v1/pack/apps/usd" |
| + const id = "price_examplev1packappsusd" |
| + cases := map[string]func(f *fakeStripe){ |
| + "inactive": func(f *fakeStripe) { f.prices[id]["active"] = false }, |
| + "wrong mode": func(f *fakeStripe) { f.prices[id]["livemode"] = true }, |
| + "wrong currency": func(f *fakeStripe) { f.prices[id]["currency"] = "eur" }, |
| + "amount off by 1": func(f *fakeStripe) { f.prices[id]["unit_amount"] = 601 }, |
| + "monthly": func(f *fakeStripe) { f.prices[id]["recurring"].(map[string]any)["interval"] = "month" }, |
| + "every two years": func(f *fakeStripe) { f.prices[id]["recurring"].(map[string]any)["interval_count"] = 2 }, |
| + "metered": func(f *fakeStripe) { f.prices[id]["recurring"].(map[string]any)["usage_type"] = "metered" }, |
| + "not recurring": func(f *fakeStripe) { delete(f.prices[id], "recurring") }, |
| + "tiered": func(f *fakeStripe) { f.prices[id]["billing_scheme"] = "tiered" }, |
| + "tax inclusive": func(f *fakeStripe) { f.prices[id]["tax_behavior"] = "inclusive" }, |
| + "transform quantity": func(f *fakeStripe) { |
| + f.prices[id]["transform_quantity"] = map[string]any{"divide_by": 2, "round": "up"} |
| + }, |
| + "a second currency": func(f *fakeStripe) { |
| + f.prices[id]["currency_options"].(map[string]any)["eur"] = map[string]any{"unit_amount": 500} |
| + }, |
| + "own option disagrees": func(f *fakeStripe) { |
| + f.prices[id]["currency_options"].(map[string]any)["usd"] = map[string]any{"unit_amount": 700} |
| + }, |
| + "price_key of another": func(f *fakeStripe) { |
| + f.prices[id]["metadata"] = map[string]string{"price_key": "example-v1/pack/email/usd"} |
| + }, |
| + "no price_key": func(f *fakeStripe) { f.prices[id]["metadata"] = map[string]string{} }, |
| + "archived product": func(f *fakeStripe) { f.products["prod_packapps"]["active"] = false }, |
| + "missing price": func(f *fakeStripe) { delete(f.prices, id) }, |
| + "wrong account": func(f *fakeStripe) { f.account = "acct_2" }, |
| + } |
| + for name, edit := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + book, pm, fs := checkFixture(t) |
| + edit(fs) |
| + srv := httptest.NewServer(fs) |
| + defer srv.Close() |
| + err := testProvider(t, srv.URL, false).Check(context.Background(), book, pm) |
| + if err == nil { |
| + t.Fatal("accepted") |
| + } |
| + want := key |
| + if name == "archived product" { // every apps price shares the product: the first in key order is named |
| + want = "example-v1/pack/apps/" |
| + } |
| + if name != "wrong account" && !strings.Contains(err.Error(), want) { |
| + t.Errorf("error %q does not name %s", err, want) |
| + } |
| + if strings.Contains(err.Error(), id) || strings.Contains(err.Error(), "601") || strings.Contains(err.Error(), "prod_") { |
| + t.Errorf("error %q carries an id or amount", err) |
| + } |
| + }) |
| + } |
| + book, pm, fs := checkFixture(t) |
| + srv := httptest.NewServer(fs) |
| + defer srv.Close() |
| + if err := testProvider(t, srv.URL, false).Check(context.Background(), book, pm); err != nil { |
| + t.Fatalf("all good: %v", err) |
| + } |
| + // Request budget: the account, each price, each distinct product. |
| + if fs.reads > 1+15+5 { |
| + t.Errorf("check made %d reads", fs.reads) |
| + } |
| +} |
| + |
| +func TestCreateCheckoutSendsItems(t *testing.T) { |
| + var form map[string][]string |
| + var idem string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = r.ParseForm() |
| + form = r.PostForm |
| + idem = r.Header.Get("Idempotency-Key") |
| + fmt.Fprint(w, `{"id":"cs_1","url":"https://checkout.stripe.com/c/pay/cs_1","status":"open","livemode":false,"currency":"usd"}`) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.CreateCheckout(context.Background(), CreateCheckoutParams{ |
| + Items: []LineItem{{PriceID: "price_p", Quantity: 1}, {PriceID: "price_a", Quantity: 2}}, |
| + SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", CustomerID: "cus_1", Currency: "usd", |
| + Metadata: CheckoutMetadata{AccountSqid: "bab", IntentID: "intent_1", PriceBook: "example-v1", Currency: "usd"}, |
| + }, "idem-1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for k, v := range map[string]string{ |
| + "line_items[0][price]": "price_p", "line_items[0][quantity]": "1", |
| + "line_items[1][price]": "price_a", "line_items[1][quantity]": "2", |
| + "adaptive_pricing[enabled]": "false", "currency": "usd", |
| + "metadata[account_sqid]": "bab", "metadata[price_book]": "example-v1", "metadata[currency]": "usd", "metadata[checkout_intent]": "intent_1", |
| + "subscription_data[metadata][account_sqid]": "bab", "subscription_data[metadata][price_book]": "example-v1", |
| + } { |
| + if got := form[k]; len(got) != 1 || got[0] != v { |
| + t.Errorf("form[%q] = %v, want %q", k, got, v) |
| + } |
| + } |
| + for _, k := range []string{"metadata[terms_version]", "metadata[plan]", "metadata[band]", "line_items[2][price]"} { |
| + if _, ok := form[k]; ok { |
| + t.Errorf("form carries %q", k) |
| + } |
| + } |
| + if idem != "idem-1" { |
| + t.Errorf("Idempotency-Key = %q", idem) |
| + } |
| + for name, items := range map[string][]LineItem{ |
| + "no items": nil, |
| + "zero": {{PriceID: "price_p", Quantity: 0}}, |
| + "bad price id": {{PriceID: "price p", Quantity: 1}}, |
| + } { |
| + _, err := c.CreateCheckout(context.Background(), CreateCheckoutParams{ |
| + Items: items, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", CustomerID: "cus_1", Currency: "usd", |
| + Metadata: CheckoutMetadata{AccountSqid: "bab", IntentID: "intent_1", PriceBook: "example-v1", Currency: "usd"}, |
| + }, "idem-2") |
| + if err == nil { |
| + t.Errorf("%s: accepted", name) |
| + } |
| + } |
| +} |
diff --git a/internal/billingstripe/catalog.go b/internal/billingstripe/catalog.go| new file mode 100644 |
| index 000000000..159b68334 |
| --- /dev/null |
| +++ b/internal/billingstripe/catalog.go |
| @@ -0,0 +1,287 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "strconv" |
| +) |
| + |
| +func safeErrorEnum(value string) string { |
| + switch value { |
| + case "customer_tax_location_invalid", "api_error", "card_error", "idempotency_error", "invalid_request_error", "rate_limit_error", "authentication_error", "card_declined", "resource_missing", "parameter_invalid_integer", "parameter_missing", "idempotency_key_in_use": |
| + return value |
| + default: |
| + return "" |
| + } |
| +} |
| + |
| +// safeErrorParam is safeErrorEnum for the error's "param": only the |
| +// parameter names a caller acts on are kept, so nothing else from the |
| +// provider's response body travels with the error. |
| +func safeErrorParam(value string) string { |
| + switch value { |
| + case "proration_date", "quantity": |
| + return value |
| + default: |
| + return "" |
| + } |
| +} |
| + |
| +type Price struct { |
| + ProductID string |
| + CurrencyOptions map[string]json.RawMessage |
| + ID string |
| + Active bool |
| + LiveMode bool |
| + Currency string |
| + UnitAmount int64 |
| + TaxBehavior string |
| + BillingScheme string |
| + TransformQuantity json.RawMessage |
| + Metadata map[string]string |
| + Recurring struct { |
| + Interval string `json:"interval"` |
| + IntervalCount int64 `json:"interval_count"` |
| + UsageType string `json:"usage_type"` |
| + } |
| +} |
| + |
| +// UnmarshalJSON decodes a Price strictly enough that a null response body, |
| +// or one missing "id" or "livemode", cannot pass. Both fields decode |
| +// through pointers specifically so a caller can tell "absent" from "present |
| +// and zero": a naive struct would decode a null object into LiveMode=false, |
| +// which reads as test mode when the response in fact proved nothing at all. |
| +func (p *Price) UnmarshalJSON(b []byte) error { |
| + var raw struct { |
| + ProductID string `json:"product"` |
| + CurrencyOptions map[string]json.RawMessage `json:"currency_options"` |
| + ID *string `json:"id"` |
| + Active bool `json:"active"` |
| + LiveMode *bool `json:"livemode"` |
| + Currency string `json:"currency"` |
| + UnitAmount int64 `json:"unit_amount"` |
| + TaxBehavior string `json:"tax_behavior"` |
| + BillingScheme string `json:"billing_scheme"` |
| + TransformQuantity json.RawMessage `json:"transform_quantity"` |
| + Metadata map[string]string `json:"metadata"` |
| + Recurring struct { |
| + Interval string `json:"interval"` |
| + IntervalCount int64 `json:"interval_count"` |
| + UsageType string `json:"usage_type"` |
| + } `json:"recurring"` |
| + } |
| + if err := json.Unmarshal(b, &raw); err != nil { |
| + return err |
| + } |
| + if raw.ID == nil || *raw.ID == "" || raw.LiveMode == nil { |
| + return errors.New("billingstripe: price response missing id or livemode") |
| + } |
| + if !validID(*raw.ID) { |
| + return errors.New("billingstripe: price id has unexpected shape") |
| + } |
| + *p = Price{} |
| + p.ProductID = raw.ProductID |
| + p.CurrencyOptions = raw.CurrencyOptions |
| + p.ID = *raw.ID |
| + p.Active = raw.Active |
| + p.LiveMode = *raw.LiveMode |
| + p.Currency = raw.Currency |
| + p.UnitAmount = raw.UnitAmount |
| + p.TaxBehavior = raw.TaxBehavior |
| + p.BillingScheme = raw.BillingScheme |
| + p.TransformQuantity = raw.TransformQuantity |
| + p.Metadata = raw.Metadata |
| + p.Recurring = raw.Recurring |
| + return nil |
| +} |
| + |
| +func (c *Client) GetPrice(ctx context.Context, id string) (*Price, error) { |
| + if !validID(id) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + var x Price |
| + if err := c.do(ctx, http.MethodGet, "/v1/prices/"+id, url.Values{"expand[]": {"currency_options"}}, "", &x); err != nil { |
| + return nil, err |
| + } |
| + return &x, nil |
| +} |
| + |
| +type TaxRegistration struct { |
| + ID string `json:"id"` |
| + Country string `json:"country"` |
| + Status string `json:"status"` |
| + ActiveFrom int64 `json:"active_from"` |
| + CountryOptions map[string]struct { |
| + Type string `json:"type"` |
| + } `json:"country_options"` |
| +} |
| + |
| +func (c *Client) ListCheckouts(ctx context.Context, createdAfter, createdBefore int64) ([]Session, error) { |
| + return c.listCheckouts(ctx, "", createdAfter, createdBefore) |
| +} |
| + |
| +// ListCheckoutsForCustomer lists only the Checkout Sessions belonging to one |
| +// Stripe customer, within a bounded creation window. The billing reconciler |
| +// uses it to recover a single intent's lost checkout without ever opening a |
| +// global, ever-growing window over every account's sessions. |
| +func (c *Client) ListCheckoutsForCustomer(ctx context.Context, customerID string, createdAfter, createdBefore int64) ([]Session, error) { |
| + if !validID(customerID) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + return c.listCheckouts(ctx, customerID, createdAfter, createdBefore) |
| +} |
| + |
| +func (c *Client) listCheckouts(ctx context.Context, customerID string, createdAfter, createdBefore int64) ([]Session, error) { |
| + if createdAfter < 0 || createdBefore < createdAfter { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + var out []Session |
| + after := "" |
| + seen := map[string]bool{} |
| + for { |
| + q := url.Values{"limit": {"100"}, "created[gte]": {strconv.FormatInt(createdAfter, 10)}, "created[lte]": {strconv.FormatInt(createdBefore, 10)}} |
| + if customerID != "" { |
| + q.Set("customer", customerID) |
| + } |
| + if after != "" { |
| + q.Set("starting_after", after) |
| + } |
| + var page struct { |
| + Data []json.RawMessage `json:"data"` |
| + HasMore bool `json:"has_more"` |
| + } |
| + // A listing that fails after its first page returns, with the |
| + // error, the sessions of the pages it did read: each of those was |
| + // a provider answer, and a caller that records what it reads must |
| + // not lose them to a later page's failure. A caller that wants a |
| + // whole listing checks the error, as before. |
| + if err := c.do(ctx, http.MethodGet, "/v1/checkout/sessions", q, "", &page); err != nil { |
| + return out, err |
| + } |
| + // Each session on the page is decoded on its own: one that does |
| + // not decode fails the listing, and the ones that did decode are |
| + // still returned with that error. A page that repeats a session, |
| + // or carries one with no usable id, is broken pagination and the |
| + // listing is refused the same way, with what the page did say: a |
| + // session seen twice is two answers about it, and the second may |
| + // differ. |
| + var pageErr error |
| + lastID := "" |
| + for _, raw := range page.Data { |
| + var session Session |
| + if err := json.Unmarshal(raw, &session); err != nil { |
| + pageErr = &Error{Code: CodeDecodeError, HTTPStatus: http.StatusOK} |
| + continue |
| + } |
| + if !validID(session.ID) { |
| + if pageErr == nil { |
| + pageErr = &Error{Code: CodeBrokenPagination} |
| + } |
| + continue |
| + } |
| + if seen[session.ID] && pageErr == nil { |
| + pageErr = &Error{Code: CodeBrokenPagination} |
| + } |
| + seen[session.ID] = true |
| + out = append(out, session) |
| + lastID = session.ID |
| + } |
| + if pageErr != nil { |
| + return out, pageErr |
| + } |
| + if len(out) > 10000 { |
| + return out, &Error{Code: CodeTooManyRecords} |
| + } |
| + if !page.HasMore { |
| + return out, nil |
| + } |
| + if len(page.Data) == 0 { |
| + return out, &Error{Code: CodeBrokenPagination} |
| + } |
| + after = lastID |
| + } |
| +} |
| + |
| +func (c *Client) ActiveTaxRegistrations(ctx context.Context) ([]TaxRegistration, error) { |
| + var page struct { |
| + Data []TaxRegistration `json:"data"` |
| + HasMore bool `json:"has_more"` |
| + } |
| + if err := c.do(ctx, http.MethodGet, "/v1/tax/registrations", url.Values{"status": {"active"}, "limit": {"100"}}, "", &page); err != nil { |
| + return nil, err |
| + } |
| + if page.HasMore { |
| + return nil, &Error{Code: CodeTooManyRecords} |
| + } |
| + return page.Data, nil |
| +} |
| + |
| +// Coupon is a Stripe coupon trimmed to what the house-account flow must |
| +// prove before it is ever attached to a Checkout Session: that it is a |
| +// live-mode, still-valid, 100%-off-forever discount that carries no fixed |
| +// amount and, if it restricts the products it applies to, includes the |
| +// product being purchased. Anything less would let a coupon that charges |
| +// the house account at renewal (a "once" duration, or a percent below 100) |
| +// slip through unnoticed. |
| +type Coupon struct { |
| + ID string |
| + Valid bool |
| + LiveMode bool |
| + PercentOff *float64 |
| + AmountOff *int64 |
| + Duration string |
| + AppliesToProducts []string |
| +} |
| + |
| +func (cp *Coupon) UnmarshalJSON(b []byte) error { |
| + var raw struct { |
| + ID *string `json:"id"` |
| + Valid *bool `json:"valid"` |
| + LiveMode *bool `json:"livemode"` |
| + PercentOff *float64 `json:"percent_off"` |
| + AmountOff *int64 `json:"amount_off"` |
| + Duration string `json:"duration"` |
| + AppliesTo *struct { |
| + Products []string `json:"products"` |
| + } `json:"applies_to"` |
| + } |
| + if err := json.Unmarshal(b, &raw); err != nil { |
| + return err |
| + } |
| + if raw.ID == nil || *raw.ID == "" || raw.LiveMode == nil || raw.Valid == nil { |
| + return errors.New("billingstripe: coupon response missing id, valid or livemode") |
| + } |
| + if !validID(*raw.ID) { |
| + return errors.New("billingstripe: coupon id has unexpected shape") |
| + } |
| + *cp = Coupon{} |
| + cp.ID = *raw.ID |
| + cp.Valid = *raw.Valid |
| + cp.LiveMode = *raw.LiveMode |
| + cp.PercentOff = raw.PercentOff |
| + cp.AmountOff = raw.AmountOff |
| + cp.Duration = raw.Duration |
| + if raw.AppliesTo != nil { |
| + cp.AppliesToProducts = raw.AppliesTo.Products |
| + } |
| + return nil |
| +} |
| + |
| +// GetCoupon reads one coupon, with applies_to expanded so a product-limited |
| +// coupon's product list is available in the same call. |
| +func (c *Client) GetCoupon(ctx context.Context, id string) (*Coupon, error) { |
| + if !validID(id) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + var cp Coupon |
| + if err := c.do(ctx, http.MethodGet, "/v1/coupons/"+id, nil, "", &cp); err != nil { |
| + return nil, err |
| + } |
| + if cp.ID != id { |
| + return nil, &Error{Code: CodeDecodeError} |
| + } |
| + return &cp, nil |
| +} |
diff --git a/internal/billingstripe/catalog_test.go b/internal/billingstripe/catalog_test.go| new file mode 100644 |
| index 000000000..c59efbeac |
| --- /dev/null |
| +++ b/internal/billingstripe/catalog_test.go |
| @@ -0,0 +1,743 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| +) |
| + |
| +// --- GetPrice: path, method, headers, decoding --- |
| + |
| +func TestGetPrice_PathMethodAndHeaders(t *testing.T) { |
| + var gotMethod, gotPath string |
| + var gotHeader http.Header |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotMethod = r.Method |
| + gotPath = r.URL.Path |
| + gotHeader = r.Header.Clone() |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "price_123", "currency": "usd", "livemode": false}) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + if _, err := c.GetPrice(context.Background(), "price_123"); err != nil { |
| + t.Fatalf("GetPrice: %v", err) |
| + } |
| + if gotMethod != http.MethodGet { |
| + t.Errorf("method = %q, want GET", gotMethod) |
| + } |
| + if gotPath != "/v1/prices/price_123" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + if got := gotHeader.Get("Authorization"); got != "Bearer rk_test_123" { |
| + t.Errorf("Authorization = %q", got) |
| + } |
| + if got := gotHeader.Get("Stripe-Version"); got != apiVersion { |
| + t.Errorf("Stripe-Version = %q, want %q", got, apiVersion) |
| + } |
| + if got := gotHeader.Get("Idempotency-Key"); got != "" { |
| + t.Errorf("GET must not carry Idempotency-Key, got %q", got) |
| + } |
| +} |
| + |
| +func TestGetPrice_RejectsInvalidID(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + for _, id := range []string{"../../../etc/passwd", "price_1/../../v1/customers", "price 1", "", strings.Repeat("a", 256)} { |
| + _, err := c.GetPrice(context.Background(), id) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidID { |
| + t.Errorf("id %q: err = %v, want CodeInvalidID", id, err) |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestGetPrice_DecodesFullFieldSet(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "price_1", "active": true, "livemode": true, "currency": "usd", |
| + "unit_amount": 1999, "tax_behavior": "exclusive", "billing_scheme": "per_unit", |
| + "transform_quantity": map[string]any{"divide_by": 5, "round": "up"}, |
| + "metadata": map[string]string{"band": "A"}, |
| + "recurring": map[string]any{"interval": "month", "interval_count": 1, "usage_type": "licensed"}, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + p, err := c.GetPrice(context.Background(), "price_1") |
| + if err != nil { |
| + t.Fatalf("GetPrice: %v", err) |
| + } |
| + if !p.Active || !p.LiveMode || p.Currency != "usd" || p.UnitAmount != 1999 { |
| + t.Fatalf("unexpected price: %+v", p) |
| + } |
| + if p.TaxBehavior != "exclusive" || p.BillingScheme != "per_unit" { |
| + t.Fatalf("unexpected price: %+v", p) |
| + } |
| + if p.Recurring.Interval != "month" || p.Recurring.IntervalCount != 1 || p.Recurring.UsageType != "licensed" { |
| + t.Fatalf("unexpected recurring: %+v", p.Recurring) |
| + } |
| + if p.Metadata["band"] != "A" { |
| + t.Fatalf("unexpected metadata: %+v", p.Metadata) |
| + } |
| + if !strings.Contains(string(p.TransformQuantity), `"divide_by":5`) { |
| + t.Fatalf("TransformQuantity not preserved raw: %s", p.TransformQuantity) |
| + } |
| +} |
| + |
| +func TestGetPrice_NullRecurringMetadataTransformQuantity(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "price_1", "currency": "usd", "livemode": true, |
| + "recurring": nil, "metadata": nil, "transform_quantity": nil, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + p, err := c.GetPrice(context.Background(), "price_1") |
| + if err != nil { |
| + t.Fatalf("GetPrice with null sub-objects: %v", err) |
| + } |
| + if p.Recurring.Interval != "" || p.Recurring.IntervalCount != 0 { |
| + t.Errorf("Recurring should be zero value on null, got %+v", p.Recurring) |
| + } |
| + if p.Metadata != nil { |
| + t.Errorf("Metadata should be nil on null, got %+v", p.Metadata) |
| + } |
| + if p.TransformQuantity != nil && string(p.TransformQuantity) != "null" { |
| + t.Errorf("TransformQuantity = %s, want nil or literal null", p.TransformQuantity) |
| + } |
| +} |
| + |
| +func TestGetPrice_PassesThroughUnexpectedCurrencyAndFalseLiveMode(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "price_1", "currency": "not-a-real-currency", "livemode": false, "active": false, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + p, err := c.GetPrice(context.Background(), "price_1") |
| + if err != nil { |
| + t.Fatalf("GetPrice: %v", err) |
| + } |
| + if p.Currency != "not-a-real-currency" { |
| + t.Errorf("Currency = %q, want pass-through of unrecognized value", p.Currency) |
| + } |
| + if p.LiveMode { |
| + t.Errorf("LiveMode = true, want false") |
| + } |
| +} |
| + |
| +func TestGetPrice_APIErrorDoesNotLeakProviderMessage(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusNotFound) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "error": map[string]any{ |
| + "type": "invalid_request_error", "code": "resource_missing", |
| + "message": "No such price: 'price_1' for account acct_secret123 owned by jane@example.com", |
| + "param": "id", |
| + }, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetPrice(context.Background(), "price_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeAPIError { |
| + t.Fatalf("err = %v, want CodeAPIError", err) |
| + } |
| + msg := e.Error() |
| + for _, secret := range []string{"acct_secret123", "jane@example.com", "rk_test_123", "param", "No such price"} { |
| + if strings.Contains(msg, secret) { |
| + t.Fatalf("Error() leaked %q: %s", secret, msg) |
| + } |
| + } |
| +} |
| + |
| +func TestGetPrice_MalformedJSONBodyIsDecodeErrorNotCrash(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusOK) |
| + _, _ = w.Write([]byte("not json at all {{{")) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetPrice(context.Background(), "price_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| + if strings.Contains(e.Error(), "not json at all") { |
| + t.Fatalf("Error() leaked raw body: %s", e.Error()) |
| + } |
| +} |
| + |
| +// --- Strict decode: Price rejects null / missing / invalid id / missing livemode --- |
| + |
| +func TestPriceUnmarshalJSON_Strictness(t *testing.T) { |
| + if err := json.Unmarshal([]byte(`{"id":"price_1","livemode":false}`), &Price{}); err != nil { |
| + t.Fatalf("valid price with explicit livemode:false: %v", err) |
| + } |
| + cases := map[string]string{ |
| + "null body": `null`, |
| + "missing id": `{"livemode":false}`, |
| + "empty id": `{"id":"","livemode":false}`, |
| + "invalid id shape": `{"id":"price 1","livemode":false}`, |
| + "path traversal id": `{"id":"../../v1/customers","livemode":false}`, |
| + "missing livemode": `{"id":"price_1"}`, |
| + "null livemode": `{"id":"price_1","livemode":null}`, |
| + } |
| + for name, body := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + var p Price |
| + if err := json.Unmarshal([]byte(body), &p); err == nil { |
| + t.Fatalf("%s: expected error, got price %+v", name, p) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPriceUnmarshalJSON_ResetsStaleFieldsWhenAbsent(t *testing.T) { |
| + p := Price{ |
| + ProductID: "prod_old", |
| + CurrencyOptions: map[string]json.RawMessage{"usd": json.RawMessage(`{"unit_amount":100}`)}, |
| + } |
| + minimal := `{"id":"price_1","livemode":true}` |
| + if err := json.Unmarshal([]byte(minimal), &p); err != nil { |
| + t.Fatalf("decode: %v", err) |
| + } |
| + if p.ProductID != "" { |
| + t.Errorf("ProductID = %q, want cleared (absent in this response)", p.ProductID) |
| + } |
| + if p.CurrencyOptions != nil { |
| + t.Errorf("CurrencyOptions = %+v, want nil (absent in this response)", p.CurrencyOptions) |
| + } |
| +} |
| + |
| +// --- ListCheckouts: query shape, pagination, bounds --- |
| + |
| +func TestListCheckouts_QueryShapeFirstPage(t *testing.T) { |
| + var gotQuery map[string][]string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotQuery = map[string][]string(r.URL.Query()) |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}, "has_more": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + if _, err := c.ListCheckouts(context.Background(), 1000, 2000); err != nil { |
| + t.Fatalf("ListCheckouts: %v", err) |
| + } |
| + if got := gotQuery["limit"]; len(got) != 1 || got[0] != "100" { |
| + t.Errorf("limit = %v", got) |
| + } |
| + if got := gotQuery["created[gte]"]; len(got) != 1 || got[0] != "1000" { |
| + t.Errorf("created[gte] = %v", got) |
| + } |
| + if got := gotQuery["created[lte]"]; len(got) != 1 || got[0] != "2000" { |
| + t.Errorf("created[lte] = %v", got) |
| + } |
| + if _, ok := gotQuery["starting_after"]; ok { |
| + t.Errorf("starting_after must be absent on the first page, got %v", gotQuery["starting_after"]) |
| + } |
| +} |
| + |
| +func TestListCheckouts_PathAndVersionHeader(t *testing.T) { |
| + var gotPath, gotVersion string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotPath = r.URL.Path |
| + gotVersion = r.Header.Get("Stripe-Version") |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}, "has_more": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + if _, err := c.ListCheckouts(context.Background(), 0, 1); err != nil { |
| + t.Fatalf("ListCheckouts: %v", err) |
| + } |
| + if gotPath != "/v1/checkout/sessions" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + if gotVersion != apiVersion { |
| + t.Errorf("Stripe-Version = %q", gotVersion) |
| + } |
| +} |
| + |
| +func TestListCheckouts_UsesStartingAfterOnSubsequentPage(t *testing.T) { |
| + var gotCursors []string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cursor := r.URL.Query().Get("starting_after") |
| + gotCursors = append(gotCursors, cursor) |
| + if cursor == "" { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": "cs_1", "livemode": true}, {"id": "cs_2", "livemode": true}}, |
| + "has_more": true, |
| + }) |
| + return |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": "cs_3", "livemode": true}}, |
| + "has_more": false, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + out, err := c.ListCheckouts(context.Background(), 0, 100) |
| + if err != nil { |
| + t.Fatalf("ListCheckouts: %v", err) |
| + } |
| + if len(out) != 3 || out[0].ID != "cs_1" || out[1].ID != "cs_2" || out[2].ID != "cs_3" { |
| + t.Fatalf("unexpected result: %+v", out) |
| + } |
| + if len(gotCursors) != 2 || gotCursors[0] != "" || gotCursors[1] != "cs_2" { |
| + t.Fatalf("unexpected cursor sequence: %v", gotCursors) |
| + } |
| +} |
| + |
| +// A listing that fails on a later page returns the sessions of the pages |
| +// it read together with the error: each was a provider answer, and a |
| +// caller that records what it reads must not lose them. |
| +func TestListCheckouts_ALaterPagesFailureKeepsTheEarlierPages(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Query().Get("starting_after") == "" { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": "cs_1", "livemode": true}, {"id": "cs_2", "livemode": true}}, |
| + "has_more": true, |
| + }) |
| + return |
| + } |
| + w.WriteHeader(http.StatusInternalServerError) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + out, err := c.ListCheckouts(context.Background(), 0, 100) |
| + if err == nil { |
| + t.Fatal("a failed second page: no error") |
| + } |
| + if len(out) != 2 || out[0].ID != "cs_1" || out[1].ID != "cs_2" { |
| + t.Fatalf("the pages read before the failure: %+v", out) |
| + } |
| +} |
| + |
| +// A page with a session that does not decode fails the listing, and the |
| +// sessions on it that did decode are still returned with the error. |
| +func TestListCheckouts_AMalformedSessionKeepsTheOthersOnItsPage(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": "cs_1", "status": "complete", "livemode": true}, {"id": "cs_bad"}, {"id": "cs_2", "status": "open", "livemode": true}}, |
| + "has_more": false, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + out, err := c.ListCheckouts(context.Background(), 0, 100) |
| + var listErr *Error |
| + if !errors.As(err, &listErr) || listErr.Code != CodeDecodeError { |
| + t.Fatalf("a session that does not decode: %v; want a decode error", err) |
| + } |
| + if len(out) != 2 || out[0].ID != "cs_1" || out[0].Status != "complete" || out[1].ID != "cs_2" { |
| + t.Fatalf("the sessions that did decode: %+v; want the ones before and after the malformed one", out) |
| + } |
| +} |
| + |
| +// A page that repeats a session is broken pagination, and what it said is |
| +// still returned with the error: the repeat, and what follows it. |
| +func TestListCheckouts_ABrokenPageStillReturnsWhatItSaid(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Query().Get("starting_after") == "" { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": "cs_1", "status": "expired", "livemode": true}}, |
| + "has_more": true, |
| + }) |
| + return |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": "cs_1", "status": "complete", "livemode": true}, {"id": "cs_2", "status": "open", "livemode": true}}, |
| + "has_more": false, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + out, err := c.ListCheckouts(context.Background(), 0, 100) |
| + var listErr *Error |
| + if !errors.As(err, &listErr) || listErr.Code != CodeBrokenPagination { |
| + t.Fatalf("a repeated session: %v; want broken pagination", err) |
| + } |
| + if len(out) != 3 || out[0].ID != "cs_1" || out[0].Status != "expired" || out[1].ID != "cs_1" || out[1].Status != "complete" || out[2].ID != "cs_2" { |
| + t.Fatalf("what the pages said: %+v; want both answers about cs_1 and the session after the repeat", out) |
| + } |
| +} |
| + |
| +func TestListCheckouts_RejectsInvalidBoundsWithoutHTTPCall(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + |
| + if _, err := c.ListCheckouts(context.Background(), -1, 100); err == nil { |
| + t.Error("expected error for negative createdAfter") |
| + } |
| + if _, err := c.ListCheckouts(context.Background(), 100, 99); err == nil { |
| + t.Error("expected error when createdBefore < createdAfter") |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request for invalid bounds, got %d", calls) |
| + } |
| +} |
| + |
| +func TestListCheckouts_EqualBoundsAllowed(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}, "has_more": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + if _, err := c.ListCheckouts(context.Background(), 500, 500); err != nil { |
| + t.Fatalf("equal createdAfter/createdBefore should be allowed: %v", err) |
| + } |
| +} |
| + |
| +func TestListCheckouts_EmptyTerminatingPageSucceeds(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}, "has_more": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + out, err := c.ListCheckouts(context.Background(), 0, 1) |
| + if err != nil { |
| + t.Fatalf("ListCheckouts: %v", err) |
| + } |
| + if len(out) != 0 { |
| + t.Fatalf("expected empty result, got %+v", out) |
| + } |
| +} |
| + |
| +func TestListCheckouts_NullDataTerminatesCleanly(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": nil, "has_more": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + out, err := c.ListCheckouts(context.Background(), 0, 1) |
| + if err != nil { |
| + t.Fatalf("ListCheckouts: %v", err) |
| + } |
| + if len(out) != 0 { |
| + t.Fatalf("expected empty result, got %+v", out) |
| + } |
| +} |
| + |
| +func TestListCheckouts_EmptyPageWithHasMoreIsBrokenPagination(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}, "has_more": true}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListCheckouts(context.Background(), 0, 1) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeBrokenPagination { |
| + t.Fatalf("err = %v, want CodeBrokenPagination", err) |
| + } |
| +} |
| + |
| +func TestListCheckouts_RepeatedCursorDetected(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + // Always the same single id, has_more forever: must not loop or |
| + // silently accept the duplicate as a new record. |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": "cs_stuck", "livemode": true}}, |
| + "has_more": true, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListCheckouts(context.Background(), 0, 1) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeBrokenPagination { |
| + t.Fatalf("err = %v, want CodeBrokenPagination", err) |
| + } |
| + if calls != 2 { |
| + t.Fatalf("expected exactly 2 calls before detecting the stuck cursor, got %d", calls) |
| + } |
| +} |
| + |
| +func TestListCheckouts_MissingSessionIDRejected(t *testing.T) { |
| + // Session.UnmarshalJSON itself now refuses a response missing "id" (or |
| + // "livemode"), so this fails at decode time rather than reaching |
| + // ListCheckouts' own validID/seen check — CodeDecodeError, not |
| + // CodeBrokenPagination. |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"status": "open"}}, // no "id" field |
| + "has_more": false, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListCheckouts(context.Background(), 0, 1) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +func TestListCheckouts_NullSessionObjectRejected(t *testing.T) { |
| + // A null array element decodes through Session.UnmarshalJSON with a |
| + // literal "null" body, which its id/livemode presence check refuses — |
| + // CodeDecodeError, not CodeBrokenPagination. |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/json") |
| + _, _ = w.Write([]byte(`{"data":[null],"has_more":false}`)) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListCheckouts(context.Background(), 0, 1) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError (a null session must not decode as an empty-ID session)", err) |
| + } |
| +} |
| + |
| +func TestListCheckouts_BoundedAt10000(t *testing.T) { |
| + var page int32 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + n := atomic.AddInt32(&page, 1) |
| + var data []map[string]any |
| + for i := 0; i < 100; i++ { |
| + data = append(data, map[string]any{"id": fmt.Sprintf("cs_%d_%d", n, i), "livemode": true}) |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": data, "has_more": true}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListCheckouts(context.Background(), 0, 1) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeTooManyRecords { |
| + t.Fatalf("err = %v, want CodeTooManyRecords", err) |
| + } |
| + // 10000 exactly must NOT trip the bound (100 pages); 10100 (101 pages) must. |
| + if page < 101 { |
| + t.Fatalf("bound tripped too early at page %d", page) |
| + } |
| +} |
| + |
| +func TestListCheckouts_OversizeResponseRejected(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusOK) |
| + buf := make([]byte, maxResponseBytes+1024) |
| + for i := range buf { |
| + buf[i] = ' ' |
| + } |
| + _, _ = w.Write(buf) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListCheckouts(context.Background(), 0, 1) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeResponseTooLarge { |
| + t.Fatalf("err = %v, want CodeResponseTooLarge", err) |
| + } |
| +} |
| + |
| +func TestListCheckouts_LiveModeAndMetadataDecodedAcrossPages(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{ |
| + {"id": "cs_1", "livemode": true, "metadata": map[string]string{"plan": "personal"}}, |
| + {"id": "cs_2", "livemode": false, "metadata": nil}, |
| + }, |
| + "has_more": false, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + out, err := c.ListCheckouts(context.Background(), 0, 1) |
| + if err != nil { |
| + t.Fatalf("ListCheckouts: %v", err) |
| + } |
| + if len(out) != 2 { |
| + t.Fatalf("got %d sessions, want 2", len(out)) |
| + } |
| + if !out[0].LiveMode || out[0].Metadata["plan"] != "personal" { |
| + t.Errorf("session0 = %+v", out[0]) |
| + } |
| + if out[1].LiveMode || out[1].Metadata != nil { |
| + t.Errorf("session1 = %+v", out[1]) |
| + } |
| +} |
| + |
| +func TestListCheckouts_ErrorDoesNotLeakProviderMessage(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusTooManyRequests) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "error": map[string]any{ |
| + "type": "rate_limit_error", "code": "rate_limit_error", |
| + "message": "Secret internal detail about account acct_deadbeef", |
| + }, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListCheckouts(context.Background(), 0, 1) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeAPIError { |
| + t.Fatalf("err = %v, want CodeAPIError", err) |
| + } |
| + if strings.Contains(e.Error(), "acct_deadbeef") || strings.Contains(e.Error(), "Secret internal detail") { |
| + t.Fatalf("Error() leaked provider message: %s", e.Error()) |
| + } |
| +} |
| + |
| +// --- ActiveTaxRegistrations: query shape, decoding, pagination boundary --- |
| + |
| +func TestActiveTaxRegistrations_QueryPathAndVersion(t *testing.T) { |
| + var gotPath, gotVersion string |
| + var gotQuery map[string][]string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotPath = r.URL.Path |
| + gotVersion = r.Header.Get("Stripe-Version") |
| + gotQuery = map[string][]string(r.URL.Query()) |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}, "has_more": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + if _, err := c.ActiveTaxRegistrations(context.Background()); err != nil { |
| + t.Fatalf("ActiveTaxRegistrations: %v", err) |
| + } |
| + if gotPath != "/v1/tax/registrations" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + if gotVersion != apiVersion { |
| + t.Errorf("Stripe-Version = %q", gotVersion) |
| + } |
| + if got := gotQuery["status"]; len(got) != 1 || got[0] != "active" { |
| + t.Errorf("status = %v", got) |
| + } |
| + if got := gotQuery["limit"]; len(got) != 1 || got[0] != "100" { |
| + t.Errorf("limit = %v", got) |
| + } |
| +} |
| + |
| +func TestActiveTaxRegistrations_DecodesFields(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{ |
| + { |
| + "id": "txr_1", "country": "DE", "status": "active", "active_from": 1700000000, |
| + "country_options": map[string]any{"de": map[string]any{"type": "standard"}}, |
| + }, |
| + }, |
| + "has_more": false, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + regs, err := c.ActiveTaxRegistrations(context.Background()) |
| + if err != nil { |
| + t.Fatalf("ActiveTaxRegistrations: %v", err) |
| + } |
| + if len(regs) != 1 { |
| + t.Fatalf("got %d registrations, want 1", len(regs)) |
| + } |
| + r := regs[0] |
| + if r.ID != "txr_1" || r.Country != "DE" || r.Status != "active" || r.ActiveFrom != 1700000000 { |
| + t.Fatalf("unexpected registration: %+v", r) |
| + } |
| + if opt, ok := r.CountryOptions["de"]; !ok || opt.Type != "standard" { |
| + t.Fatalf("unexpected country_options: %+v", r.CountryOptions) |
| + } |
| +} |
| + |
| +func TestActiveTaxRegistrations_HasMoreTrueIsRejected(t *testing.T) { |
| + // This endpoint has no pagination loop: even a single record on a |
| + // has_more:true page is treated as "too many to enumerate safely" |
| + // rather than silently returning a partial list. |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": "txr_1", "country": "DE"}}, |
| + "has_more": true, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ActiveTaxRegistrations(context.Background()) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeTooManyRecords { |
| + t.Fatalf("err = %v, want CodeTooManyRecords", err) |
| + } |
| +} |
| + |
| +func TestActiveTaxRegistrations_NullDataSucceedsEmpty(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": nil, "has_more": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + regs, err := c.ActiveTaxRegistrations(context.Background()) |
| + if err != nil { |
| + t.Fatalf("ActiveTaxRegistrations: %v", err) |
| + } |
| + if len(regs) != 0 { |
| + t.Fatalf("expected empty result, got %+v", regs) |
| + } |
| +} |
| + |
| +func TestActiveTaxRegistrations_MalformedCountryOptionsTypeIsDecodeError(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/json") |
| + // "type" is a number where a string is expected. |
| + _, _ = w.Write([]byte(`{"data":[{"id":"txr_1","country_options":{"de":{"type":42}}}],"has_more":false}`)) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ActiveTaxRegistrations(context.Background()) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +func TestActiveTaxRegistrations_ErrorSanitized(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusInternalServerError) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "error": map[string]any{ |
| + "type": "api_error", "code": "api_error", |
| + "message": "internal trace id 8f21 for key rk_live_should_never_appear", |
| + }, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ActiveTaxRegistrations(context.Background()) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeAPIError { |
| + t.Fatalf("err = %v, want CodeAPIError", err) |
| + } |
| + if strings.Contains(e.Error(), "rk_live_should_never_appear") || strings.Contains(e.Error(), "trace id") { |
| + t.Fatalf("Error() leaked provider message: %s", e.Error()) |
| + } |
| +} |
| + |
| +func TestActiveTaxRegistrations_UnexpectedStatusWithEmptyBody(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(599) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ActiveTaxRegistrations(context.Background()) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeAPIError || e.HTTPStatus != 599 { |
| + t.Fatalf("err = %v, want CodeAPIError status=599", err) |
| + } |
| +} |
diff --git a/internal/billingstripe/client.go b/internal/billingstripe/client.go| new file mode 100644 |
| index 000000000..59cc8a38f |
| --- /dev/null |
| +++ b/internal/billingstripe/client.go |
| @@ -0,0 +1,875 @@ |
| +// Package billingstripe is a thin stdlib client for the Stripe API surface |
| +// billing needs: Checkout, the Customer Portal, Subscriptions, Prices and |
| +// Products, and webhook verification. adapter.go wraps it as a |
| +// billing.Provider, which is all the console sees. |
| +// |
| +// No stripe-go, no retries (retry policy belongs to the caller: a billing |
| +// call must never be retried with a fresh idempotency key, which is a |
| +// decision only the caller's state machine can make safely), no network |
| +// mutation beyond what a caller explicitly asks for. |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "regexp" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +const ( |
| + // apiVersion is pinned so Stripe's response shapes never drift under us. |
| + // current_period_start/end still live on the subscription object at this |
| + // version; a later version moves them onto subscription items. |
| + apiVersion = "2025-02-24.acacia" |
| + |
| + defaultBaseURL = "https://api.stripe.com" |
| + |
| + // maxResponseBytes bounds how much of a response body we ever hold in |
| + // memory, independent of what Content-Length claims. |
| + maxResponseBytes = 1 << 20 // 1 MiB |
| + |
| + requestTimeout = 15 * time.Second |
| +) |
| + |
| +// Stable, sanitized error codes. Error never carries a response body, |
| +// a Stripe error "message" (which can echo request parameters back) or |
| +// any request secret — only these codes plus the HTTP status and, for a |
| +// parsed Stripe API error, Stripe's own "type" and "code" enum values. |
| +const ( |
| + CodeInvalidParams = "invalid_params" |
| + CodeInvalidID = "invalid_id" |
| + CodeMissingIdempotencyKey = "missing_idempotency_key" |
| + CodeMutuallyExclusive = "mutually_exclusive_params" |
| + CodeTimeout = "timeout" |
| + CodeNetwork = "network_error" |
| + CodeUnexpectedRedirect = "unexpected_redirect" |
| + CodeUnexpectedRedirectURL = "unexpected_redirect_url" |
| + CodeResponseTooLarge = "response_too_large" |
| + CodeDecodeError = "decode_error" |
| + CodeAPIError = "api_error" |
| + CodeBrokenPagination = "broken_pagination" |
| + CodeTooManyRecords = "too_many_records" |
| +) |
| + |
| +// Error is the only error shape this package returns. Its Error() string is |
| +// stable and safe to log: no response body, no request body, no secret key. |
| +type Error struct { |
| + Code string |
| + HTTPStatus int // 0 when the request never reached Stripe |
| + StripeType string // Stripe's error "type" field, present only for CodeAPIError |
| + StripeCode string // Stripe's error "code" field, present only for CodeAPIError |
| + // StripeParam is Stripe's error "param" field: the request parameter |
| + // the refusal is about. Present only for CodeAPIError. |
| + StripeParam string |
| + // Replayed reports that the provider answered from its memory of an |
| + // earlier request under the same idempotency key (its |
| + // Idempotent-Replayed header), and ran nothing now. |
| + Replayed bool |
| + // SessionID and Session are set only for CodeCurrencyMismatch: the |
| + // checkout session the provider did create, which is not the one that |
| + // was asked for. It exists and is open. The caller decides what to do |
| + // with it from the session itself (whose it is, above all), not from |
| + // the id alone. |
| + SessionID string |
| + Session *Session |
| +} |
| + |
| +// RefusedParam reports whether Stripe refused the request outright as |
| +// invalid because of the named parameter. Such a request was not executed. |
| +func (e *Error) RefusedParam(name string) bool { |
| + return e != nil && e.Code == CodeAPIError && e.HTTPStatus == 400 && e.StripeType == "invalid_request_error" && e.StripeParam == name |
| +} |
| + |
| +func (e *Error) Error() string { |
| + parts := []string{"billingstripe: " + e.Code} |
| + if e.HTTPStatus != 0 { |
| + parts = append(parts, fmt.Sprintf("status=%d", e.HTTPStatus)) |
| + } |
| + if e.StripeType != "" { |
| + parts = append(parts, "stripe_type="+e.StripeType) |
| + } |
| + if e.StripeCode != "" { |
| + parts = append(parts, "stripe_code="+e.StripeCode) |
| + } |
| + return strings.Join(parts, " ") |
| +} |
| + |
| +// Client calls the Stripe API. Zero value is not usable; build with |
| +// NewClient. |
| +type Client struct { |
| + secretKey string |
| + baseURL string |
| + httpClient *http.Client |
| +} |
| + |
| +// String and GoString redact the secret key so an accidental %v/%+v of a |
| +// Client — a log line, a debugger dump, a panic trace — never prints it. |
| +func (c *Client) String() string { return fmt.Sprintf("billingstripe.Client{baseURL:%q}", c.baseURL) } |
| + |
| +func (c *Client) GoString() string { return c.String() } |
| + |
| +// Option configures a Client at construction. |
| +type Option func(*Client) |
| + |
| +// WithBaseURL points the client at something other than api.stripe.com — |
| +// an httptest.Server in tests. |
| +func WithBaseURL(base string) Option { |
| + return func(c *Client) { c.baseURL = strings.TrimRight(base, "/") } |
| +} |
| + |
| +// NewClient builds a Client. secretKey must be a restricted key (rk_...); |
| +// a full secret key (sk_...) grants far more than this package uses and is |
| +// refused rather than silently accepted. |
| +func NewClient(secretKey string, opts ...Option) (*Client, error) { |
| + if !strings.HasPrefix(secretKey, "rk_") { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + c := &Client{ |
| + secretKey: secretKey, |
| + baseURL: defaultBaseURL, |
| + httpClient: &http.Client{ |
| + Timeout: requestTimeout, |
| + // Never follow a redirect: Stripe's API does not issue them, and |
| + // following one would replay the Authorization header (and thus |
| + // the restricted key) against a host we did not choose. Treat any |
| + // 3xx as a hard failure instead of a hop. |
| + CheckRedirect: func(*http.Request, []*http.Request) error { |
| + return http.ErrUseLastResponse |
| + }, |
| + }, |
| + } |
| + for _, opt := range opts { |
| + opt(c) |
| + } |
| + return c, nil |
| +} |
| + |
| +// validIDRe matches the charset real Stripe object ids use. Interpolating |
| +// an id into a URL path without this check is a path-traversal vector |
| +// ("../../v1/customers") and a request-smuggling one. |
| +var validIDRe = regexp.MustCompile(`^[A-Za-z0-9_]{1,255}$`) |
| + |
| +func validID(id string) bool { return validIDRe.MatchString(id) } |
| + |
| +type stripeErrorEnvelope struct { |
| + Error struct { |
| + Type string `json:"type"` |
| + Code string `json:"code"` |
| + Param string `json:"param"` |
| + // message and param are deliberately not decoded: Stripe's message |
| + // text can interpolate request parameters (card numbers' last four, |
| + // email addresses, free-text fields), and this package promises |
| + // never to surface response-body content in an error. |
| + } `json:"error"` |
| +} |
| + |
| +// do executes one request. Every POST requires idempotencyKey; GET ignores |
| +// it. No retries: a failed request is returned to the caller exactly once. |
| +func (c *Client) do(ctx context.Context, method, path string, form url.Values, idempotencyKey string, out any) error { |
| + if method == http.MethodPost && idempotencyKey == "" { |
| + return &Error{Code: CodeMissingIdempotencyKey} |
| + } |
| + |
| + reqURL := c.baseURL + path |
| + var body io.Reader |
| + if method == http.MethodPost { |
| + body = strings.NewReader(form.Encode()) |
| + } else if len(form) > 0 { |
| + reqURL += "?" + form.Encode() |
| + } |
| + |
| + req, err := http.NewRequestWithContext(ctx, method, reqURL, body) |
| + if err != nil { |
| + return &Error{Code: CodeInvalidParams} |
| + } |
| + req.Header.Set("Authorization", "Bearer "+c.secretKey) |
| + req.Header.Set("Stripe-Version", apiVersion) |
| + req.Header.Set("Accept", "application/json") |
| + if method == http.MethodPost { |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Idempotency-Key", idempotencyKey) |
| + } |
| + |
| + resp, err := c.httpClient.Do(req) |
| + if err != nil { |
| + if ctx.Err() != nil || isTimeout(err) { |
| + return &Error{Code: CodeTimeout} |
| + } |
| + return &Error{Code: CodeNetwork} |
| + } |
| + defer resp.Body.Close() |
| + |
| + if resp.StatusCode >= 300 && resp.StatusCode < 400 { |
| + // CheckRedirect stopped us from following it, but a 3xx is still not |
| + // a status this API is supposed to return. |
| + return &Error{Code: CodeUnexpectedRedirect, HTTPStatus: resp.StatusCode} |
| + } |
| + |
| + limited := io.LimitReader(resp.Body, maxResponseBytes+1) |
| + respBody, err := io.ReadAll(limited) |
| + if err != nil { |
| + return &Error{Code: CodeNetwork} |
| + } |
| + if len(respBody) > maxResponseBytes { |
| + return &Error{Code: CodeResponseTooLarge, HTTPStatus: resp.StatusCode} |
| + } |
| + |
| + if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| + var env stripeErrorEnvelope |
| + _ = json.Unmarshal(respBody, &env) // best-effort; body itself never leaves this function |
| + return &Error{ |
| + Code: CodeAPIError, |
| + HTTPStatus: resp.StatusCode, |
| + StripeType: safeErrorEnum(env.Error.Type), |
| + StripeCode: safeErrorEnum(env.Error.Code), |
| + StripeParam: safeErrorParam(env.Error.Param), |
| + Replayed: resp.Header.Get("Idempotent-Replayed") == "true", |
| + } |
| + } |
| + |
| + if out == nil { |
| + return nil |
| + } |
| + if err := json.Unmarshal(respBody, out); err != nil { |
| + return &Error{Code: CodeDecodeError, HTTPStatus: resp.StatusCode} |
| + } |
| + return nil |
| +} |
| + |
| +func isTimeout(err error) bool { |
| + var ue *url.Error |
| + if errors.As(err, &ue) { |
| + return ue.Timeout() |
| + } |
| + return false |
| +} |
| + |
| +// validateRedirectURL enforces that a session's hosted URL actually points |
| +// at the Stripe-operated host it is supposed to, so a compromised or |
| +// misconfigured upstream can't hand back a phishing redirect that our own |
| +// client then treats as trustworthy. Validating the caller-supplied |
| +// success/cancel/return URLs is the caller's job; this is the other |
| +// direction — what Stripe hands back to us. |
| +func validateRedirectURL(raw, wantHost string) error { |
| + u, err := url.Parse(raw) |
| + if err != nil || u.Scheme != "https" || u.Host != wantHost { |
| + return &Error{Code: CodeUnexpectedRedirectURL} |
| + } |
| + return nil |
| +} |
| + |
| +// idOrExpanded decodes a Stripe expandable field: a bare id string, a full |
| +// object (when the caller asked Stripe to expand it), or null. |
| +type idOrExpanded struct { |
| + ID string |
| + Object json.RawMessage // non-nil only when Stripe sent a full object |
| +} |
| + |
| +func (v *idOrExpanded) UnmarshalJSON(b []byte) error { |
| + if string(b) == "null" { |
| + *v = idOrExpanded{} |
| + return nil |
| + } |
| + if len(b) > 0 && b[0] == '"' { |
| + return json.Unmarshal(b, &v.ID) |
| + } |
| + var withID struct { |
| + ID string `json:"id"` |
| + } |
| + if err := json.Unmarshal(b, &withID); err != nil { |
| + return err |
| + } |
| + v.ID = withID.ID |
| + v.Object = b |
| + return nil |
| +} |
| + |
| +// Session is a Checkout Session, trimmed to the fields the spec's |
| +// entitlement flow needs. |
| +type Session struct { |
| + ID string |
| + URL string |
| + Status string |
| + PaymentStatus string |
| + CustomerID string |
| + SubscriptionID string |
| + Subscription *Subscription // set only when the caller asked Stripe to expand it |
| + ClientReferenceID string |
| + Metadata map[string]string |
| + ExpiresAt int64 |
| + BillingCountry string |
| + LiveMode bool |
| + // Currency is the session's own currency, lower case, as Stripe |
| + // reports it ("" when the response carried none). |
| + Currency string |
| + // AdaptivePricing is true when the response says Adaptive Pricing is |
| + // enabled for the session, and Converted when it carries a currency |
| + // conversion. Prices here are fixed per currency: a session with |
| + // either is not one this package asked for. |
| + AdaptivePricing bool |
| + Converted bool |
| +} |
| + |
| +// UnmarshalJSON decodes a Session strictly enough that a null response body, |
| +// or one missing "id" or "livemode", cannot pass. Both fields decode through |
| +// pointers specifically so a caller can tell "absent" from "present and |
| +// zero": a naive struct would decode a null object into LiveMode=false, |
| +// which reads as test mode when the response in fact proved nothing at all. |
| +func (s *Session) UnmarshalJSON(b []byte) error { |
| + var raw struct { |
| + ID *string `json:"id"` |
| + URL string `json:"url"` |
| + Status string `json:"status"` |
| + PaymentStatus string `json:"payment_status"` |
| + Customer idOrExpanded `json:"customer"` |
| + Subscription idOrExpanded `json:"subscription"` |
| + ClientReferenceID string `json:"client_reference_id"` |
| + Metadata map[string]string `json:"metadata"` |
| + ExpiresAt int64 `json:"expires_at"` |
| + LiveMode *bool `json:"livemode"` |
| + Currency string `json:"currency"` |
| + AdaptivePricing *struct { |
| + Enabled bool `json:"enabled"` |
| + } `json:"adaptive_pricing"` |
| + CurrencyConversion json.RawMessage `json:"currency_conversion"` |
| + CustomerDetails struct { |
| + Address struct { |
| + Country string `json:"country"` |
| + } `json:"address"` |
| + } `json:"customer_details"` |
| + } |
| + if err := json.Unmarshal(b, &raw); err != nil { |
| + return err |
| + } |
| + if raw.ID == nil || *raw.ID == "" || raw.LiveMode == nil { |
| + return errors.New("billingstripe: session response missing id or livemode") |
| + } |
| + if !validID(*raw.ID) { |
| + return errors.New("billingstripe: session id has unexpected shape") |
| + } |
| + *s = Session{} |
| + s.ID = *raw.ID |
| + s.URL = raw.URL |
| + s.Status = raw.Status |
| + s.PaymentStatus = raw.PaymentStatus |
| + s.CustomerID = raw.Customer.ID |
| + s.SubscriptionID = raw.Subscription.ID |
| + s.ClientReferenceID = raw.ClientReferenceID |
| + s.Metadata = raw.Metadata |
| + s.ExpiresAt, s.LiveMode, s.BillingCountry = raw.ExpiresAt, *raw.LiveMode, raw.CustomerDetails.Address.Country |
| + s.Currency = raw.Currency |
| + s.AdaptivePricing = raw.AdaptivePricing != nil && raw.AdaptivePricing.Enabled |
| + s.Converted = len(raw.CurrencyConversion) > 0 && string(raw.CurrencyConversion) != "null" |
| + if raw.Subscription.Object != nil { |
| + var sub Subscription |
| + if err := json.Unmarshal(raw.Subscription.Object, &sub); err != nil { |
| + return err |
| + } |
| + s.Subscription = &sub |
| + } |
| + return nil |
| +} |
| + |
| +// SubscriptionItem is one line of a subscription. Subscription.Items |
| +// carries every item Stripe returned — this package never picks "the |
| +// first" and drops the rest; a caller that only supports one item must |
| +// reject a multi-item subscription itself. |
| +type SubscriptionItem struct { |
| + ID string |
| + PriceID string |
| + Quantity int64 |
| + // PriceCurrency is the currency of the item's price, lower case, as |
| + // Stripe reports it ("" when the response carried none). |
| + PriceCurrency string |
| +} |
| + |
| +func (it *SubscriptionItem) UnmarshalJSON(b []byte) error { |
| + var raw struct { |
| + ID string `json:"id"` |
| + Quantity int64 `json:"quantity"` |
| + Price struct { |
| + ID string `json:"id"` |
| + Currency string `json:"currency"` |
| + } `json:"price"` |
| + } |
| + if err := json.Unmarshal(b, &raw); err != nil { |
| + return err |
| + } |
| + it.ID = raw.ID |
| + it.Quantity = raw.Quantity |
| + it.PriceID = raw.Price.ID |
| + it.PriceCurrency = raw.Price.Currency |
| + return nil |
| +} |
| + |
| +// Subscription, trimmed to the fields entitlement and billing need. |
| +type Subscription struct { |
| + ID string |
| + CustomerID string |
| + Status string |
| + Created time.Time |
| + CurrentPeriodStart time.Time |
| + CurrentPeriodEnd time.Time |
| + CancelAtPeriodEnd bool |
| + Metadata map[string]string |
| + Items []SubscriptionItem |
| + LiveMode bool |
| + ItemsHasMore bool |
| + // Currency is the subscription's own currency, lower case, as Stripe |
| + // reports it ("" when the response carried none). |
| + Currency string |
| +} |
| + |
| +// UnmarshalJSON decodes a Subscription strictly enough that a null response |
| +// body, or one missing "id" or "livemode", cannot pass. Both fields decode |
| +// through pointers specifically so a caller can tell "absent" from "present |
| +// and zero": a naive struct would decode a null object into LiveMode=false, |
| +// which reads as test mode when the response in fact proved nothing at all. |
| +func (s *Subscription) UnmarshalJSON(b []byte) error { |
| + var raw struct { |
| + ID *string `json:"id"` |
| + Customer idOrExpanded `json:"customer"` |
| + Status string `json:"status"` |
| + Created int64 `json:"created"` |
| + CurrentPeriodStart int64 `json:"current_period_start"` |
| + CurrentPeriodEnd int64 `json:"current_period_end"` |
| + CancelAtPeriodEnd bool `json:"cancel_at_period_end"` |
| + Metadata map[string]string `json:"metadata"` |
| + LiveMode *bool `json:"livemode"` |
| + Currency string `json:"currency"` |
| + Items struct { |
| + Data []SubscriptionItem `json:"data"` |
| + HasMore bool `json:"has_more"` |
| + } `json:"items"` |
| + } |
| + if err := json.Unmarshal(b, &raw); err != nil { |
| + return err |
| + } |
| + if raw.ID == nil || *raw.ID == "" || raw.LiveMode == nil { |
| + return errors.New("billingstripe: subscription response missing id or livemode") |
| + } |
| + if !validID(*raw.ID) { |
| + return errors.New("billingstripe: subscription id has unexpected shape") |
| + } |
| + *s = Subscription{} |
| + s.ID = *raw.ID |
| + s.CustomerID = raw.Customer.ID |
| + s.Status = raw.Status |
| + s.Created = time.Unix(raw.Created, 0).UTC() |
| + s.CurrentPeriodStart = time.Unix(raw.CurrentPeriodStart, 0).UTC() |
| + s.CurrentPeriodEnd = time.Unix(raw.CurrentPeriodEnd, 0).UTC() |
| + s.CancelAtPeriodEnd = raw.CancelAtPeriodEnd |
| + s.Metadata = raw.Metadata |
| + s.Items = raw.Items.Data |
| + s.LiveMode, s.ItemsHasMore = *raw.LiveMode, raw.Items.HasMore |
| + s.Currency = raw.Currency |
| + return nil |
| +} |
| + |
| +// PortalSession is a Customer Portal session. |
| +type PortalSession struct { |
| + ID string `json:"id"` |
| + URL string `json:"url"` |
| +} |
| + |
| +// CheckoutMetadata is written to both the session and the subscription it |
| +// creates. The customer the console created for the account is the |
| +// purchase's identity; the metadata lets an operator, and the console's |
| +// identity checks, see which account, intent, book and currency a |
| +// subscription was bought under without trusting anything the buyer typed. |
| +type CheckoutMetadata struct { |
| + AccountSqid string |
| + IntentID string |
| + PriceBook string |
| + Currency string |
| +} |
| + |
| +func (m CheckoutMetadata) valid() bool { |
| + return m.AccountSqid != "" && validID(m.IntentID) && m.PriceBook != "" && validCurrency(m.Currency) |
| +} |
| + |
| +// validCurrency accepts a lower-case three-letter code. Which currencies |
| +// are sold is the caller's rule; this only keeps anything else out of a |
| +// request. |
| +func validCurrency(c string) bool { |
| + if len(c) != 3 { |
| + return false |
| + } |
| + for i := 0; i < 3; i++ { |
| + if c[i] < 'a' || c[i] > 'z' { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func (m CheckoutMetadata) set(form url.Values, prefix string) { |
| + form.Set(prefix+"[account_sqid]", m.AccountSqid) |
| + form.Set(prefix+"[checkout_intent]", m.IntentID) |
| + form.Set(prefix+"[price_book]", m.PriceBook) |
| + form.Set(prefix+"[currency]", m.Currency) |
| +} |
| + |
| +// LineItem is one price on a checkout, with its quantity. |
| +type LineItem struct { |
| + PriceID string |
| + Quantity int64 |
| +} |
| + |
| +// CreateCheckoutParams. Deliberately absent: CustomerEmail (when neither |
| +// CustomerID nor an email is set, Checkout collects the buyer's identity |
| +// itself), payment_method_types (it overrides the Dashboard's dynamic |
| +// methods) and currency_options (a price here is in one currency). |
| +// |
| +// Prices are fixed in each currency they are sold in, so a session is |
| +// created in exactly the currency the buyer chose, and Adaptive Pricing, |
| +// which would present and charge a converted amount, is switched off on |
| +// every session. |
| +type CreateCheckoutParams struct { |
| + // Items is the plan's price at quantity 1 and one line per pack: every |
| + // item a subscription is bought with, all in Currency. |
| + Items []LineItem |
| + SuccessURL string |
| + CancelURL string |
| + CustomerID string // optional: an existing Stripe customer |
| + ClientReferenceID string |
| + Metadata CheckoutMetadata |
| + |
| + // HouseCoupon, when set, attaches a 100%-off coupon and suppresses |
| + // promotion codes (Stripe refuses a session carrying both). Leave empty |
| + // for the ordinary path, which enables promotion codes. |
| + HouseCoupon string |
| + |
| + // Currency is the currency the session must be in: the prices' own. |
| + // It is sent to Stripe, which refuses a session whose prices are in |
| + // another currency, and the session that comes back is checked |
| + // against it. Required. |
| + Currency string |
| +} |
| + |
| +// CodeCurrencyMismatch: Stripe answered with a session that is not in the |
| +// currency asked for, or that has Adaptive Pricing or a conversion on it. |
| +const CodeCurrencyMismatch = "currency_mismatch" |
| + |
| +// FixedCurrency reports whether a session is in exactly currency, with no |
| +// Adaptive Pricing and no conversion: what every session this package |
| +// creates must be, and what a caller checks again when it reads one back. |
| +func (s *Session) FixedCurrency(currency string) bool { |
| + return validCurrency(currency) && s.Currency == currency && !s.AdaptivePricing && !s.Converted |
| +} |
| + |
| +// CreateCheckout starts a subscription-mode Checkout Session at exactly the |
| +// configured price and quantity. idempotencyKey is required and is never |
| +// generated by this package — a caller retrying a failed create must reuse |
| +// the same key, or it is not a retry. |
| +func (c *Client) CreateCheckout(ctx context.Context, p CreateCheckoutParams, idempotencyKey string) (*Session, error) { |
| + if len(p.Items) == 0 { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + for _, it := range p.Items { |
| + if !validID(it.PriceID) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + if it.Quantity < 1 { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + } |
| + if p.SuccessURL == "" || p.CancelURL == "" { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + if !p.Metadata.valid() { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + if !validID(p.CustomerID) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + if !validCurrency(p.Currency) || p.Metadata.Currency != p.Currency { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + |
| + form := url.Values{} |
| + form.Set("mode", "subscription") |
| + form.Set("currency", p.Currency) |
| + form.Set("adaptive_pricing[enabled]", "false") |
| + for i, it := range p.Items { |
| + form.Set(fmt.Sprintf("line_items[%d][price]", i), it.PriceID) |
| + form.Set(fmt.Sprintf("line_items[%d][quantity]", i), strconv.FormatInt(it.Quantity, 10)) |
| + } |
| + form.Set("success_url", p.SuccessURL) |
| + form.Set("cancel_url", p.CancelURL) |
| + form.Set("automatic_tax[enabled]", "true") |
| + if p.ClientReferenceID != "" { |
| + form.Set("client_reference_id", p.ClientReferenceID) |
| + } |
| + if p.CustomerID != "" { |
| + form.Set("customer", p.CustomerID) |
| + } |
| + if p.HouseCoupon != "" { |
| + form.Set("discounts[0][coupon]", p.HouseCoupon) |
| + } else { |
| + form.Set("allow_promotion_codes", "true") |
| + } |
| + p.Metadata.set(form, "metadata") |
| + p.Metadata.set(form, "subscription_data[metadata]") |
| + |
| + var sess Session |
| + if err := c.do(ctx, http.MethodPost, "/v1/checkout/sessions", form, idempotencyKey, &sess); err != nil { |
| + return nil, err |
| + } |
| + if err := validateRedirectURL(sess.URL, "checkout.stripe.com"); err != nil { |
| + return nil, err |
| + } |
| + if !sess.FixedCurrency(p.Currency) { |
| + return nil, &Error{Code: CodeCurrencyMismatch, SessionID: sess.ID, Session: &sess} |
| + } |
| + return &sess, nil |
| +} |
| + |
| +// GetCheckout reads back a Checkout Session with its subscription expanded, |
| +// so a completed session's subscription state is available in one call. |
| +func (c *Client) GetCheckout(ctx context.Context, id string) (*Session, error) { |
| + if !validID(id) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + form := url.Values{} |
| + form.Add("expand[]", "subscription") |
| + var sess Session |
| + if err := c.do(ctx, http.MethodGet, "/v1/checkout/sessions/"+id, form, "", &sess); err != nil { |
| + return nil, err |
| + } |
| + return &sess, nil |
| +} |
| + |
| +// ExpireCheckout expires an open Checkout Session early. |
| +func (c *Client) ExpireCheckout(ctx context.Context, id, idempotencyKey string) (*Session, error) { |
| + if !validID(id) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + var sess Session |
| + if err := c.do(ctx, http.MethodPost, "/v1/checkout/sessions/"+id+"/expire", nil, idempotencyKey, &sess); err != nil { |
| + return nil, err |
| + } |
| + return &sess, nil |
| +} |
| + |
| +// CreatePortal opens a Customer Portal session for card updates, |
| +// cancellation and invoice history, against the given Configuration — |
| +// configurationID is required rather than left to Stripe's account-default |
| +// configuration, so the caller (and GetPortalConfiguration) always knows |
| +// exactly which feature set a session was opened under. |
| +func (c *Client) CreatePortal(ctx context.Context, customerID, returnURL, configurationID, idempotencyKey string) (*PortalSession, error) { |
| + if !validID(customerID) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + if returnURL == "" { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + if !validID(configurationID) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + form := url.Values{} |
| + form.Set("customer", customerID) |
| + form.Set("return_url", returnURL) |
| + form.Set("configuration", configurationID) |
| + var ps PortalSession |
| + if err := c.do(ctx, http.MethodPost, "/v1/billing_portal/sessions", form, idempotencyKey, &ps); err != nil { |
| + return nil, err |
| + } |
| + if err := validateRedirectURL(ps.URL, "billing.stripe.com"); err != nil { |
| + return nil, err |
| + } |
| + return &ps, nil |
| +} |
| + |
| +// GetSubscription reads one subscription. |
| +func (c *Client) GetSubscription(ctx context.Context, id string) (*Subscription, error) { |
| + if !validID(id) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + var sub Subscription |
| + if err := c.do(ctx, http.MethodGet, "/v1/subscriptions/"+id, nil, "", &sub); err != nil { |
| + return nil, err |
| + } |
| + return &sub, nil |
| +} |
| + |
| +// Proration behaviours UpdateQuantityWith accepts. They are Stripe's own |
| +// values for proration_behavior. |
| +const ( |
| + ProrationAlwaysInvoice = "always_invoice" // invoice and collect the proration now |
| + ProrationCreateProrations = "create_prorations" // add it to the next invoice |
| + ProrationNone = "none" // change the quantity, prorate nothing |
| +) |
| + |
| +// UpdateQuantity changes one subscription item's quantity, invoicing the |
| +// proration immediately (always_invoice) rather than deferring it to the |
| +// next regular invoice. |
| +func (c *Client) UpdateQuantity(ctx context.Context, itemID string, quantity int64, idempotencyKey string) (*SubscriptionItem, error) { |
| + return c.UpdateQuantityWith(ctx, itemID, quantity, ProrationAlwaysInvoice, time.Time{}, idempotencyKey) |
| +} |
| + |
| +// UpdateQuantityWith changes one subscription item's quantity under the |
| +// named proration behaviour. When the proration is collected is a product |
| +// decision the caller carries; nothing here defaults it. |
| +// |
| +// A non-zero prorationDate is sent as proration_date: the proration is |
| +// computed as of that instant, and the provider refuses the request when |
| +// the instant lies outside the subscription's current period. A caller that |
| +// decided the update in one period therefore cannot have it charged into |
| +// the next. |
| +func (c *Client) UpdateQuantityWith(ctx context.Context, itemID string, quantity int64, proration string, prorationDate time.Time, idempotencyKey string) (*SubscriptionItem, error) { |
| + if !validID(itemID) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + if quantity < 1 { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + switch proration { |
| + case ProrationAlwaysInvoice, ProrationCreateProrations, ProrationNone: |
| + default: |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + form := url.Values{} |
| + form.Set("quantity", strconv.FormatInt(quantity, 10)) |
| + form.Set("proration_behavior", proration) |
| + if !prorationDate.IsZero() { |
| + if prorationDate.Unix() <= 0 { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + form.Set("proration_date", strconv.FormatInt(prorationDate.Unix(), 10)) |
| + } |
| + var item SubscriptionItem |
| + if err := c.do(ctx, http.MethodPost, "/v1/subscription_items/"+itemID, form, idempotencyKey, &item); err != nil { |
| + return nil, err |
| + } |
| + return &item, nil |
| +} |
| + |
| +// What a fence request found (FenceQuantityKey). |
| +const ( |
| + // FenceTaken: the fence request ran. The key now belongs to it, so the |
| + // operation's own request never ran under this key, and cannot while |
| + // the provider remembers the key. |
| + FenceTaken = "fence" |
| + // FenceHeldByRequest: the provider refused the fence request because |
| + // the key already belongs to a request with other parameters, which is |
| + // the operation's own. That request began executing. It says nothing |
| + // about how it ended: it may have succeeded, failed for good, or ended |
| + // in an error the provider itself calls indeterminate (a 500, which it |
| + // may still reconcile). A second copy of it runs nothing. |
| + FenceHeldByRequest = "request" |
| +) |
| + |
| +// FenceQuantityKey tries to make the provider refuse any later quantity |
| +// update sent under idempotencyKey, without changing anything a customer is |
| +// billed for. |
| +// |
| +// The provider remembers an idempotency key with the parameters it was |
| +// first used with, and refuses the key with any other parameters. This |
| +// sends a metadata-only update of the item under the key. It returns |
| +// FenceTaken or FenceHeldByRequest (above), or "" with no error when a |
| +// request under the key is executing at this moment (a 409); the caller |
| +// asks again later. |
| +// |
| +// Every other answer is an error and means nothing is known to hold the |
| +// key. That includes a missing item: a 404 saves no result, and the same |
| +// answer comes back for an item id that belongs to another account or |
| +// mode. |
| +// |
| +// The provider's memory of a key is not permanent. Stripe documents that a |
| +// key may be removed once it is at least 24 hours old, counted from the |
| +// request that first used it. FenceTaken therefore holds for 24 hours from |
| +// this call, and FenceHeldByRequest only until 24 hours after the |
| +// operation's own request, which may be nearly over. |
| +func (c *Client) FenceQuantityKey(ctx context.Context, itemID string, generation int64, idempotencyKey string) (kind string, err error) { |
| + if !validID(itemID) { |
| + return "", &Error{Code: CodeInvalidID} |
| + } |
| + if generation < 0 { |
| + return "", &Error{Code: CodeInvalidParams} |
| + } |
| + form := url.Values{} |
| + form.Set("metadata[quantity_fence]", strconv.FormatInt(generation, 10)) |
| + var item SubscriptionItem |
| + err = c.do(ctx, http.MethodPost, "/v1/subscription_items/"+itemID, form, idempotencyKey, &item) |
| + if err == nil { |
| + if item.ID != itemID { |
| + return "", &Error{Code: CodeDecodeError} |
| + } |
| + return FenceTaken, nil |
| + } |
| + var refused *Error |
| + if errors.As(err, &refused) && refused.Code == CodeAPIError { |
| + switch { |
| + case refused.HTTPStatus == http.StatusBadRequest && refused.StripeType == "idempotency_error": |
| + return FenceHeldByRequest, nil |
| + case refused.HTTPStatus == http.StatusConflict: |
| + return "", nil |
| + } |
| + } |
| + return "", err |
| +} |
| + |
| +type subscriptionListResponse struct { |
| + Data []Subscription `json:"data"` |
| + HasMore bool `json:"has_more"` |
| +} |
| + |
| +const ( |
| + listPageLimit = 100 |
| + listMaxRecords = 10000 |
| +) |
| + |
| +// ListSubscriptions walks every page of Stripe's subscription list across |
| +// every status (Stripe's default list excludes canceled subscriptions, |
| +// which this package must still see to reconcile entitlement), stopping at |
| +// listMaxRecords (a runaway account list must not be read into memory |
| +// without bound) and refusing to loop forever against a cursor stuck on a |
| +// page that reports more records but returns none, or against a cursor |
| +// that revisits an id it has already seen — including a multi-page cycle |
| +// (A -> B -> A) that a same-as-last-page check alone would miss. |
| +func (c *Client) ListSubscriptions(ctx context.Context) ([]Subscription, error) { |
| + var out []Subscription |
| + cursor := "" |
| + seen := map[string]bool{} |
| + for { |
| + form := url.Values{} |
| + form.Set("limit", strconv.Itoa(listPageLimit)) |
| + form.Set("status", "all") |
| + if cursor != "" { |
| + form.Set("starting_after", cursor) |
| + } |
| + var page subscriptionListResponse |
| + if err := c.do(ctx, http.MethodGet, "/v1/subscriptions", form, "", &page); err != nil { |
| + return nil, err |
| + } |
| + if len(page.Data) == 0 { |
| + if page.HasMore { |
| + return nil, &Error{Code: CodeBrokenPagination} |
| + } |
| + break |
| + } |
| + for _, sub := range page.Data { |
| + if !validID(sub.ID) || seen[sub.ID] { |
| + return nil, &Error{Code: CodeBrokenPagination} |
| + } |
| + seen[sub.ID] = true |
| + } |
| + out = append(out, page.Data...) |
| + if len(out) > listMaxRecords { |
| + return nil, &Error{Code: CodeTooManyRecords} |
| + } |
| + if !page.HasMore { |
| + break |
| + } |
| + cursor = page.Data[len(page.Data)-1].ID |
| + } |
| + return out, nil |
| +} |
diff --git a/internal/billingstripe/client_test.go b/internal/billingstripe/client_test.go| new file mode 100644 |
| index 000000000..f49c26caf |
| --- /dev/null |
| +++ b/internal/billingstripe/client_test.go |
| @@ -0,0 +1,1005 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func testClient(t *testing.T, base string) *Client { |
| + t.Helper() |
| + c, err := NewClient("rk_test_123", WithBaseURL(base)) |
| + if err != nil { |
| + t.Fatalf("NewClient: %v", err) |
| + } |
| + return c |
| +} |
| + |
| +func validMetadata() CheckoutMetadata { |
| + return CheckoutMetadata{AccountSqid: "acct_1", IntentID: "intent_test", PriceBook: "example-v1", Currency: "eur"} |
| +} |
| + |
| +func TestNewClient_RequiresRestrictedKey(t *testing.T) { |
| + if _, err := NewClient("sk_live_full_access"); err == nil { |
| + t.Fatal("expected error for a non-restricted secret key") |
| + } |
| + if _, err := NewClient("rk_test_ok"); err != nil { |
| + t.Fatalf("unexpected error for a restricted key: %v", err) |
| + } |
| +} |
| + |
| +// --- CreateCheckout: exact form shape --- |
| + |
| +func TestCreateCheckout_FormAndHeaders(t *testing.T) { |
| + var gotMethod, gotPath string |
| + var gotHeader http.Header |
| + var gotForm map[string][]string |
| + |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotMethod = r.Method |
| + gotPath = r.URL.Path |
| + gotHeader = r.Header.Clone() |
| + if err := r.ParseForm(); err != nil { |
| + t.Fatalf("ParseForm: %v", err) |
| + } |
| + gotForm = map[string][]string(r.PostForm) |
| + w.WriteHeader(http.StatusOK) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "cs_test_1", |
| + "url": "https://checkout.stripe.com/c/pay/cs_test_1", |
| + "status": "open", |
| + "livemode": false, |
| + "currency": "eur", |
| + }) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + p := CreateCheckoutParams{ |
| + Currency: "eur", |
| + Items: []LineItem{{PriceID: "price_123", Quantity: 3}}, |
| + SuccessURL: "https://example.com/success", |
| + CancelURL: "https://example.com/cancel", |
| + CustomerID: "cus_abc", |
| + ClientReferenceID: "ref_1", |
| + Metadata: validMetadata(), |
| + } |
| + sess, err := c.CreateCheckout(context.Background(), p, "idem-key-1") |
| + if err != nil { |
| + t.Fatalf("CreateCheckout: %v", err) |
| + } |
| + if sess.ID != "cs_test_1" || sess.Status != "open" { |
| + t.Fatalf("unexpected session: %+v", sess) |
| + } |
| + |
| + if gotMethod != http.MethodPost { |
| + t.Errorf("method = %q, want POST", gotMethod) |
| + } |
| + if len(gotForm["customer_update[address]"]) != 0 || len(gotForm["billing_address_collection"]) != 0 { |
| + t.Fatal("checkout may replace validated tax country") |
| + } |
| + if gotPath != "/v1/checkout/sessions" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + if got := gotHeader.Get("Authorization"); got != "Bearer rk_test_123" { |
| + t.Errorf("Authorization = %q", got) |
| + } |
| + if got := gotHeader.Get("Stripe-Version"); got != apiVersion { |
| + t.Errorf("Stripe-Version = %q, want %q", got, apiVersion) |
| + } |
| + if got := gotHeader.Get("Idempotency-Key"); got != "idem-key-1" { |
| + t.Errorf("Idempotency-Key = %q", got) |
| + } |
| + if got := gotHeader.Get("Content-Type"); got != "application/x-www-form-urlencoded" { |
| + t.Errorf("Content-Type = %q", got) |
| + } |
| + |
| + want := map[string]string{ |
| + "mode": "subscription", |
| + "line_items[0][price]": "price_123", |
| + "line_items[0][quantity]": "3", |
| + "success_url": "https://example.com/success", |
| + "cancel_url": "https://example.com/cancel", |
| + "automatic_tax[enabled]": "true", |
| + "client_reference_id": "ref_1", |
| + "customer": "cus_abc", |
| + "allow_promotion_codes": "true", |
| + "currency": "eur", |
| + "adaptive_pricing[enabled]": "false", |
| + "metadata[account_sqid]": "acct_1", |
| + "metadata[price_book]": "example-v1", |
| + "metadata[currency]": "eur", |
| + "metadata[checkout_intent]": "intent_test", |
| + "subscription_data[metadata][account_sqid]": "acct_1", |
| + "subscription_data[metadata][price_book]": "example-v1", |
| + "subscription_data[metadata][currency]": "eur", |
| + } |
| + for k, v := range want { |
| + got := gotForm[k] |
| + if len(got) != 1 || got[0] != v { |
| + t.Errorf("form[%q] = %v, want [%q]", k, got, v) |
| + } |
| + } |
| + forbidden := []string{"payment_method_types", "currency_options", "discounts[0][coupon]", "customer_email", "metadata[terms_version]", "metadata[plan]", "metadata[band]"} |
| + for _, k := range forbidden { |
| + if _, ok := gotForm[k]; ok { |
| + t.Errorf("form unexpectedly contains %q", k) |
| + } |
| + } |
| +} |
| + |
| +func TestCreateCheckout_HouseCouponSuppressesPromotionCodes(t *testing.T) { |
| + var gotForm map[string][]string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = r.ParseForm() |
| + gotForm = map[string][]string(r.PostForm) |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1", "livemode": false, "currency": "eur"}) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", |
| + Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, |
| + SuccessURL: "https://example.com/s", |
| + CancelURL: "https://example.com/c", |
| + Metadata: validMetadata(), |
| + HouseCoupon: "house-100", |
| + } |
| + if _, err := c.CreateCheckout(context.Background(), p, "idem-2"); err != nil { |
| + t.Fatalf("CreateCheckout: %v", err) |
| + } |
| + if got := gotForm["discounts[0][coupon]"]; len(got) != 1 || got[0] != "house-100" { |
| + t.Errorf("discounts[0][coupon] = %v", got) |
| + } |
| + if _, ok := gotForm["allow_promotion_codes"]; ok { |
| + t.Error("allow_promotion_codes must be absent when a house coupon is set") |
| + } |
| +} |
| + |
| +// Prices are fixed per currency. Every session is asked for in one |
| +// currency with Adaptive Pricing off, a purchase priced from a book says |
| +// which book and currency in the metadata of the session and of the |
| +// subscription, and a session that comes back in another currency, with |
| +// Adaptive Pricing on, with a conversion, or with no currency at all, is |
| +// refused. |
| +func TestCreateCheckout_FixedCurrency(t *testing.T) { |
| + type response map[string]any |
| + ok := func(currency string) response { |
| + return response{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1", "livemode": false, "currency": currency} |
| + } |
| + with := func(r response, k string, v any) response { r[k] = v; return r } |
| + for name, tc := range map[string]struct { |
| + currency string |
| + answer response |
| + wantCode string |
| + }{ |
| + "usd": {"usd", ok("usd"), ""}, |
| + "gbp": {"gbp", ok("gbp"), ""}, |
| + "adaptive pricing reported off": {"gbp", with(ok("gbp"), "adaptive_pricing", map[string]any{"enabled": false}), ""}, |
| + "a null conversion": {"gbp", with(ok("gbp"), "currency_conversion", nil), ""}, |
| + "the session is in another": {"gbp", ok("eur"), CodeCurrencyMismatch}, |
| + "the session names no currency": {"gbp", response{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1", "livemode": false}, CodeCurrencyMismatch}, |
| + "adaptive pricing came back on": {"gbp", with(ok("gbp"), "adaptive_pricing", map[string]any{"enabled": true}), CodeCurrencyMismatch}, |
| + "the session carries a conversion": {"gbp", with(ok("gbp"), "currency_conversion", map[string]any{"source_currency": "gbp", "fx_rate": "1.2"}), CodeCurrencyMismatch}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + var gotForm map[string][]string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = r.ParseForm() |
| + gotForm = map[string][]string(r.PostForm) |
| + _ = json.NewEncoder(w).Encode(tc.answer) |
| + })) |
| + defer srv.Close() |
| + meta := validMetadata() |
| + meta.PriceBook, meta.Currency = "2026-10-01-draft1", tc.currency |
| + p := CreateCheckoutParams{CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: meta, Currency: tc.currency} |
| + sess, err := testClient(t, srv.URL).CreateCheckout(context.Background(), p, "idem-3") |
| + for k, want := range map[string]string{ |
| + "currency": tc.currency, "adaptive_pricing[enabled]": "false", |
| + "metadata[currency]": tc.currency, "metadata[price_book]": "2026-10-01-draft1", |
| + "subscription_data[metadata][currency]": tc.currency, "subscription_data[metadata][price_book]": "2026-10-01-draft1", |
| + } { |
| + if got := gotForm[k]; len(got) != 1 || got[0] != want { |
| + t.Errorf("form[%q] = %v, want %q", k, got, want) |
| + } |
| + } |
| + if tc.wantCode == "" { |
| + if err != nil || !sess.FixedCurrency(tc.currency) { |
| + t.Fatalf("CreateCheckout: %+v %v", sess, err) |
| + } |
| + return |
| + } |
| + // The refusal names the session the provider did create, so |
| + // the caller can expire it. |
| + if e, isErr := err.(*Error); !isErr || e.Code != tc.wantCode || sess != nil || e.SessionID != "cs_1" { |
| + t.Fatalf("CreateCheckout: %+v %v, want %s naming cs_1 and no session", sess, err, tc.wantCode) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A currency that is not a lower-case three-letter code, or metadata that |
| +// disagrees with it, or lacks a book or a currency, never reaches Stripe. |
| +func TestCreateCheckout_RefusesAMalformedCurrency(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1", "livemode": false, "currency": "eur"}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + base := CreateCheckoutParams{CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: validMetadata(), Currency: "eur"} |
| + for name, edit := range map[string]func(p *CreateCheckoutParams){ |
| + "no currency": func(p *CreateCheckoutParams) { p.Currency = "" }, |
| + "upper case": func(p *CreateCheckoutParams) { p.Currency = "EUR" }, |
| + "not a code": func(p *CreateCheckoutParams) { p.Currency = "euro" }, |
| + "metadata in another currency": func(p *CreateCheckoutParams) { p.Metadata.PriceBook, p.Metadata.Currency = "b1", "usd" }, |
| + "metadata with a book and no currency": func(p *CreateCheckoutParams) { p.Metadata.Currency = "" }, |
| + "metadata with a currency and no book": func(p *CreateCheckoutParams) { p.Metadata.PriceBook = "" }, |
| + } { |
| + p := base |
| + edit(&p) |
| + if _, err := c.CreateCheckout(context.Background(), p, "idem"); err == nil { |
| + t.Errorf("%s: accepted", name) |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatalf("%d requests were sent", calls) |
| + } |
| +} |
| + |
| +func TestCreateCheckout_RequiresIdempotencyKey(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cs_1", "url": "https://checkout.stripe.com/c/pay/cs_1"}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: validMetadata()} |
| + _, err := c.CreateCheckout(context.Background(), p, "") |
| + if err == nil { |
| + t.Fatal("expected an error for a missing idempotency key") |
| + } |
| + if e, ok := err.(*Error); !ok || e.Code != CodeMissingIdempotencyKey { |
| + t.Fatalf("err = %v, want CodeMissingIdempotencyKey", err) |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestCreateCheckout_MissingMetadataRejected(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c"} |
| + _, err := c.CreateCheckout(context.Background(), p, "idem") |
| + if err == nil { |
| + t.Fatal("expected an error for incomplete checkout metadata") |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestCreateCheckout_MissingIntentIDRejectedWithoutHTTPCall(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + meta := validMetadata() |
| + meta.IntentID = "" |
| + p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: meta} |
| + _, err := c.CreateCheckout(context.Background(), p, "idem") |
| + if err == nil { |
| + t.Fatal("expected an error for a missing checkout intent id") |
| + } |
| + if e, ok := err.(*Error); !ok || e.Code != CodeInvalidParams { |
| + t.Fatalf("err = %v, want CodeInvalidParams", err) |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestCreateCheckout_InvalidIntentIDRejectedWithoutHTTPCall(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + meta := validMetadata() |
| + meta.IntentID = "../../etc/passwd" |
| + p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: meta} |
| + _, err := c.CreateCheckout(context.Background(), p, "idem") |
| + if err == nil { |
| + t.Fatal("expected an error for a malformed checkout intent id") |
| + } |
| + if e, ok := err.(*Error); !ok || e.Code != CodeInvalidParams { |
| + t.Fatalf("err = %v, want CodeInvalidParams", err) |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestCreateCheckout_RejectsUnexpectedRedirectHost(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cs_1", "url": "https://evil.example.com/phish", "livemode": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + p := CreateCheckoutParams{Currency: "eur", CustomerID: "cus_abc", Items: []LineItem{{PriceID: "price_123", Quantity: 1}}, SuccessURL: "https://example.com/s", CancelURL: "https://example.com/c", Metadata: validMetadata()} |
| + _, err := c.CreateCheckout(context.Background(), p, "idem") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeUnexpectedRedirectURL { |
| + t.Fatalf("err = %v, want CodeUnexpectedRedirectURL", err) |
| + } |
| +} |
| + |
| +func TestCreatePortal_ValidatesRedirectHost(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "bps_1", "url": "https://billing.stripe.com/session/bps_1"}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + ps, err := c.CreatePortal(context.Background(), "cus_1", "https://example.com/back", "bpc_1", "idem") |
| + if err != nil { |
| + t.Fatalf("CreatePortal: %v", err) |
| + } |
| + if ps.URL != "https://billing.stripe.com/session/bps_1" { |
| + t.Fatalf("unexpected url: %s", ps.URL) |
| + } |
| +} |
| + |
| +func TestCreatePortal_RejectsBadRedirectHost(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "bps_1", "url": "https://checkout.stripe.com/session/bps_1"}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.CreatePortal(context.Background(), "cus_1", "https://example.com/back", "bpc_1", "idem") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeUnexpectedRedirectURL { |
| + t.Fatalf("err = %v, want CodeUnexpectedRedirectURL", err) |
| + } |
| +} |
| + |
| +// --- ID validation / path traversal --- |
| + |
| +func TestGetCheckout_RejectsInvalidID(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + for _, id := range []string{"../../../etc/passwd", "cs_1/../../v1/customers", "cs 1", ""} { |
| + _, err := c.GetCheckout(context.Background(), id) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidID { |
| + t.Errorf("id %q: err = %v, want CodeInvalidID", id, err) |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestGetCheckout_ExpandsSubscriptionAsID(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if got := r.URL.Query().Get("expand[]"); got != "subscription" { |
| + t.Errorf("expand[] = %q", got) |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "cs_1", "status": "complete", "payment_status": "paid", |
| + "customer": "cus_1", "subscription": "sub_1", "livemode": true, |
| + "metadata": map[string]string{"plan": "personal"}, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + sess, err := c.GetCheckout(context.Background(), "cs_1") |
| + if err != nil { |
| + t.Fatalf("GetCheckout: %v", err) |
| + } |
| + if sess.CustomerID != "cus_1" || sess.SubscriptionID != "sub_1" || sess.Subscription != nil { |
| + t.Fatalf("unexpected session: %+v", sess) |
| + } |
| + if sess.Metadata["plan"] != "personal" { |
| + t.Fatalf("metadata not decoded: %+v", sess.Metadata) |
| + } |
| +} |
| + |
| +func TestGetCheckout_ExpandsSubscriptionAsObject(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "cs_1", "status": "complete", |
| + "customer": "cus_1", "livemode": true, |
| + "subscription": map[string]any{ |
| + "id": "sub_1", "status": "active", "customer": "cus_1", "livemode": true, |
| + "created": 1700000000, "current_period_start": 1700000000, "current_period_end": 1702592000, |
| + "items": map[string]any{"data": []map[string]any{ |
| + {"id": "si_1", "quantity": 3, "price": map[string]any{"id": "price_1"}}, |
| + }}, |
| + }, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + sess, err := c.GetCheckout(context.Background(), "cs_1") |
| + if err != nil { |
| + t.Fatalf("GetCheckout: %v", err) |
| + } |
| + if sess.SubscriptionID != "sub_1" { |
| + t.Fatalf("SubscriptionID = %q", sess.SubscriptionID) |
| + } |
| + if sess.Subscription == nil { |
| + t.Fatal("expected Subscription to be populated from the expanded object") |
| + } |
| + if sess.Subscription.Status != "active" || len(sess.Subscription.Items) != 1 { |
| + t.Fatalf("unexpected expanded subscription: %+v", sess.Subscription) |
| + } |
| + if sess.Subscription.Items[0].PriceID != "price_1" || sess.Subscription.Items[0].Quantity != 3 { |
| + t.Fatalf("unexpected item: %+v", sess.Subscription.Items[0]) |
| + } |
| +} |
| + |
| +func TestExpireCheckout_RequiresIdempotencyKey(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cs_1", "status": "expired", "livemode": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + if _, err := c.ExpireCheckout(context.Background(), "cs_1", ""); err == nil { |
| + t.Fatal("expected error for missing idempotency key") |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP call, got %d", calls) |
| + } |
| + sess, err := c.ExpireCheckout(context.Background(), "cs_1", "idem-4") |
| + if err != nil { |
| + t.Fatalf("ExpireCheckout: %v", err) |
| + } |
| + if sess.Status != "expired" { |
| + t.Fatalf("status = %q", sess.Status) |
| + } |
| +} |
| + |
| +// --- GetSubscription: full field set, multi-item preserved --- |
| + |
| +func TestGetSubscription_ParsesAllFieldsAndAllItems(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/v1/subscriptions/sub_1" { |
| + t.Errorf("path = %q", r.URL.Path) |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "sub_1", "customer": "cus_1", "status": "active", "livemode": true, |
| + "created": 1700000000, "current_period_start": 1700000000, "current_period_end": 1702592000, |
| + "cancel_at_period_end": true, |
| + "metadata": map[string]string{"account_sqid": "acct_1"}, |
| + "items": map[string]any{"data": []map[string]any{ |
| + {"id": "si_1", "quantity": 2, "price": map[string]any{"id": "price_1"}}, |
| + {"id": "si_2", "quantity": 1, "price": map[string]any{"id": "price_2"}}, |
| + }}, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + sub, err := c.GetSubscription(context.Background(), "sub_1") |
| + if err != nil { |
| + t.Fatalf("GetSubscription: %v", err) |
| + } |
| + if sub.ID != "sub_1" || sub.CustomerID != "cus_1" || sub.Status != "active" || !sub.CancelAtPeriodEnd { |
| + t.Fatalf("unexpected subscription: %+v", sub) |
| + } |
| + if !sub.Created.Equal(time.Unix(1700000000, 0).UTC()) { |
| + t.Errorf("Created = %v", sub.Created) |
| + } |
| + if !sub.CurrentPeriodStart.Equal(time.Unix(1700000000, 0).UTC()) || !sub.CurrentPeriodEnd.Equal(time.Unix(1702592000, 0).UTC()) { |
| + t.Errorf("period = %v .. %v", sub.CurrentPeriodStart, sub.CurrentPeriodEnd) |
| + } |
| + if sub.Metadata["account_sqid"] != "acct_1" { |
| + t.Errorf("metadata = %+v", sub.Metadata) |
| + } |
| + // Both items must survive — this package never silently keeps only the first. |
| + if len(sub.Items) != 2 { |
| + t.Fatalf("Items = %+v, want 2", sub.Items) |
| + } |
| + if sub.Items[0].ID != "si_1" || sub.Items[0].PriceID != "price_1" || sub.Items[0].Quantity != 2 { |
| + t.Errorf("item0 = %+v", sub.Items[0]) |
| + } |
| + if sub.Items[1].ID != "si_2" || sub.Items[1].PriceID != "price_2" || sub.Items[1].Quantity != 1 { |
| + t.Errorf("item1 = %+v", sub.Items[1]) |
| + } |
| +} |
| + |
| +func TestUpdateQuantity_SendsAlwaysInvoiceProration(t *testing.T) { |
| + var gotForm map[string][]string |
| + var gotPath string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotPath = r.URL.Path |
| + _ = r.ParseForm() |
| + gotForm = map[string][]string(r.PostForm) |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "si_1", "quantity": 5, "price": map[string]any{"id": "price_1"}}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + item, err := c.UpdateQuantity(context.Background(), "si_1", 5, "idem-5") |
| + if err != nil { |
| + t.Fatalf("UpdateQuantity: %v", err) |
| + } |
| + if item.Quantity != 5 || item.PriceID != "price_1" { |
| + t.Fatalf("unexpected item: %+v", item) |
| + } |
| + if gotPath != "/v1/subscription_items/si_1" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + if got := gotForm["proration_behavior"]; len(got) != 1 || got[0] != "always_invoice" { |
| + t.Errorf("proration_behavior = %v", got) |
| + } |
| + if got := gotForm["quantity"]; len(got) != 1 || got[0] != "5" { |
| + t.Errorf("quantity = %v", got) |
| + } |
| +} |
| + |
| +func TestUpdateQuantity_RejectsInvalidItemID(t *testing.T) { |
| + c := testClient(t, "http://unused.invalid") |
| + _, err := c.UpdateQuantity(context.Background(), "../etc/passwd", 1, "idem") |
| + if e, ok := err.(*Error); !ok || e.Code != CodeInvalidID { |
| + t.Fatalf("err = %v, want CodeInvalidID", err) |
| + } |
| +} |
| + |
| +// --- ListSubscriptions: pagination, bound, broken cursor --- |
| + |
| +func TestListSubscriptions_Paginates(t *testing.T) { |
| + page1 := []string{"sub_1", "sub_2"} |
| + page2 := []string{"sub_3"} |
| + var gotCursors []string |
| + |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cursor := r.URL.Query().Get("starting_after") |
| + gotCursors = append(gotCursors, cursor) |
| + var ids []string |
| + hasMore := false |
| + if cursor == "" { |
| + ids, hasMore = page1, true |
| + } else if cursor == "sub_2" { |
| + ids, hasMore = page2, false |
| + } |
| + var data []map[string]any |
| + for _, id := range ids { |
| + data = append(data, map[string]any{"id": id, "status": "active", "customer": "cus_1", "livemode": true}) |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": data, "has_more": hasMore}) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + subs, err := c.ListSubscriptions(context.Background()) |
| + if err != nil { |
| + t.Fatalf("ListSubscriptions: %v", err) |
| + } |
| + if len(subs) != 3 { |
| + t.Fatalf("got %d subscriptions, want 3: %+v", len(subs), subs) |
| + } |
| + if subs[0].ID != "sub_1" || subs[1].ID != "sub_2" || subs[2].ID != "sub_3" { |
| + t.Fatalf("unexpected order: %+v", subs) |
| + } |
| + if len(gotCursors) != 2 || gotCursors[0] != "" || gotCursors[1] != "sub_2" { |
| + t.Fatalf("unexpected cursor sequence: %v", gotCursors) |
| + } |
| +} |
| + |
| +func TestListSubscriptions_RejectsBrokenCursor(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + // Always returns the same id and claims more exist: a cursor that |
| + // never advances must not loop forever. |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": "sub_stuck", "status": "active", "livemode": true}}, |
| + "has_more": true, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListSubscriptions(context.Background()) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeBrokenPagination { |
| + t.Fatalf("err = %v, want CodeBrokenPagination", err) |
| + } |
| + if calls != 2 { |
| + t.Fatalf("expected exactly 2 calls before detecting the stuck cursor, got %d", calls) |
| + } |
| +} |
| + |
| +func TestListSubscriptions_BoundedAt10000(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cursor := r.URL.Query().Get("starting_after") |
| + start := 0 |
| + if cursor != "" { |
| + n, err := strconv.Atoi(cursor) |
| + if err != nil { |
| + t.Fatalf("unexpected cursor %q", cursor) |
| + } |
| + start = n |
| + } |
| + var data []map[string]any |
| + for i := 0; i < listPageLimit; i++ { |
| + data = append(data, map[string]any{"id": strconv.Itoa(start + i + 1), "status": "active", "livemode": true}) |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": data, "has_more": true}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListSubscriptions(context.Background()) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeTooManyRecords { |
| + t.Fatalf("err = %v, want CodeTooManyRecords", err) |
| + } |
| +} |
| + |
| +// --- do(): redirects, size bound, timeouts, network errors, sanitized errors --- |
| + |
| +func TestDo_RefusesRedirect(t *testing.T) { |
| + evilCalls := 0 |
| + evil := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + evilCalls++ |
| + })) |
| + defer evil.Close() |
| + |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + http.Redirect(w, r, evil.URL+"/steal", http.StatusFound) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetSubscription(context.Background(), "sub_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeUnexpectedRedirect { |
| + t.Fatalf("err = %v, want CodeUnexpectedRedirect", err) |
| + } |
| + if e.HTTPStatus != http.StatusFound { |
| + t.Errorf("HTTPStatus = %d", e.HTTPStatus) |
| + } |
| + if evilCalls != 0 { |
| + t.Fatalf("the redirect target must never be contacted, got %d calls", evilCalls) |
| + } |
| +} |
| + |
| +func TestDo_BoundedResponseSize(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusOK) |
| + buf := make([]byte, maxResponseBytes+1024) |
| + for i := range buf { |
| + buf[i] = ' ' |
| + } |
| + _, _ = w.Write(buf) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetSubscription(context.Background(), "sub_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeResponseTooLarge { |
| + t.Fatalf("err = %v, want CodeResponseTooLarge", err) |
| + } |
| +} |
| + |
| +func TestDo_TimeoutClassification(t *testing.T) { |
| + block := make(chan struct{}) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + <-block |
| + })) |
| + defer func() { |
| + close(block) |
| + srv.Close() |
| + }() |
| + |
| + c := testClient(t, srv.URL) |
| + c.httpClient.Timeout = 50 * time.Millisecond // same-package test: override the 15s default directly |
| + |
| + _, err := c.GetSubscription(context.Background(), "sub_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeTimeout { |
| + t.Fatalf("err = %v, want CodeTimeout", err) |
| + } |
| +} |
| + |
| +func TestDo_NetworkErrorClassification(t *testing.T) { |
| + // A port nothing listens on: connection refused immediately, not a timeout. |
| + l, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatalf("listen: %v", err) |
| + } |
| + addr := l.Addr().String() |
| + l.Close() // now guaranteed unused for this test's duration |
| + |
| + c := testClient(t, "http://"+addr) |
| + _, err = c.GetSubscription(context.Background(), "sub_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeNetwork { |
| + t.Fatalf("err = %v, want CodeNetwork", err) |
| + } |
| +} |
| + |
| +func TestDo_APIErrorSanitized(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusPaymentRequired) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "error": map[string]any{ |
| + "type": "card_error", |
| + "code": "card_declined", |
| + "message": "Sensitive: card ending 4242 held by Jane Roe <jane@example.com>", |
| + "param": "customer[email]", |
| + }, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetSubscription(context.Background(), "sub_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeAPIError { |
| + t.Fatalf("err = %v, want CodeAPIError", err) |
| + } |
| + if e.HTTPStatus != http.StatusPaymentRequired || e.StripeType != "card_error" || e.StripeCode != "card_declined" { |
| + t.Fatalf("unexpected fields: %+v", e) |
| + } |
| + msg := e.Error() |
| + for _, secret := range []string{"4242", "Jane Roe", "jane@example.com", "customer[email]", "Sensitive"} { |
| + if strings.Contains(msg, secret) { |
| + t.Fatalf("Error() leaked response-body content %q: %s", secret, msg) |
| + } |
| + } |
| +} |
| + |
| +// --- Strict decode: Session/Subscription reject null / missing / invalid id / missing livemode --- |
| + |
| +func TestSessionUnmarshalJSON_Strictness(t *testing.T) { |
| + if err := json.Unmarshal([]byte(`{"id":"cs_1","livemode":false}`), &Session{}); err != nil { |
| + t.Fatalf("valid session with explicit livemode:false: %v", err) |
| + } |
| + cases := map[string]string{ |
| + "null body": `null`, |
| + "missing id": `{"livemode":false}`, |
| + "empty id": `{"id":"","livemode":false}`, |
| + "invalid id shape": `{"id":"cs 1","livemode":false}`, |
| + "path traversal id": `{"id":"../../v1/customers","livemode":false}`, |
| + "missing livemode": `{"id":"cs_1"}`, |
| + "null livemode": `{"id":"cs_1","livemode":null}`, |
| + } |
| + for name, body := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + var s Session |
| + if err := json.Unmarshal([]byte(body), &s); err == nil { |
| + t.Fatalf("%s: expected error, got session %+v", name, s) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSessionUnmarshalJSON_ResetsStaleFieldsWhenAbsent(t *testing.T) { |
| + s := Session{ |
| + BillingCountry: "US", |
| + Subscription: &Subscription{ID: "sub_old"}, |
| + } |
| + full := `{"id":"cs_1","livemode":true,"customer_details":{"address":{"country":"DE"}},"subscription":"sub_1"}` |
| + if err := json.Unmarshal([]byte(full), &s); err != nil { |
| + t.Fatalf("decode full: %v", err) |
| + } |
| + if s.BillingCountry != "DE" || s.SubscriptionID != "sub_1" { |
| + t.Fatalf("unexpected after full decode: %+v", s) |
| + } |
| + // Re-decoding a response with no customer_details and a bare (not |
| + // expanded) subscription id must not let the previous BillingCountry or |
| + // expanded Subscription object survive on a struct that gets reused. |
| + minimal := `{"id":"cs_2","livemode":true,"subscription":"sub_2"}` |
| + if err := json.Unmarshal([]byte(minimal), &s); err != nil { |
| + t.Fatalf("decode minimal: %v", err) |
| + } |
| + if s.BillingCountry != "" { |
| + t.Errorf("BillingCountry = %q, want cleared", s.BillingCountry) |
| + } |
| + if s.Subscription != nil { |
| + t.Errorf("Subscription = %+v, want nil (no expanded object in this response)", s.Subscription) |
| + } |
| + if s.SubscriptionID != "sub_2" { |
| + t.Errorf("SubscriptionID = %q", s.SubscriptionID) |
| + } |
| +} |
| + |
| +func TestSubscriptionUnmarshalJSON_Strictness(t *testing.T) { |
| + if err := json.Unmarshal([]byte(`{"id":"sub_1","livemode":false}`), &Subscription{}); err != nil { |
| + t.Fatalf("valid subscription with explicit livemode:false: %v", err) |
| + } |
| + cases := map[string]string{ |
| + "null body": `null`, |
| + "missing id": `{"livemode":false}`, |
| + "empty id": `{"id":"","livemode":false}`, |
| + "invalid id shape": `{"id":"sub 1","livemode":false}`, |
| + "path traversal id": `{"id":"../../v1/customers","livemode":false}`, |
| + "missing livemode": `{"id":"sub_1"}`, |
| + "null livemode": `{"id":"sub_1","livemode":null}`, |
| + } |
| + for name, body := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + var s Subscription |
| + if err := json.Unmarshal([]byte(body), &s); err == nil { |
| + t.Fatalf("%s: expected error, got subscription %+v", name, s) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSubscriptionUnmarshalJSON_ResetsStaleFieldsWhenAbsent(t *testing.T) { |
| + s := Subscription{ |
| + Metadata: map[string]string{"account_sqid": "acct_old"}, |
| + Items: []SubscriptionItem{{ID: "si_old"}}, |
| + } |
| + minimal := `{"id":"sub_1","livemode":true,"status":"active"}` |
| + if err := json.Unmarshal([]byte(minimal), &s); err != nil { |
| + t.Fatalf("decode: %v", err) |
| + } |
| + if s.Metadata != nil { |
| + t.Errorf("Metadata = %+v, want nil (absent in this response)", s.Metadata) |
| + } |
| + if len(s.Items) != 0 { |
| + t.Errorf("Items = %+v, want empty (absent in this response)", s.Items) |
| + } |
| +} |
| + |
| +// --- ListSubscriptions: all statuses requested, empty+has_more, multi-page cycle --- |
| + |
| +func TestListSubscriptions_RequestsAllStatuses(t *testing.T) { |
| + var gotStatus string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotStatus = r.URL.Query().Get("status") |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}, "has_more": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + if _, err := c.ListSubscriptions(context.Background()); err != nil { |
| + t.Fatalf("ListSubscriptions: %v", err) |
| + } |
| + if gotStatus != "all" { |
| + t.Errorf("status = %q, want all — the default list excludes canceled subscriptions", gotStatus) |
| + } |
| +} |
| + |
| +func TestListSubscriptions_EmptyPageWithHasMoreIsBrokenPagination(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}, "has_more": true}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListSubscriptions(context.Background()) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeBrokenPagination { |
| + t.Fatalf("err = %v, want CodeBrokenPagination", err) |
| + } |
| +} |
| + |
| +func TestListSubscriptions_DetectsMultiPageCycle(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + var id string |
| + switch r.URL.Query().Get("starting_after") { |
| + case "": |
| + id = "sub_a" |
| + case "sub_a": |
| + id = "sub_b" |
| + case "sub_b": |
| + id = "sub_a" // A -> B -> A: a same-as-last-page check alone would miss this. |
| + default: |
| + t.Fatalf("unexpected cursor %q", r.URL.Query().Get("starting_after")) |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "data": []map[string]any{{"id": id, "status": "active", "livemode": true}}, |
| + "has_more": true, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.ListSubscriptions(context.Background()) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeBrokenPagination { |
| + t.Fatalf("err = %v, want CodeBrokenPagination", err) |
| + } |
| + if calls != 3 { |
| + t.Fatalf("expected exactly 3 calls before detecting the cycle, got %d", calls) |
| + } |
| +} |
| + |
| +// --- Client: the secret key never appears in an accidental %v/%+v/%#v --- |
| + |
| +func TestClient_StringRedactsSecretKey(t *testing.T) { |
| + c := testClient(t, "http://unused.invalid") |
| + forms := []string{c.String(), c.GoString(), fmt.Sprintf("%v", c), fmt.Sprintf("%+v", c), fmt.Sprintf("%#v", c)} |
| + for _, s := range forms { |
| + if strings.Contains(s, "rk_test_123") { |
| + t.Fatalf("secret key leaked: %s", s) |
| + } |
| + } |
| +} |
| + |
| +func TestDo_PinnedAPIVersionOnEveryRequest(t *testing.T) { |
| + var got []string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + got = append(got, r.Header.Get("Stripe-Version")) |
| + _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{}, "has_more": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, _ = c.ListSubscriptions(context.Background()) |
| + if len(got) == 0 { |
| + t.Fatal("no requests observed") |
| + } |
| + for _, v := range got { |
| + if v != "2025-02-24.acacia" { |
| + t.Errorf("Stripe-Version = %q", v) |
| + } |
| + } |
| +} |
| + |
| +// The fence request carries the operation's key and nothing that is billed: |
| +// no quantity, no proration. What the provider answers decides what is |
| +// known about the key, and only two answers say anything holds it. |
| +func TestFenceQuantityKey(t *testing.T) { |
| + cases := []struct { |
| + name string |
| + status int |
| + body string |
| + wantKind string |
| + wantErr bool |
| + }{ |
| + {"the update ran: the key is now this request's", 200, `{"id":"si_1","quantity":10,"price":{"id":"price_1"}}`, FenceTaken, false}, |
| + {"refused as a parameter mismatch: the key is the quantity update's", 400, `{"error":{"type":"idempotency_error","message":"Keys for idempotent requests can only be used with the same parameters they were first used with."}}`, FenceHeldByRequest, false}, |
| + {"a request under the key is executing: ask again", 409, `{"error":{"type":"idempotency_error","code":"idempotency_key_in_use"}}`, "", false}, |
| + {"a missing item holds nothing: a 404 saves no result", 404, `{"error":{"type":"invalid_request_error","code":"resource_missing","message":"No such subscription item"}}`, "", true}, |
| + {"a server error holds nothing", 500, `{"error":{"type":"api_error"}}`, "", true}, |
| + {"another refusal holds nothing", 400, `{"error":{"type":"invalid_request_error","code":"parameter_missing"}}`, "", true}, |
| + {"a mismatch answered with another status holds nothing", 402, `{"error":{"type":"idempotency_error"}}`, "", true}, |
| + {"rate limited holds nothing", 429, `{"error":{"type":"rate_limit_error"}}`, "", true}, |
| + {"an answer for another item holds nothing", 200, `{"id":"si_other","quantity":10,"price":{"id":"price_1"}}`, "", true}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + var form map[string][]string |
| + var key, path string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = r.ParseForm() |
| + form, key, path = r.PostForm, r.Header.Get("Idempotency-Key"), r.URL.Path |
| + w.WriteHeader(tc.status) |
| + _, _ = w.Write([]byte(tc.body)) |
| + })) |
| + defer srv.Close() |
| + kind, err := testClient(t, srv.URL).FenceQuantityKey(context.Background(), "si_1", 7, "op-key") |
| + if kind != tc.wantKind || (err != nil) != tc.wantErr { |
| + t.Fatalf("kind=%q err=%v, want kind=%q err=%v", kind, err, tc.wantKind, tc.wantErr) |
| + } |
| + if path != "/v1/subscription_items/si_1" || key != "op-key" { |
| + t.Fatalf("sent to %q under key %q", path, key) |
| + } |
| + if len(form) != 1 || len(form["metadata[quantity_fence]"]) != 1 || form["metadata[quantity_fence]"][0] != "7" { |
| + t.Fatalf("the fence request carries more than its marker: %v", form) |
| + } |
| + }) |
| + } |
| + c := testClient(t, "http://127.0.0.1:1") |
| + if _, err := c.FenceQuantityKey(context.Background(), "../x", 1, "k"); err == nil { |
| + t.Fatal("an invalid item id was accepted") |
| + } |
| + if _, err := c.FenceQuantityKey(context.Background(), "si_1", 1, ""); err == nil { |
| + t.Fatal("a fence with no key was accepted") |
| + } |
| +} |
diff --git a/internal/billingstripe/customer.go b/internal/billingstripe/customer.go| new file mode 100644 |
| index 000000000..2f45081ba |
| --- /dev/null |
| +++ b/internal/billingstripe/customer.go |
| @@ -0,0 +1,208 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "regexp" |
| + "unicode" |
| +) |
| + |
| +// maxPostalCodeLen bounds a field this package forwards verbatim into a |
| +// form value and, on decode, never persists — but an unbounded string is |
| +// still a way to inflate a request or a log line. |
| +const maxPostalCodeLen = 20 |
| + |
| +// isoCountryRe enforces ISO 3166-1 alpha-2: exactly two upper-case ASCII |
| +// letters. Stripe's address[country] accepts nothing else, and the two-letter |
| +// shape also rejects every control character by construction. |
| +var isoCountryRe = regexp.MustCompile(`^[A-Z]{2}$`) |
| + |
| +func validCountry(country string) bool { return isoCountryRe.MatchString(country) } |
| + |
| +// noControlChars guards free-form fields (postal code, account sqid) that |
| +// carry no charset restriction of their own: a control character has no |
| +// business in a billing address or an error log. |
| +func noControlChars(s string) bool { |
| + for _, r := range s { |
| + if unicode.IsControl(r) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func validPostalCode(postal string) bool { |
| + return len(postal) <= maxPostalCodeLen && noControlChars(postal) |
| +} |
| + |
| +// CustomerParams is exactly the billing location Stripe's tax engine needs. |
| +// Deliberately absent: name, email, line1/2, city, state — this package |
| +// never collects, stores or forwards a customer's full billing identity, |
| +// only the country (and, where Stripe requires it, postal code) automatic |
| +// tax actually consumes. |
| +type CustomerParams struct { |
| + Country string // ISO 3166-1 alpha-2, upper case (e.g. "US") |
| + PostalCode string // optional; Stripe requires it for US, CA, IN |
| + AccountSqid string |
| + IntentID string |
| +} |
| + |
| +func (p CustomerParams) valid() bool { |
| + if !validCountry(p.Country) { |
| + return false |
| + } |
| + if p.AccountSqid == "" || !noControlChars(p.AccountSqid) { |
| + return false |
| + } |
| + if !validID(p.IntentID) { |
| + return false |
| + } |
| + return validPostalCode(p.PostalCode) |
| +} |
| + |
| +func (p CustomerParams) setMetadata(form url.Values) { |
| + form.Set("metadata[account_sqid]", p.AccountSqid) |
| + form.Set("metadata[checkout_intent]", p.IntentID) |
| +} |
| + |
| +// Customer is a Stripe Customer trimmed to exactly what the tax-location |
| +// flow needs to verify: which country Stripe is actually taxing at, and |
| +// whether a saved shipping address exists to contest that (a shipping |
| +// address wins over the billing address for tax purposes, so its mere |
| +// presence — never its content — is what callers need). Deliberately |
| +// absent: name, email, phone, the rest of the address, and any payment |
| +// method; this package never stores or exposes a customer's full billing |
| +// identity or card details. |
| +type Customer struct { |
| + ID string |
| + LiveMode bool |
| + Country string |
| + HasShipping bool |
| + AutomaticTax string // tax.automatic_tax: "supported", "not_collecting", "unrecognized_location", "failed", or "" when tax was not expanded |
| + TaxCountry string // tax.location.country; "" when tax was not expanded or has no location yet |
| + Metadata map[string]string |
| +} |
| + |
| +// UnmarshalJSON decodes a Customer strictly enough that a null response |
| +// body, or one missing "id" or "livemode", cannot pass. Both fields decode |
| +// through pointers specifically so a caller can tell "absent" from "present |
| +// and zero": a naive struct would decode a null object into LiveMode=false, |
| +// which reads as test mode when the response in fact proved nothing at all. |
| +func (cus *Customer) UnmarshalJSON(b []byte) error { |
| + var raw struct { |
| + ID *string `json:"id"` |
| + LiveMode *bool `json:"livemode"` |
| + Address *struct { |
| + Country string `json:"country"` |
| + } `json:"address"` |
| + Shipping json.RawMessage `json:"shipping"` |
| + Metadata map[string]string `json:"metadata"` |
| + Tax *struct { |
| + AutomaticTax string `json:"automatic_tax"` |
| + Location *struct { |
| + Country string `json:"country"` |
| + } `json:"location"` |
| + } `json:"tax"` |
| + } |
| + if err := json.Unmarshal(b, &raw); err != nil { |
| + return err |
| + } |
| + if raw.ID == nil || *raw.ID == "" || raw.LiveMode == nil { |
| + return errors.New("billingstripe: customer response missing id or livemode") |
| + } |
| + if !validID(*raw.ID) { |
| + return errors.New("billingstripe: customer id has unexpected shape") |
| + } |
| + cus.ID = *raw.ID |
| + cus.LiveMode = *raw.LiveMode |
| + if raw.Address != nil { |
| + cus.Country = raw.Address.Country |
| + } |
| + cus.HasShipping = len(raw.Shipping) > 0 && string(raw.Shipping) != "null" |
| + cus.Metadata = raw.Metadata |
| + if raw.Tax != nil { |
| + cus.AutomaticTax = raw.Tax.AutomaticTax |
| + if raw.Tax.Location != nil { |
| + cus.TaxCountry = raw.Tax.Location.Country |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// CreateCustomer creates a Stripe Customer carrying only a billing country |
| +// (and, when given, a postal code) plus the account/intent metadata |
| +// entitlement needs to attribute the customer later. tax[validate_location] |
| +// is set to "immediately" so a location Stripe's tax engine cannot resolve |
| +// fails the create outright, before any Checkout Session — and so before |
| +// any payment — is ever created against it. |
| +func (c *Client) CreateCustomer(ctx context.Context, p CustomerParams, idempotencyKey string) (*Customer, error) { |
| + if !p.valid() { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + form := url.Values{} |
| + form.Set("address[country]", p.Country) |
| + if p.PostalCode != "" { |
| + form.Set("address[postal_code]", p.PostalCode) |
| + } |
| + form.Set("tax[validate_location]", "immediately") |
| + p.setMetadata(form) |
| + |
| + var cus Customer |
| + if err := c.do(ctx, http.MethodPost, "/v1/customers", form, idempotencyKey, &cus); err != nil { |
| + return nil, err |
| + } |
| + return &cus, nil |
| +} |
| + |
| +// UpdateCustomerLocation overwrites an existing Customer's billing location. |
| +// Unlike CreateCustomer, it always sends address[postal_code] — as the given |
| +// value, or as "" to clear one left over from a previous country — because a |
| +// stale postal code from an earlier update must not silently keep steering |
| +// tax at the old jurisdiction. line1, line2, city, state and shipping are |
| +// cleared for the same reason: a saved shipping address, in particular, |
| +// takes priority over the billing address for tax purposes, so leaving one |
| +// in place would make this update a no-op from the tax engine's point of |
| +// view. |
| +func (c *Client) UpdateCustomerLocation(ctx context.Context, id string, p CustomerParams, idempotencyKey string) (*Customer, error) { |
| + if !validID(id) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + if !p.valid() { |
| + return nil, &Error{Code: CodeInvalidParams} |
| + } |
| + form := url.Values{} |
| + form.Set("address[country]", p.Country) |
| + form.Set("address[postal_code]", p.PostalCode) |
| + form.Set("address[line1]", "") |
| + form.Set("address[line2]", "") |
| + form.Set("address[city]", "") |
| + form.Set("address[state]", "") |
| + form.Set("shipping", "") |
| + form.Set("tax[validate_location]", "immediately") |
| + p.setMetadata(form) |
| + |
| + var cus Customer |
| + if err := c.do(ctx, http.MethodPost, "/v1/customers/"+id, form, idempotencyKey, &cus); err != nil { |
| + return nil, err |
| + } |
| + return &cus, nil |
| +} |
| + |
| +// GetCustomer reads back a Customer with tax expanded, so the country |
| +// automatic tax actually resolved (and whether a shipping address exists to |
| +// override it) is available in one call. |
| +func (c *Client) GetCustomer(ctx context.Context, id string) (*Customer, error) { |
| + if !validID(id) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + form := url.Values{} |
| + form.Add("expand[]", "tax") |
| + var cus Customer |
| + if err := c.do(ctx, http.MethodGet, "/v1/customers/"+id, form, "", &cus); err != nil { |
| + return nil, err |
| + } |
| + return &cus, nil |
| +} |
diff --git a/internal/billingstripe/customer_test.go b/internal/billingstripe/customer_test.go| new file mode 100644 |
| index 000000000..726dee759 |
| --- /dev/null |
| +++ b/internal/billingstripe/customer_test.go |
| @@ -0,0 +1,489 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "reflect" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func validCustomerParams() CustomerParams { |
| + return CustomerParams{Country: "US", PostalCode: "10001", AccountSqid: "acct_1", IntentID: "intent_test"} |
| +} |
| + |
| +// --- CreateCustomer: exact form shape --- |
| + |
| +func TestCreateCustomer_FormAndHeaders(t *testing.T) { |
| + var gotMethod, gotPath string |
| + var gotHeader http.Header |
| + var gotForm map[string][]string |
| + |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotMethod = r.Method |
| + gotPath = r.URL.Path |
| + gotHeader = r.Header.Clone() |
| + if err := r.ParseForm(); err != nil { |
| + t.Fatalf("ParseForm: %v", err) |
| + } |
| + gotForm = map[string][]string(r.PostForm) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "cus_1", "livemode": false, |
| + "address": map[string]any{"country": "US"}, |
| + "shipping": nil, |
| + "metadata": map[string]string{"account_sqid": "acct_1", "checkout_intent": "intent_test"}, |
| + }) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + cus, err := c.CreateCustomer(context.Background(), validCustomerParams(), "idem-cus-1") |
| + if err != nil { |
| + t.Fatalf("CreateCustomer: %v", err) |
| + } |
| + if cus.ID != "cus_1" || cus.LiveMode { |
| + t.Fatalf("unexpected customer: %+v", cus) |
| + } |
| + |
| + if gotMethod != http.MethodPost { |
| + t.Errorf("method = %q, want POST", gotMethod) |
| + } |
| + if gotPath != "/v1/customers" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + if got := gotHeader.Get("Idempotency-Key"); got != "idem-cus-1" { |
| + t.Errorf("Idempotency-Key = %q", got) |
| + } |
| + |
| + want := map[string]string{ |
| + "address[country]": "US", |
| + "address[postal_code]": "10001", |
| + "tax[validate_location]": "immediately", |
| + "metadata[account_sqid]": "acct_1", |
| + "metadata[checkout_intent]": "intent_test", |
| + } |
| + for k, v := range want { |
| + got := gotForm[k] |
| + if len(got) != 1 || got[0] != v { |
| + t.Errorf("form[%q] = %v, want [%q]", k, got, v) |
| + } |
| + } |
| + forbidden := []string{"address[line1]", "address[line2]", "address[city]", "address[state]", "shipping", "name", "email"} |
| + for _, k := range forbidden { |
| + if _, ok := gotForm[k]; ok { |
| + t.Errorf("create form unexpectedly contains %q", k) |
| + } |
| + } |
| +} |
| + |
| +func TestCreateCustomer_PostalCodeOmittedWhenEmpty(t *testing.T) { |
| + var gotForm map[string][]string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = r.ParseForm() |
| + gotForm = map[string][]string(r.PostForm) |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cus_1", "livemode": false}) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + p := CustomerParams{Country: "GB", AccountSqid: "acct_1", IntentID: "intent_test"} |
| + if _, err := c.CreateCustomer(context.Background(), p, "idem-cus-2"); err != nil { |
| + t.Fatalf("CreateCustomer: %v", err) |
| + } |
| + if _, ok := gotForm["address[postal_code]"]; ok { |
| + t.Errorf("address[postal_code] must be absent when PostalCode is empty on create, got %v", gotForm["address[postal_code]"]) |
| + } |
| +} |
| + |
| +func TestCreateCustomer_RequiresIdempotencyKey(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cus_1", "livemode": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.CreateCustomer(context.Background(), validCustomerParams(), "") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeMissingIdempotencyKey { |
| + t.Fatalf("err = %v, want CodeMissingIdempotencyKey", err) |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +// --- Invalid params: never reach the network --- |
| + |
| +func TestCreateCustomer_InvalidCountryRejected(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + |
| + for _, country := range []string{"", "us", "USA", "U", "U1", "U\x00", "**"} { |
| + p := validCustomerParams() |
| + p.Country = country |
| + _, err := c.CreateCustomer(context.Background(), p, "idem") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidParams { |
| + t.Errorf("country %q: err = %v, want CodeInvalidParams", country, err) |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestCreateCustomer_InvalidPostalCodeRejected(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + |
| + longPostal := strings.Repeat("1", maxPostalCodeLen+1) |
| + for _, postal := range []string{longPostal, "1000\x00", "10\n01", "10\t01"} { |
| + p := validCustomerParams() |
| + p.PostalCode = postal |
| + _, err := c.CreateCustomer(context.Background(), p, "idem") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidParams { |
| + t.Errorf("postal %q: err = %v, want CodeInvalidParams", postal, err) |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestCreateCustomer_MissingMetadataRejected(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + |
| + p := validCustomerParams() |
| + p.AccountSqid = "" |
| + if _, err := c.CreateCustomer(context.Background(), p, "idem"); err == nil { |
| + t.Error("expected error for empty AccountSqid") |
| + } |
| + |
| + p = validCustomerParams() |
| + p.IntentID = "" |
| + if _, err := c.CreateCustomer(context.Background(), p, "idem"); err == nil { |
| + t.Error("expected error for empty IntentID") |
| + } |
| + |
| + p = validCustomerParams() |
| + p.IntentID = "../../v1/customers" |
| + if _, err := c.CreateCustomer(context.Background(), p, "idem"); err == nil { |
| + t.Error("expected error for a malformed IntentID") |
| + } |
| + |
| + p = validCustomerParams() |
| + p.AccountSqid = "acct\x001" |
| + if _, err := c.CreateCustomer(context.Background(), p, "idem"); err == nil { |
| + t.Error("expected error for a control character in AccountSqid") |
| + } |
| + |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +// --- UpdateCustomerLocation: clears stale fields --- |
| + |
| +func TestUpdateCustomerLocation_FormClearsStaleFieldsAndPostalCode(t *testing.T) { |
| + var gotPath string |
| + var gotForm map[string][]string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotPath = r.URL.Path |
| + _ = r.ParseForm() |
| + gotForm = map[string][]string(r.PostForm) |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cus_1", "livemode": false}) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + p := CustomerParams{Country: "GB", AccountSqid: "acct_1", IntentID: "intent_test"} // no postal code |
| + if _, err := c.UpdateCustomerLocation(context.Background(), "cus_1", p, "idem-upd-1"); err != nil { |
| + t.Fatalf("UpdateCustomerLocation: %v", err) |
| + } |
| + if gotPath != "/v1/customers/cus_1" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + want := map[string]string{ |
| + "address[country]": "GB", |
| + "address[postal_code]": "", // clears a stale postal code from a prior US/CA/IN update |
| + "address[line1]": "", |
| + "address[line2]": "", |
| + "address[city]": "", |
| + "address[state]": "", |
| + "shipping": "", |
| + "tax[validate_location]": "immediately", |
| + } |
| + for k, v := range want { |
| + got, ok := gotForm[k] |
| + if !ok || len(got) != 1 || got[0] != v { |
| + t.Errorf("form[%q] = %v (present=%v), want [%q]", k, got, ok, v) |
| + } |
| + } |
| +} |
| + |
| +func TestUpdateCustomerLocation_SendsGivenPostalCode(t *testing.T) { |
| + var gotForm map[string][]string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = r.ParseForm() |
| + gotForm = map[string][]string(r.PostForm) |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cus_1", "livemode": false}) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + p := validCustomerParams() // PostalCode: "10001" |
| + if _, err := c.UpdateCustomerLocation(context.Background(), "cus_1", p, "idem-upd-2"); err != nil { |
| + t.Fatalf("UpdateCustomerLocation: %v", err) |
| + } |
| + if got := gotForm["address[postal_code]"]; len(got) != 1 || got[0] != "10001" { |
| + t.Errorf("address[postal_code] = %v, want [10001]", got) |
| + } |
| +} |
| + |
| +func TestUpdateCustomerLocation_RejectsInvalidID(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + for _, id := range []string{"../../../etc/passwd", "cus_1/../../v1/customers", "cus 1", ""} { |
| + _, err := c.UpdateCustomerLocation(context.Background(), id, validCustomerParams(), "idem") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidID { |
| + t.Errorf("id %q: err = %v, want CodeInvalidID", id, err) |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestUpdateCustomerLocation_RequiresIdempotencyKey(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cus_1", "livemode": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.UpdateCustomerLocation(context.Background(), "cus_1", validCustomerParams(), "") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeMissingIdempotencyKey { |
| + t.Fatalf("err = %v, want CodeMissingIdempotencyKey", err) |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +// --- GetCustomer: tax expand, DTO decoding, shipping null vs present --- |
| + |
| +func TestGetCustomer_RequestsTaxExpand(t *testing.T) { |
| + var gotPath, gotExpand string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotPath = r.URL.Path |
| + gotExpand = r.URL.Query().Get("expand[]") |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cus_1", "livemode": true}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + if _, err := c.GetCustomer(context.Background(), "cus_1"); err != nil { |
| + t.Fatalf("GetCustomer: %v", err) |
| + } |
| + if gotPath != "/v1/customers/cus_1" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + if gotExpand != "tax" { |
| + t.Errorf("expand[] = %q, want tax", gotExpand) |
| + } |
| +} |
| + |
| +func TestGetCustomer_RejectsInvalidID(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + for _, id := range []string{"../../../etc/passwd", "cus_1/../../v1/customers", "cus 1", ""} { |
| + _, err := c.GetCustomer(context.Background(), id) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidID { |
| + t.Errorf("id %q: err = %v, want CodeInvalidID", id, err) |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestGetCustomer_DecodesDTOFields(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "cus_1", "livemode": true, |
| + "address": map[string]any{"country": "US"}, |
| + "shipping": nil, |
| + "metadata": map[string]string{"account_sqid": "acct_1", "checkout_intent": "intent_test"}, |
| + "tax": map[string]any{ |
| + "automatic_tax": "supported", |
| + "location": map[string]any{"country": "US"}, |
| + }, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + cus, err := c.GetCustomer(context.Background(), "cus_1") |
| + if err != nil { |
| + t.Fatalf("GetCustomer: %v", err) |
| + } |
| + if cus.ID != "cus_1" || !cus.LiveMode || cus.Country != "US" || cus.HasShipping { |
| + t.Fatalf("unexpected customer: %+v", cus) |
| + } |
| + if cus.AutomaticTax != "supported" || cus.TaxCountry != "US" { |
| + t.Fatalf("unexpected tax fields: %+v", cus) |
| + } |
| + if cus.Metadata["account_sqid"] != "acct_1" || cus.Metadata["checkout_intent"] != "intent_test" { |
| + t.Fatalf("unexpected metadata: %+v", cus.Metadata) |
| + } |
| +} |
| + |
| +func TestGetCustomer_ShippingNullVersusPresent(t *testing.T) { |
| + cases := []struct { |
| + name string |
| + shipping any |
| + want bool |
| + }{ |
| + {"null", nil, false}, |
| + {"present", map[string]any{"address": map[string]any{"country": "CA"}}, true}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "id": "cus_1", "livemode": false, "shipping": tc.shipping, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + cus, err := c.GetCustomer(context.Background(), "cus_1") |
| + if err != nil { |
| + t.Fatalf("GetCustomer: %v", err) |
| + } |
| + if cus.HasShipping != tc.want { |
| + t.Errorf("HasShipping = %v, want %v", cus.HasShipping, tc.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// --- Decode strictness: null object / missing id / missing livemode must not masquerade as test mode --- |
| + |
| +func TestGetCustomer_RejectsNullObject(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _, _ = w.Write([]byte("null")) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetCustomer(context.Background(), "cus_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +func TestGetCustomer_RejectsMissingID(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"livemode": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetCustomer(context.Background(), "cus_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +func TestGetCustomer_RejectsMissingLiveMode(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cus_1"}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetCustomer(context.Background(), "cus_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| + // A response missing livemode must error, not silently decode livemode |
| + // as its Go zero value (false) and let a caller mistake it for test mode. |
| +} |
| + |
| +func TestGetCustomer_RejectsMalformedID(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "../../v1/customers", "livemode": false}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetCustomer(context.Background(), "cus_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +// --- DTO is minimal: no name/email/address-line/card field ever gets added silently --- |
| + |
| +func TestCustomer_DTOHasNoBillingIdentityFields(t *testing.T) { |
| + allowed := map[string]bool{ |
| + "ID": true, "LiveMode": true, "Country": true, "HasShipping": true, |
| + "AutomaticTax": true, "TaxCountry": true, "Metadata": true, |
| + } |
| + typ := reflect.TypeOf(Customer{}) |
| + for i := 0; i < typ.NumField(); i++ { |
| + name := typ.Field(i).Name |
| + if !allowed[name] { |
| + t.Errorf("Customer gained an unexpected field %q — this DTO must never carry name/email/address/card", name) |
| + } |
| + } |
| + if typ.NumField() != len(allowed) { |
| + t.Errorf("Customer has %d fields, want exactly %d", typ.NumField(), len(allowed)) |
| + } |
| +} |
| + |
| +// --- No secret or PII in error output --- |
| + |
| +func TestCustomer_APIErrorSanitized(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusBadRequest) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "error": map[string]any{ |
| + "type": "invalid_request_error", |
| + "code": "parameter_invalid_integer", |
| + "message": "Sensitive: postal code 10001 for Jane Roe <jane@example.com>", |
| + "param": "address[postal_code]", |
| + }, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.CreateCustomer(context.Background(), validCustomerParams(), "idem") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeAPIError { |
| + t.Fatalf("err = %v, want CodeAPIError", err) |
| + } |
| + msg := e.Error() |
| + for _, secret := range []string{"10001", "Jane Roe", "jane@example.com", "address[postal_code]", "Sensitive", c.secretKey} { |
| + if strings.Contains(msg, secret) { |
| + t.Fatalf("Error() leaked sensitive content %q: %s", secret, msg) |
| + } |
| + } |
| +} |
diff --git a/internal/billingstripe/merchant.go b/internal/billingstripe/merchant.go| new file mode 100644 |
| index 000000000..18f0e3de6 |
| --- /dev/null |
| +++ b/internal/billingstripe/merchant.go |
| @@ -0,0 +1,74 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "strings" |
| +) |
| + |
| +// MerchantAccount reads the account belonging to the credential, without a |
| +// Connect account selector. The caller pins its expected merchant ID. |
| +func (c *Client) MerchantAccount(ctx context.Context) (string, error) { |
| + var account struct { |
| + ID string `json:"id"` |
| + } |
| + if err := c.do(ctx, http.MethodGet, "/v1/account", nil, "", &account); err != nil { |
| + return "", err |
| + } |
| + if !validID(account.ID) || !strings.HasPrefix(account.ID, "acct_") { |
| + return "", &Error{Code: CodeDecodeError} |
| + } |
| + return account.ID, nil |
| +} |
| + |
| +type Product struct { |
| + ID string |
| + Active bool |
| + LiveMode bool |
| + TaxCode string |
| +} |
| + |
| +// UnmarshalJSON decodes a Product strictly enough that a null response |
| +// body, or one missing "id" or "livemode", cannot pass. Both fields decode |
| +// through pointers specifically so a caller can tell "absent" from "present |
| +// and zero": a naive struct would decode a null object into LiveMode=false, |
| +// which reads as test mode when the response in fact proved nothing at all. |
| +func (pr *Product) UnmarshalJSON(b []byte) error { |
| + var raw struct { |
| + ID *string `json:"id"` |
| + Active bool `json:"active"` |
| + LiveMode *bool `json:"livemode"` |
| + TaxCode string `json:"tax_code"` |
| + } |
| + if err := json.Unmarshal(b, &raw); err != nil { |
| + return err |
| + } |
| + if raw.ID == nil || *raw.ID == "" || raw.LiveMode == nil { |
| + return errors.New("billingstripe: product response missing id or livemode") |
| + } |
| + if !validID(*raw.ID) { |
| + return errors.New("billingstripe: product id has unexpected shape") |
| + } |
| + *pr = Product{} |
| + pr.ID = *raw.ID |
| + pr.Active = raw.Active |
| + pr.LiveMode = *raw.LiveMode |
| + pr.TaxCode = raw.TaxCode |
| + return nil |
| +} |
| + |
| +func (c *Client) GetProduct(ctx context.Context, id string) (*Product, error) { |
| + if !validID(id) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + var product Product |
| + if err := c.do(ctx, http.MethodGet, "/v1/products/"+id, nil, "", &product); err != nil { |
| + return nil, err |
| + } |
| + if product.ID != id { |
| + return nil, &Error{Code: CodeDecodeError} |
| + } |
| + return &product, nil |
| +} |
diff --git a/internal/billingstripe/merchant_test.go b/internal/billingstripe/merchant_test.go| new file mode 100644 |
| index 000000000..25f698ac8 |
| --- /dev/null |
| +++ b/internal/billingstripe/merchant_test.go |
| @@ -0,0 +1,97 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| +) |
| + |
| +func TestMerchantAccountBelongsToCredential(t *testing.T) { |
| + for _, body := range []string{`{"id":"acct_expected"}`, `null`, `{}`, `{"id":"cus_wrong"}`} { |
| + t.Run(body, func(t *testing.T) { |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method != http.MethodGet || r.URL.Path != "/v1/account" || r.Header.Get("Stripe-Account") != "" { |
| + t.Error("merchant lookup selected a connected account") |
| + } |
| + w.Write([]byte(body)) |
| + })) |
| + defer ts.Close() |
| + id, err := testClient(t, ts.URL).MerchantAccount(context.Background()) |
| + if body == `{"id":"acct_expected"}` { |
| + if err != nil || id != "acct_expected" { |
| + t.Fatalf("%s %v", id, err) |
| + } |
| + } else if err == nil { |
| + t.Fatal("invalid merchant accepted") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestProductAndCurrencyOptionsReachLaunchValidation(t *testing.T) { |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch r.URL.Path { |
| + case "/v1/prices/price_one": |
| + if r.URL.Query().Get("expand[]") != "currency_options" { |
| + t.Error("currency options must be expanded before rejecting adaptive-pricing conflicts") |
| + } |
| + w.Write([]byte(`{"id":"price_one","product":"prod_one","livemode":true,"currency_options":{"usd":{"unit_amount":2700}}}`)) |
| + case "/v1/products/prod_one": |
| + w.Write([]byte(`{"id":"prod_one","active":true,"livemode":true,"tax_code":"txcd_verified"}`)) |
| + default: |
| + t.Error("unexpected path") |
| + w.WriteHeader(404) |
| + } |
| + })) |
| + defer ts.Close() |
| + c := testClient(t, ts.URL) |
| + p, err := c.GetPrice(context.Background(), "price_one") |
| + if err != nil || p.ProductID != "prod_one" || len(p.CurrencyOptions) != 1 { |
| + t.Fatalf("price lost catalogue checks: %+v %v", p, err) |
| + } |
| + prod, err := c.GetProduct(context.Background(), p.ProductID) |
| + if err != nil || prod.TaxCode != "txcd_verified" || !prod.LiveMode || !prod.Active { |
| + t.Fatalf("product lost tax checks: %+v %v", prod, err) |
| + } |
| +} |
| + |
| +// --- Strict decode: Product rejects null / missing / invalid id / missing livemode --- |
| + |
| +func TestProductUnmarshalJSON_Strictness(t *testing.T) { |
| + if err := json.Unmarshal([]byte(`{"id":"prod_1","livemode":false}`), &Product{}); err != nil { |
| + t.Fatalf("valid product with explicit livemode:false: %v", err) |
| + } |
| + cases := map[string]string{ |
| + "null body": `null`, |
| + "missing id": `{"livemode":false}`, |
| + "empty id": `{"id":"","livemode":false}`, |
| + "invalid id shape": `{"id":"prod 1","livemode":false}`, |
| + "path traversal id": `{"id":"../../v1/customers","livemode":false}`, |
| + "missing livemode": `{"id":"prod_1"}`, |
| + "null livemode": `{"id":"prod_1","livemode":null}`, |
| + } |
| + for name, body := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + var p Product |
| + if err := json.Unmarshal([]byte(body), &p); err == nil { |
| + t.Fatalf("%s: expected error, got product %+v", name, p) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestProductUnmarshalJSON_ResetsStaleFieldsWhenAbsent(t *testing.T) { |
| + p := Product{TaxCode: "txcd_old", Active: true} |
| + minimal := `{"id":"prod_1","livemode":true}` |
| + if err := json.Unmarshal([]byte(minimal), &p); err != nil { |
| + t.Fatalf("decode: %v", err) |
| + } |
| + if p.TaxCode != "" { |
| + t.Errorf("TaxCode = %q, want cleared (absent in this response)", p.TaxCode) |
| + } |
| + if p.Active { |
| + t.Error("Active = true, want cleared (absent in this response)") |
| + } |
| +} |
diff --git a/internal/billingstripe/portal.go b/internal/billingstripe/portal.go| new file mode 100644 |
| index 000000000..fe0f0fb3b |
| --- /dev/null |
| +++ b/internal/billingstripe/portal.go |
| @@ -0,0 +1,127 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| +) |
| + |
| +// PortalToggleFeature is the shape shared by every Customer Portal feature |
| +// that is nothing but an on/off switch. |
| +type PortalToggleFeature struct { |
| + Enabled bool |
| +} |
| + |
| +// PortalCustomerUpdateFeature also carries which fields a customer may edit. |
| +// AllowedUpdates is the raw enum Stripe returns (e.g. "email", "address", |
| +// "shipping", "phone", "tax_id") — this package does not interpret the |
| +// list, only surfaces it, so a caller can refuse a configuration that |
| +// permits editing address or shipping (both feed the tax location this |
| +// package's Customer flow already validated). |
| +type PortalCustomerUpdateFeature struct { |
| + Enabled bool |
| + AllowedUpdates []string |
| +} |
| + |
| +// PortalSubscriptionCancelFeature also carries the cancellation mode: |
| +// "immediately" or "at_period_end". |
| +type PortalSubscriptionCancelFeature struct { |
| + Enabled bool |
| + Mode string |
| +} |
| + |
| +// PortalFeatures is the subset of a Configuration's features block the |
| +// pricing spec's entitlement model cares about. Deliberately absent: |
| +// business_profile, login_page, metadata, subscription_update's |
| +// default_allowed_updates, subscription_cancel's cancellation_reason and |
| +// proration_behavior — none of them change what a customer can do to their |
| +// entitlement, only how the portal looks or explains itself. |
| +type PortalFeatures struct { |
| + CustomerUpdate PortalCustomerUpdateFeature |
| + SubscriptionUpdate PortalToggleFeature |
| + SubscriptionCancel PortalSubscriptionCancelFeature |
| + PaymentMethodUpdate PortalToggleFeature |
| + InvoiceHistory PortalToggleFeature |
| +} |
| + |
| +// PortalConfiguration is a Customer Portal Configuration |
| +// (https://docs.stripe.com/api/customer_portal/configurations/object), |
| +// trimmed to what a caller needs to decide whether a configuration is safe |
| +// to point CreatePortal at. |
| +type PortalConfiguration struct { |
| + ID string |
| + LiveMode bool |
| + Active bool |
| + Features PortalFeatures |
| +} |
| + |
| +// UnmarshalJSON decodes a PortalConfiguration strictly enough that a null |
| +// response body, or one missing "id" or "livemode", cannot pass silently as |
| +// a zero-value (inactive, test-mode) configuration. Both fields decode |
| +// through pointers for exactly that reason: a naive struct would decode a |
| +// null object into LiveMode=false, which reads as "confirmed test mode" |
| +// when the response in fact proved nothing. |
| +func (pc *PortalConfiguration) UnmarshalJSON(b []byte) error { |
| + var raw struct { |
| + ID *string `json:"id"` |
| + LiveMode *bool `json:"livemode"` |
| + Active bool `json:"active"` |
| + Features struct { |
| + CustomerUpdate struct { |
| + Enabled bool `json:"enabled"` |
| + AllowedUpdates []string `json:"allowed_updates"` |
| + } `json:"customer_update"` |
| + SubscriptionUpdate struct { |
| + Enabled bool `json:"enabled"` |
| + } `json:"subscription_update"` |
| + SubscriptionCancel struct { |
| + Enabled bool `json:"enabled"` |
| + Mode string `json:"mode"` |
| + } `json:"subscription_cancel"` |
| + PaymentMethodUpdate struct { |
| + Enabled bool `json:"enabled"` |
| + } `json:"payment_method_update"` |
| + InvoiceHistory struct { |
| + Enabled bool `json:"enabled"` |
| + } `json:"invoice_history"` |
| + } `json:"features"` |
| + } |
| + if err := json.Unmarshal(b, &raw); err != nil { |
| + return err |
| + } |
| + if raw.ID == nil || *raw.ID == "" || raw.LiveMode == nil { |
| + return errors.New("billingstripe: portal configuration response missing id or livemode") |
| + } |
| + if !validID(*raw.ID) { |
| + return errors.New("billingstripe: portal configuration id has unexpected shape") |
| + } |
| + pc.ID = *raw.ID |
| + pc.LiveMode = *raw.LiveMode |
| + pc.Active = raw.Active |
| + pc.Features.CustomerUpdate.Enabled = raw.Features.CustomerUpdate.Enabled |
| + pc.Features.CustomerUpdate.AllowedUpdates = raw.Features.CustomerUpdate.AllowedUpdates |
| + pc.Features.SubscriptionUpdate.Enabled = raw.Features.SubscriptionUpdate.Enabled |
| + pc.Features.SubscriptionCancel.Enabled = raw.Features.SubscriptionCancel.Enabled |
| + pc.Features.SubscriptionCancel.Mode = raw.Features.SubscriptionCancel.Mode |
| + pc.Features.PaymentMethodUpdate.Enabled = raw.Features.PaymentMethodUpdate.Enabled |
| + pc.Features.InvoiceHistory.Enabled = raw.Features.InvoiceHistory.Enabled |
| + return nil |
| +} |
| + |
| +// GetPortalConfiguration reads back a Customer Portal Configuration so a |
| +// caller can verify its shape (active, correct mode, cancellation and |
| +// update policy) before ever pointing CreatePortal at it. Thin on purpose: |
| +// this package makes no policy judgment about what a configuration should |
| +// allow — that belongs to the console, which owns the entitlement rules a |
| +// configuration must not be allowed to violate. |
| +func (c *Client) GetPortalConfiguration(ctx context.Context, id string) (*PortalConfiguration, error) { |
| + if !validID(id) { |
| + return nil, &Error{Code: CodeInvalidID} |
| + } |
| + var pc PortalConfiguration |
| + if err := c.do(ctx, http.MethodGet, "/v1/billing_portal/configurations/"+id, nil, "", &pc); err != nil { |
| + return nil, err |
| + } |
| + return &pc, nil |
| +} |
diff --git a/internal/billingstripe/portal_test.go b/internal/billingstripe/portal_test.go| new file mode 100644 |
| index 000000000..7f0bc0452 |
| --- /dev/null |
| +++ b/internal/billingstripe/portal_test.go |
| @@ -0,0 +1,309 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// fullPortalConfigJSON mirrors the shape Stripe's API actually returns |
| +// (https://docs.stripe.com/api/customer_portal/configurations/object), |
| +// trimmed to the fields PortalConfiguration decodes. |
| +func fullPortalConfigJSON(overrides map[string]any) map[string]any { |
| + body := map[string]any{ |
| + "id": "bpc_1", |
| + "object": "billing_portal.configuration", |
| + "active": true, |
| + "livemode": true, |
| + "features": map[string]any{ |
| + "customer_update": map[string]any{ |
| + "enabled": true, |
| + "allowed_updates": []string{"email", "tax_id"}, |
| + }, |
| + "subscription_update": map[string]any{ |
| + "enabled": false, |
| + }, |
| + "subscription_cancel": map[string]any{ |
| + "enabled": true, |
| + "mode": "at_period_end", |
| + }, |
| + "payment_method_update": map[string]any{ |
| + "enabled": true, |
| + }, |
| + "invoice_history": map[string]any{ |
| + "enabled": true, |
| + }, |
| + }, |
| + } |
| + for k, v := range overrides { |
| + body[k] = v |
| + } |
| + return body |
| +} |
| + |
| +func TestGetPortalConfiguration_ExactPathAndFields(t *testing.T) { |
| + var gotMethod, gotPath string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotMethod = r.Method |
| + gotPath = r.URL.Path |
| + _ = json.NewEncoder(w).Encode(fullPortalConfigJSON(nil)) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + pc, err := c.GetPortalConfiguration(context.Background(), "bpc_1") |
| + if err != nil { |
| + t.Fatalf("GetPortalConfiguration: %v", err) |
| + } |
| + if gotMethod != http.MethodGet { |
| + t.Errorf("method = %q, want GET", gotMethod) |
| + } |
| + if gotPath != "/v1/billing_portal/configurations/bpc_1" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + |
| + if pc.ID != "bpc_1" || !pc.LiveMode || !pc.Active { |
| + t.Fatalf("unexpected configuration: %+v", pc) |
| + } |
| + if !pc.Features.CustomerUpdate.Enabled { |
| + t.Error("Features.CustomerUpdate.Enabled = false") |
| + } |
| + if got := pc.Features.CustomerUpdate.AllowedUpdates; len(got) != 2 || got[0] != "email" || got[1] != "tax_id" { |
| + t.Errorf("Features.CustomerUpdate.AllowedUpdates = %v", got) |
| + } |
| + if pc.Features.SubscriptionUpdate.Enabled { |
| + t.Error("Features.SubscriptionUpdate.Enabled = true, want false") |
| + } |
| + if !pc.Features.SubscriptionCancel.Enabled || pc.Features.SubscriptionCancel.Mode != "at_period_end" { |
| + t.Errorf("Features.SubscriptionCancel = %+v", pc.Features.SubscriptionCancel) |
| + } |
| + if !pc.Features.PaymentMethodUpdate.Enabled { |
| + t.Error("Features.PaymentMethodUpdate.Enabled = false") |
| + } |
| + if !pc.Features.InvoiceHistory.Enabled { |
| + t.Error("Features.InvoiceHistory.Enabled = false") |
| + } |
| +} |
| + |
| +func TestGetPortalConfiguration_RejectsInvalidID(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + for _, id := range []string{"../../../etc/passwd", "bpc_1/../../v1/customers", "bpc 1", ""} { |
| + _, err := c.GetPortalConfiguration(context.Background(), id) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidID { |
| + t.Errorf("id %q: err = %v, want CodeInvalidID", id, err) |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestGetPortalConfiguration_MissingIDInvalid(t *testing.T) { |
| + body := fullPortalConfigJSON(nil) |
| + delete(body, "id") |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(body) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetPortalConfiguration(context.Background(), "bpc_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +func TestGetPortalConfiguration_NullIDInvalid(t *testing.T) { |
| + body := fullPortalConfigJSON(map[string]any{"id": nil}) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(body) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetPortalConfiguration(context.Background(), "bpc_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +func TestGetPortalConfiguration_MissingLiveModeInvalid(t *testing.T) { |
| + body := fullPortalConfigJSON(nil) |
| + delete(body, "livemode") |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(body) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetPortalConfiguration(context.Background(), "bpc_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +func TestGetPortalConfiguration_NullLiveModeInvalid(t *testing.T) { |
| + body := fullPortalConfigJSON(map[string]any{"livemode": nil}) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _ = json.NewEncoder(w).Encode(body) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetPortalConfiguration(context.Background(), "bpc_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +func TestGetPortalConfiguration_NullBodyInvalid(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _, _ = w.Write([]byte("null")) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetPortalConfiguration(context.Background(), "bpc_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeDecodeError { |
| + t.Fatalf("err = %v, want CodeDecodeError", err) |
| + } |
| +} |
| + |
| +func TestGetPortalConfiguration_SanitizedErrorOnAPIError(t *testing.T) { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusNotFound) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "error": map[string]any{ |
| + "type": "invalid_request_error", |
| + "code": "resource_missing", |
| + "message": "No such configuration: 'bpc_1' for account acct_secret_123", |
| + }, |
| + }) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetPortalConfiguration(context.Background(), "bpc_1") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeAPIError { |
| + t.Fatalf("err = %v, want CodeAPIError", err) |
| + } |
| + if e.HTTPStatus != http.StatusNotFound || e.StripeType != "invalid_request_error" || e.StripeCode != "resource_missing" { |
| + t.Fatalf("unexpected fields: %+v", e) |
| + } |
| + if strings.Contains(e.Error(), "acct_secret_123") { |
| + t.Fatalf("Error() leaked response-body content: %s", e.Error()) |
| + } |
| +} |
| + |
| +// --- CreatePortal: configuration is required and sent on the wire --- |
| + |
| +func TestCreatePortal_SendsConfigurationForm(t *testing.T) { |
| + var gotMethod, gotPath string |
| + var gotForm map[string][]string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotMethod = r.Method |
| + gotPath = r.URL.Path |
| + _ = r.ParseForm() |
| + gotForm = map[string][]string(r.PostForm) |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "bps_1", "url": "https://billing.stripe.com/session/bps_1"}) |
| + })) |
| + defer srv.Close() |
| + |
| + c := testClient(t, srv.URL) |
| + ps, err := c.CreatePortal(context.Background(), "cus_1", "https://example.com/back", "bpc_1", "idem") |
| + if err != nil { |
| + t.Fatalf("CreatePortal: %v", err) |
| + } |
| + if ps.ID != "bps_1" { |
| + t.Fatalf("unexpected session: %+v", ps) |
| + } |
| + if gotMethod != http.MethodPost { |
| + t.Errorf("method = %q, want POST", gotMethod) |
| + } |
| + if gotPath != "/v1/billing_portal/sessions" { |
| + t.Errorf("path = %q", gotPath) |
| + } |
| + want := map[string]string{ |
| + "customer": "cus_1", |
| + "return_url": "https://example.com/back", |
| + "configuration": "bpc_1", |
| + } |
| + for k, v := range want { |
| + got := gotForm[k] |
| + if len(got) != 1 || got[0] != v { |
| + t.Errorf("form[%q] = %v, want [%q]", k, got, v) |
| + } |
| + } |
| +} |
| + |
| +func TestCreatePortal_RequiresValidConfigurationID(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + for _, id := range []string{"", "../../../etc/passwd", "bpc_1/../../v1/customers", "bpc 1"} { |
| + _, err := c.CreatePortal(context.Background(), "cus_1", "https://example.com/back", id, "idem") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidID { |
| + t.Errorf("configurationID %q: err = %v, want CodeInvalidID", id, err) |
| + } |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestCreatePortal_RequiresIdempotencyKey(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + _ = json.NewEncoder(w).Encode(map[string]any{"id": "bps_1", "url": "https://billing.stripe.com/session/bps_1"}) |
| + })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.CreatePortal(context.Background(), "cus_1", "https://example.com/back", "bpc_1", "") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeMissingIdempotencyKey { |
| + t.Fatalf("err = %v, want CodeMissingIdempotencyKey", err) |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestCreatePortal_RejectsInvalidCustomerID(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.CreatePortal(context.Background(), "../etc/passwd", "https://example.com/back", "bpc_1", "idem") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidID { |
| + t.Fatalf("err = %v, want CodeInvalidID", err) |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
| + |
| +func TestCreatePortal_RejectsMissingReturnURL(t *testing.T) { |
| + calls := 0 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ })) |
| + defer srv.Close() |
| + c := testClient(t, srv.URL) |
| + _, err := c.CreatePortal(context.Background(), "cus_1", "", "bpc_1", "idem") |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeInvalidParams { |
| + t.Fatalf("err = %v, want CodeInvalidParams", err) |
| + } |
| + if calls != 0 { |
| + t.Fatalf("expected no HTTP request, got %d", calls) |
| + } |
| +} |
diff --git a/internal/billingstripe/webhook.go b/internal/billingstripe/webhook.go| new file mode 100644 |
| index 000000000..c8cfbf7f6 |
| --- /dev/null |
| +++ b/internal/billingstripe/webhook.go |
| @@ -0,0 +1,162 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +const ( |
| + maxWebhookPayloadBytes = 1 << 20 // 1 MiB |
| + webhookTolerance = 5 * time.Minute |
| +) |
| + |
| +const ( |
| + CodeWebhookPayloadTooLarge = "webhook_payload_too_large" |
| + CodeWebhookNoSecrets = "webhook_no_secrets" |
| + CodeWebhookMalformedHeader = "webhook_malformed_signature_header" |
| + CodeWebhookSignatureMismatch = "webhook_signature_mismatch" |
| + CodeWebhookOutOfTolerance = "webhook_timestamp_out_of_tolerance" |
| + CodeWebhookInvalidEvent = "webhook_invalid_event" |
| +) |
| + |
| +// Event is the minimal envelope this package trusts. Object is left |
| +// undecoded: this package does not interpret event payloads, persist them, |
| +// or grant entitlement — it only proves the delivery is authentic. Stripe |
| +// does not guarantee delivery order, so a caller must never treat Created |
| +// as a sequence number; reconcile state by calling GetSubscription for the |
| +// event's subscription, not by trusting whichever event arrived last. |
| +type Event struct { |
| + ID string |
| + Type string |
| + Created time.Time |
| + LiveMode bool |
| + Object json.RawMessage |
| +} |
| + |
| +// VerifyEvent authenticates a Stripe webhook delivery against the |
| +// Stripe-Signature header and decodes its envelope. It tries every secret |
| +// in secrets against every v1 signature present in the header, so a secret |
| +// rotation window (old and new secret both valid) and a header carrying |
| +// more than one v1 both work without the caller branching on which secret |
| +// is "current". now is passed in, not read from time.Now, so tolerance |
| +// checks are deterministic in tests. |
| +// |
| +// This function has no side effects: it does not write raw anywhere, does |
| +// not cache, does not dedupe a replay. A caller that must not process the |
| +// same event twice needs its own idempotency store keyed on Event.ID; that |
| +// is a policy decision this package does not make for it. |
| +func VerifyEvent(raw []byte, signature string, secrets []string, now time.Time) (Event, error) { |
| + if len(raw) > maxWebhookPayloadBytes { |
| + return Event{}, &Error{Code: CodeWebhookPayloadTooLarge} |
| + } |
| + hasSecret := false |
| + for _, s := range secrets { |
| + if s != "" { |
| + hasSecret = true |
| + break |
| + } |
| + } |
| + if !hasSecret { |
| + return Event{}, &Error{Code: CodeWebhookNoSecrets} |
| + } |
| + |
| + ts, v1s, err := parseSignatureHeader(signature) |
| + if err != nil { |
| + return Event{}, err |
| + } |
| + |
| + if !signatureMatches(ts, raw, v1s, secrets) { |
| + return Event{}, &Error{Code: CodeWebhookSignatureMismatch} |
| + } |
| + |
| + tsUnix, err := strconv.ParseInt(ts, 10, 64) |
| + if err != nil { |
| + return Event{}, &Error{Code: CodeWebhookMalformedHeader} |
| + } |
| + eventTime := time.Unix(tsUnix, 0) |
| + if eventTime.Before(now.Add(-webhookTolerance)) || eventTime.After(now.Add(webhookTolerance)) { |
| + return Event{}, &Error{Code: CodeWebhookOutOfTolerance} |
| + } |
| + |
| + var env struct { |
| + ID string `json:"id"` |
| + Type string `json:"type"` |
| + Created int64 `json:"created"` |
| + LiveMode *bool `json:"livemode"` |
| + Data struct { |
| + Object json.RawMessage `json:"object"` |
| + } `json:"data"` |
| + } |
| + if err := json.Unmarshal(raw, &env); err != nil { |
| + return Event{}, &Error{Code: CodeWebhookInvalidEvent} |
| + } |
| + if !validID(env.ID) || env.Type == "" || env.Created <= 0 || env.LiveMode == nil || len(env.Data.Object) < 2 || env.Data.Object[0] != '{' { |
| + return Event{}, &Error{Code: CodeWebhookInvalidEvent} |
| + } |
| + |
| + return Event{ |
| + ID: env.ID, |
| + Type: env.Type, |
| + Created: time.Unix(env.Created, 0).UTC(), |
| + LiveMode: *env.LiveMode, |
| + Object: env.Data.Object, |
| + }, nil |
| +} |
| + |
| +// signatureMatches tries every (secret, v1) pair with a constant-time |
| +// comparison per pair. Which pair matched is not reported back — only |
| +// whether one did — so a caller (or a timing attacker probing this |
| +// function) learns nothing about which of several rotating secrets is live. |
| +func signatureMatches(ts string, raw []byte, v1s, secrets []string) bool { |
| + signedPayload := ts + "." + string(raw) |
| + matched := false |
| + for _, secret := range secrets { |
| + if secret == "" { |
| + continue |
| + } |
| + mac := hmac.New(sha256.New, []byte(secret)) |
| + mac.Write([]byte(signedPayload)) |
| + expected := mac.Sum(nil) |
| + for _, v1 := range v1s { |
| + got, err := hex.DecodeString(v1) |
| + if err != nil { |
| + continue |
| + } |
| + if hmac.Equal(expected, got) { |
| + matched = true |
| + } |
| + } |
| + } |
| + return matched |
| +} |
| + |
| +// parseSignatureHeader reads Stripe's "t=<unix>,v1=<hex>[,v1=<hex>...]" |
| +// form. Extra or unknown key=value pairs (e.g. a deprecated "v0") are |
| +// ignored rather than rejected, since Stripe controls that format and may |
| +// add fields; a missing timestamp or v1 signature is refused. |
| +func parseSignatureHeader(signature string) (ts string, v1s []string, err error) { |
| + for _, part := range strings.Split(signature, ",") { |
| + kv := strings.SplitN(strings.TrimSpace(part), "=", 2) |
| + if len(kv) != 2 { |
| + continue |
| + } |
| + switch kv[0] { |
| + case "t": |
| + if ts != "" { |
| + return "", nil, &Error{Code: CodeWebhookMalformedHeader} |
| + } |
| + ts = kv[1] |
| + case "v1": |
| + v1s = append(v1s, kv[1]) |
| + } |
| + } |
| + if ts == "" || len(v1s) == 0 { |
| + return "", nil, &Error{Code: CodeWebhookMalformedHeader} |
| + } |
| + return ts, v1s, nil |
| +} |
diff --git a/internal/billingstripe/webhook_test.go b/internal/billingstripe/webhook_test.go| new file mode 100644 |
| index 000000000..859f1ea86 |
| --- /dev/null |
| +++ b/internal/billingstripe/webhook_test.go |
| @@ -0,0 +1,264 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "fmt" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func sign(secret string, ts int64, payload []byte) string { |
| + signedPayload := fmt.Sprintf("%d.%s", ts, payload) |
| + mac := hmac.New(sha256.New, []byte(secret)) |
| + mac.Write([]byte(signedPayload)) |
| + return hex.EncodeToString(mac.Sum(nil)) |
| +} |
| + |
| +func header(ts int64, v1s ...string) string { |
| + h := fmt.Sprintf("t=%d", ts) |
| + for _, v1 := range v1s { |
| + h += ",v1=" + v1 |
| + } |
| + return h |
| +} |
| + |
| +func testEventPayload(id, typ string, created int64, live bool) []byte { |
| + return []byte(fmt.Sprintf( |
| + `{"id":%q,"type":%q,"created":%d,"livemode":%v,"data":{"object":{"id":"sub_1","status":"active"}}}`, |
| + id, typ, created, live, |
| + )) |
| +} |
| + |
| +func TestVerifyEvent_Valid(t *testing.T) { |
| + secret := "whsec_test" |
| + now := time.Unix(1700000100, 0) |
| + payload := testEventPayload("evt_1", "checkout.session.completed", 1700000100, false) |
| + sig := header(now.Unix(), sign(secret, now.Unix(), payload)) |
| + |
| + ev, err := VerifyEvent(payload, sig, []string{secret}, now) |
| + if err != nil { |
| + t.Fatalf("VerifyEvent: %v", err) |
| + } |
| + if ev.ID != "evt_1" || ev.Type != "checkout.session.completed" || ev.LiveMode { |
| + t.Fatalf("unexpected event: %+v", ev) |
| + } |
| + if !ev.Created.Equal(time.Unix(1700000100, 0).UTC()) { |
| + t.Errorf("Created = %v", ev.Created) |
| + } |
| + if string(ev.Object) != `{"id":"sub_1","status":"active"}` { |
| + t.Errorf("Object = %s", ev.Object) |
| + } |
| +} |
| + |
| +func TestVerifyEvent_LiveModeParsing(t *testing.T) { |
| + secret := "whsec_test" |
| + now := time.Unix(1700000100, 0) |
| + for _, live := range []bool{true, false} { |
| + payload := testEventPayload("evt_1", "customer.subscription.updated", 1700000100, live) |
| + sig := header(now.Unix(), sign(secret, now.Unix(), payload)) |
| + ev, err := VerifyEvent(payload, sig, []string{secret}, now) |
| + if err != nil { |
| + t.Fatalf("live=%v: VerifyEvent: %v", live, err) |
| + } |
| + if ev.LiveMode != live { |
| + t.Errorf("live=%v: LiveMode = %v", live, ev.LiveMode) |
| + } |
| + } |
| +} |
| + |
| +func TestVerifyEvent_SignatureAltered(t *testing.T) { |
| + secret := "whsec_test" |
| + now := time.Unix(1700000100, 0) |
| + payload := testEventPayload("evt_1", "invoice.paid", 1700000100, false) |
| + sig := header(now.Unix(), sign(secret, now.Unix(), payload)) |
| + |
| + tampered := append([]byte{}, payload...) |
| + tampered[10] ^= 0xFF // flip a byte in the raw payload after it was signed |
| + |
| + _, err := VerifyEvent(tampered, sig, []string{secret}, now) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookSignatureMismatch { |
| + t.Fatalf("err = %v, want CodeWebhookSignatureMismatch", err) |
| + } |
| +} |
| + |
| +func TestVerifyEvent_CorruptedHexSignature(t *testing.T) { |
| + secret := "whsec_test" |
| + now := time.Unix(1700000100, 0) |
| + payload := testEventPayload("evt_1", "invoice.paid", 1700000100, false) |
| + sig := header(now.Unix(), "not-hex-zz") |
| + |
| + _, err := VerifyEvent(payload, sig, []string{secret}, now) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookSignatureMismatch { |
| + t.Fatalf("err = %v, want CodeWebhookSignatureMismatch", err) |
| + } |
| +} |
| + |
| +func TestVerifyEvent_Replay(t *testing.T) { |
| + // This package verifies authenticity, not novelty: replaying the exact |
| + // same signed delivery must succeed both times. Deduplication by event |
| + // ID is a caller responsibility (documented on Event / VerifyEvent). |
| + secret := "whsec_test" |
| + now := time.Unix(1700000100, 0) |
| + payload := testEventPayload("evt_1", "invoice.paid", 1700000100, false) |
| + sig := header(now.Unix(), sign(secret, now.Unix(), payload)) |
| + |
| + for i := 0; i < 2; i++ { |
| + ev, err := VerifyEvent(payload, sig, []string{secret}, now) |
| + if err != nil { |
| + t.Fatalf("call %d: VerifyEvent: %v", i, err) |
| + } |
| + if ev.ID != "evt_1" { |
| + t.Fatalf("call %d: ID = %q", i, ev.ID) |
| + } |
| + } |
| +} |
| + |
| +func TestVerifyEvent_FutureTimestampOutsideTolerance(t *testing.T) { |
| + secret := "whsec_test" |
| + eventTs := int64(1700000100) |
| + now := time.Unix(eventTs-6*60, 0) // now is 6 minutes BEFORE the event's timestamp |
| + payload := testEventPayload("evt_1", "invoice.paid", eventTs, false) |
| + sig := header(eventTs, sign(secret, eventTs, payload)) |
| + |
| + _, err := VerifyEvent(payload, sig, []string{secret}, now) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookOutOfTolerance { |
| + t.Fatalf("err = %v, want CodeWebhookOutOfTolerance", err) |
| + } |
| +} |
| + |
| +func TestVerifyEvent_PastTimestampOutsideTolerance(t *testing.T) { |
| + secret := "whsec_test" |
| + eventTs := int64(1700000100) |
| + now := time.Unix(eventTs+6*60, 0) |
| + payload := testEventPayload("evt_1", "invoice.paid", eventTs, false) |
| + sig := header(eventTs, sign(secret, eventTs, payload)) |
| + |
| + _, err := VerifyEvent(payload, sig, []string{secret}, now) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookOutOfTolerance { |
| + t.Fatalf("err = %v, want CodeWebhookOutOfTolerance", err) |
| + } |
| +} |
| + |
| +func TestVerifyEvent_ToleranceBoundary(t *testing.T) { |
| + secret := "whsec_test" |
| + eventTs := int64(1700000100) |
| + payload := testEventPayload("evt_1", "invoice.paid", eventTs, false) |
| + sig := header(eventTs, sign(secret, eventTs, payload)) |
| + |
| + within := time.Unix(eventTs+5*60, 0) // exactly at the 5-minute edge |
| + if _, err := VerifyEvent(payload, sig, []string{secret}, within); err != nil { |
| + t.Fatalf("within tolerance: VerifyEvent: %v", err) |
| + } |
| + outside := time.Unix(eventTs+5*60+1, 0) // one second past it |
| + _, err := VerifyEvent(payload, sig, []string{secret}, outside) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookOutOfTolerance { |
| + t.Fatalf("err = %v, want CodeWebhookOutOfTolerance", err) |
| + } |
| +} |
| + |
| +func TestVerifyEvent_SecretRotation(t *testing.T) { |
| + oldSecret, newSecret := "whsec_old", "whsec_new" |
| + now := time.Unix(1700000100, 0) |
| + payload := testEventPayload("evt_1", "invoice.paid", 1700000100, false) |
| + // Signed with the NEW secret only, as Stripe would during a rotation |
| + // where the dashboard has already switched signing secrets. |
| + sig := header(now.Unix(), sign(newSecret, now.Unix(), payload)) |
| + |
| + if _, err := VerifyEvent(payload, sig, []string{oldSecret, newSecret}, now); err != nil { |
| + t.Fatalf("VerifyEvent with both secrets: %v", err) |
| + } |
| + if _, err := VerifyEvent(payload, sig, []string{oldSecret}, now); err == nil { |
| + t.Fatal("expected failure verifying against only the old secret") |
| + } |
| +} |
| + |
| +func TestVerifyEvent_MultipleV1InHeader(t *testing.T) { |
| + secretA, secretB := "whsec_a", "whsec_b" |
| + now := time.Unix(1700000100, 0) |
| + payload := testEventPayload("evt_1", "invoice.paid", 1700000100, false) |
| + sig := header(now.Unix(), sign(secretA, now.Unix(), payload), sign(secretB, now.Unix(), payload)) |
| + |
| + if _, err := VerifyEvent(payload, sig, []string{secretB}, now); err != nil { |
| + t.Fatalf("VerifyEvent against the second v1 in the header: %v", err) |
| + } |
| +} |
| + |
| +func TestVerifyEvent_MalformedSignatureHeader(t *testing.T) { |
| + secret := "whsec_test" |
| + now := time.Unix(1700000100, 0) |
| + payload := testEventPayload("evt_1", "invoice.paid", 1700000100, false) |
| + |
| + for _, sig := range []string{"", "garbage", "t=1700000100", "v1=abcdef"} { |
| + _, err := VerifyEvent(payload, sig, []string{secret}, now) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookMalformedHeader { |
| + t.Errorf("sig %q: err = %v, want CodeWebhookMalformedHeader", sig, err) |
| + } |
| + } |
| +} |
| + |
| +func TestVerifyEvent_NoSecretsProvided(t *testing.T) { |
| + now := time.Unix(1700000100, 0) |
| + payload := testEventPayload("evt_1", "invoice.paid", 1700000100, false) |
| + sig := header(now.Unix(), sign("whsec_test", now.Unix(), payload)) |
| + |
| + _, err := VerifyEvent(payload, sig, nil, now) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookNoSecrets { |
| + t.Fatalf("err = %v, want CodeWebhookNoSecrets", err) |
| + } |
| +} |
| + |
| +func TestVerifyEvent_PayloadTooLarge(t *testing.T) { |
| + secret := "whsec_test" |
| + now := time.Unix(1700000100, 0) |
| + huge := make([]byte, maxWebhookPayloadBytes+1) |
| + sig := header(now.Unix(), sign(secret, now.Unix(), huge)) |
| + |
| + _, err := VerifyEvent(huge, sig, []string{secret}, now) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookPayloadTooLarge { |
| + t.Fatalf("err = %v, want CodeWebhookPayloadTooLarge", err) |
| + } |
| +} |
| + |
| +func TestVerifyEvent_MissingRequiredFields(t *testing.T) { |
| + secret := "whsec_test" |
| + now := time.Unix(1700000100, 0) |
| + cases := []string{ |
| + `{"type":"invoice.paid","created":1700000100,"data":{"object":{"id":"x"}}}`, // no id |
| + `{"id":"evt_1","created":1700000100,"data":{"object":{"id":"x"}}}`, // no type |
| + `{"id":"evt_1","type":"invoice.paid","data":{"object":{"id":"x"}}}`, // no created |
| + `{"id":"evt_1","type":"invoice.paid","created":1700000100,"data":{}}`, // no data.object |
| + `{"id":"evt_1","type":"invoice.paid","created":1700000100,"data":{"object":null}}`, // null object |
| + } |
| + for _, payload := range cases { |
| + raw := []byte(payload) |
| + sig := header(now.Unix(), sign(secret, now.Unix(), raw)) |
| + _, err := VerifyEvent(raw, sig, []string{secret}, now) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookInvalidEvent { |
| + t.Errorf("payload %s: err = %v, want CodeWebhookInvalidEvent", payload, err) |
| + } |
| + } |
| +} |
| + |
| +func TestVerifyEvent_UnknownSchema(t *testing.T) { |
| + secret := "whsec_test" |
| + now := time.Unix(1700000100, 0) |
| + raw := []byte(`not json at all`) |
| + sig := header(now.Unix(), sign(secret, now.Unix(), raw)) |
| + |
| + _, err := VerifyEvent(raw, sig, []string{secret}, now) |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeWebhookInvalidEvent { |
| + t.Fatalf("err = %v, want CodeWebhookInvalidEvent", err) |
| + } |
| +} |