Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cyclops-cs): reconcile Stripe setup returns (#7432)
Francesco Bonaccic3dff03523bb
diff --git a/libs/fleet/backend/auth/authz_billing.rego b/libs/fleet/backend/auth/authz_billing.regoindex 6095532f20..a0525a5b87 100644--- a/libs/fleet/backend/auth/authz_billing.rego+++ b/libs/fleet/backend/auth/authz_billing.rego@@ -8,7 +8,7 @@# SPA only — not cua-cli, not user keys. These endpoints hand back Stripe-hosted# URLs meant to be opened in the browser session that asked for them.#-# The prefix match rather than three literals is deliberate: a new billing+# The prefix match rather than individual literals is deliberate: a new billing# browser route is covered the day it is registered. /api/billing/webhook is# excluded because it is not an authenticated route at all — Stripe signature# verification is its authentication boundary, and it is registered without thediff --git a/libs/fleet/backend/auth/policy_characterization_test.go b/libs/fleet/backend/auth/policy_characterization_test.goindex eaa43101ef..61214ebf55 100644--- a/libs/fleet/backend/auth/policy_characterization_test.go+++ b/libs/fleet/backend/auth/policy_characterization_test.go@@ -183,6 +183,7 @@ func characterizationCases() map[string][]routeCase {simple("/api/billing/summary", "/api/billing/summary")simple("/api/billing/usage", "/api/billing/usage")simple("/api/billing/setup-session", "/api/billing/setup-session")+ simple("/api/billing/setup-session/complete", "/api/billing/setup-session/complete")simple("/api/billing/portal-session", "/api/billing/portal-session")simple("/api/keys", "/api/keys")simple("/api/namespaces", "/api/namespaces")diff --git a/libs/fleet/backend/auth/policy_routes.go b/libs/fleet/backend/auth/policy_routes.goindex 61ce305b17..fc21137d4c 100644--- a/libs/fleet/backend/auth/policy_routes.go+++ b/libs/fleet/backend/auth/policy_routes.go@@ -74,7 +74,7 @@ func ChatRoutePolicy() Node {}// BillingRoutePolicy guards the Stripe-hosted billing browser routes. Its module-// matches a prefix rather than three literals, so a billing route added to+// matches a prefix rather than individual literals, so a billing route added to// main.go and bound here is covered without a policy change.func BillingRoutePolicy() Node {return All(BasePolicy(), surfaceLeaf("authz-billing", "data.authz_billing.allow"))@@ -298,10 +298,11 @@ var routeSurfaces = map[string]string{"/api/chat/conversations/{id}": "chat","/api/chat/conversations/{id}/turns": "chat",- "/api/billing/summary": "billing",- "/api/billing/usage": "billing",- "/api/billing/setup-session": "billing",- "/api/billing/portal-session": "billing",+ "/api/billing/summary": "billing",+ "/api/billing/usage": "billing",+ "/api/billing/setup-session": "billing",+ "/api/billing/setup-session/complete": "billing",+ "/api/billing/portal-session": "billing","/api/keys": "keys","/api/keys/{id}": "keys",diff --git a/libs/fleet/backend/auth/testdata/route-authorization-table.txt b/libs/fleet/backend/auth/testdata/route-authorization-table.txtindex e209e5117f..f0574e32e3 100644--- a/libs/fleet/backend/auth/testdata/route-authorization-table.txt+++ b/libs/fleet/backend/auth/testdata/route-authorization-table.txt@@ -383,6 +383,61 @@/api/billing/setup-session | plain | QUERY | spa = allow/api/billing/setup-session | plain | QUERY | user-key = deny/api/billing/setup-session | plain | QUERY | user-key-verified = deny+/api/billing/setup-session/complete | plain | DELETE | admin-spa = allow+/api/billing/setup-session/complete | plain | DELETE | cua-cli = deny+/api/billing/setup-session/complete | plain | DELETE | dcr-client = deny+/api/billing/setup-session/complete | plain | DELETE | empty-sub = deny+/api/billing/setup-session/complete | plain | DELETE | github-oidc = deny+/api/billing/setup-session/complete | plain | DELETE | oauth2-proxy = deny+/api/billing/setup-session/complete | plain | DELETE | per-key-other-ns = deny+/api/billing/setup-session/complete | plain | DELETE | per-key-owned-ns = deny+/api/billing/setup-session/complete | plain | DELETE | spa = allow+/api/billing/setup-session/complete | plain | DELETE | user-key = deny+/api/billing/setup-session/complete | plain | DELETE | user-key-verified = deny+/api/billing/setup-session/complete | plain | GET | admin-spa = allow+/api/billing/setup-session/complete | plain | GET | cua-cli = deny+/api/billing/setup-session/complete | plain | GET | dcr-client = deny+/api/billing/setup-session/complete | plain | GET | empty-sub = deny+/api/billing/setup-session/complete | plain | GET | github-oidc = deny+/api/billing/setup-session/complete | plain | GET | oauth2-proxy = deny+/api/billing/setup-session/complete | plain | GET | per-key-other-ns = deny+/api/billing/setup-session/complete | plain | GET | per-key-owned-ns = deny+/api/billing/setup-session/complete | plain | GET | spa = allow+/api/billing/setup-session/complete | plain | GET | user-key = deny+/api/billing/setup-session/complete | plain | GET | user-key-verified = deny+/api/billing/setup-session/complete | plain | PATCH | admin-spa = allow+/api/billing/setup-session/complete | plain | PATCH | cua-cli = deny+/api/billing/setup-session/complete | plain | PATCH | dcr-client = deny+/api/billing/setup-session/complete | plain | PATCH | empty-sub = deny+/api/billing/setup-session/complete | plain | PATCH | github-oidc = deny+/api/billing/setup-session/complete | plain | PATCH | oauth2-proxy = deny+/api/billing/setup-session/complete | plain | PATCH | per-key-other-ns = deny+/api/billing/setup-session/complete | plain | PATCH | per-key-owned-ns = deny+/api/billing/setup-session/complete | plain | PATCH | spa = allow+/api/billing/setup-session/complete | plain | PATCH | user-key = deny+/api/billing/setup-session/complete | plain | PATCH | user-key-verified = deny+/api/billing/setup-session/complete | plain | POST | admin-spa = allow+/api/billing/setup-session/complete | plain | POST | cua-cli = deny+/api/billing/setup-session/complete | plain | POST | dcr-client = deny+/api/billing/setup-session/complete | plain | POST | empty-sub = deny+/api/billing/setup-session/complete | plain | POST | github-oidc = deny+/api/billing/setup-session/complete | plain | POST | oauth2-proxy = deny+/api/billing/setup-session/complete | plain | POST | per-key-other-ns = deny+/api/billing/setup-session/complete | plain | POST | per-key-owned-ns = deny+/api/billing/setup-session/complete | plain | POST | spa = allow+/api/billing/setup-session/complete | plain | POST | user-key = deny+/api/billing/setup-session/complete | plain | POST | user-key-verified = deny+/api/billing/setup-session/complete | plain | QUERY | admin-spa = allow+/api/billing/setup-session/complete | plain | QUERY | cua-cli = deny+/api/billing/setup-session/complete | plain | QUERY | dcr-client = deny+/api/billing/setup-session/complete | plain | QUERY | empty-sub = deny+/api/billing/setup-session/complete | plain | QUERY | github-oidc = deny+/api/billing/setup-session/complete | plain | QUERY | oauth2-proxy = deny+/api/billing/setup-session/complete | plain | QUERY | per-key-other-ns = deny+/api/billing/setup-session/complete | plain | QUERY | per-key-owned-ns = deny+/api/billing/setup-session/complete | plain | QUERY | spa = allow+/api/billing/setup-session/complete | plain | QUERY | user-key = deny+/api/billing/setup-session/complete | plain | QUERY | user-key-verified = deny/api/billing/summary | plain | DELETE | admin-spa = allow/api/billing/summary | plain | DELETE | cua-cli = deny/api/billing/summary | plain | DELETE | dcr-client = denydiff --git a/libs/fleet/backend/billing/service.go b/libs/fleet/backend/billing/service.goindex 91444c448a..a0afa778af 100644--- a/libs/fleet/backend/billing/service.go+++ b/libs/fleet/backend/billing/service.go@@ -18,11 +18,16 @@ const (SetupPurpose = "fleet_default_card"MetadataSetupGeneration = "fleet_setup_generation"MetadataSetupSource = "fleet_source"+ MetadataIdentityClass = "fleet_identity_class")var (- ErrCustomerNotFound = errors.New("billing customer not found")- ErrPaymentMethodNotFound = errors.New("default payment method not found")+ ErrCustomerNotFound = errors.New("billing customer not found")+ ErrPaymentMethodNotFound = errors.New("default payment method not found")+ ErrSetupSessionNotFound = errors.New("billing setup session not found")+ ErrSetupSessionNotOwned = errors.New("billing setup session not owned by subject")+ ErrSetupSessionIncomplete = errors.New("billing setup session is not complete")+ ErrSetupSessionInvalid = errors.New("billing setup session is invalid"))type Customer struct {@@ -44,6 +49,24 @@ type SetupSessionRequest struct {SetupGeneration stringSubject stringSource string+ IdentityClass string+}++type SetupSession struct {+ ID string+ Mode string+ Status string+ CustomerID string+ SetupIntentID string+ SetupIntentStatus string+ SetupIntentCustomerID string+ PaymentMethodID string+ Metadata map[string]string+}++type SetupCompletion struct {+ Applied bool+ SetupIntentID string}type PortalSessionRequest struct {@@ -59,6 +82,7 @@ type Gateway interface {ListAttachedCards(ctx context.Context, customerID string) ([]SavedCard, error)SetDefaultPaymentMethodForSetupGeneration(ctx context.Context, customerID, paymentMethodID, generation string) (bool, error)CreateSetupSession(ctx context.Context, request SetupSessionRequest) (string, error)+ RetrieveSetupSession(ctx context.Context, sessionID string) (SetupSession, error)CreatePortalSession(ctx context.Context, request PortalSessionRequest) (string, error)PreviewInvoice(ctx context.Context, customerID string) (*Invoice, error)ListInvoices(ctx context.Context, customerID string, createdAfter time.Time) ([]Invoice, error)@@ -351,9 +375,10 @@ func (s *Service) Usage(ctx context.Context, subject string, months int, now tim}type SetupOptions struct {- SuccessURL string- CancelURL string- Source string+ SuccessURL string+ CancelURL string+ Source string+ IdentityClass string}func (s *Service) CreateSetupSession(ctx context.Context, subject string, options SetupOptions) (string, error) {@@ -372,6 +397,7 @@ func (s *Service) CreateSetupSession(ctx context.Context, subject string, optionSetupGeneration: generation,Subject: subject,Source: options.Source,+ IdentityClass: options.IdentityClass,})if err != nil {return "", err@@ -382,6 +408,52 @@ func (s *Service) CreateSetupSession(ctx context.Context, subject string, optionreturn url, nil}+func (s *Service) CompleteSetupSession(ctx context.Context, subject, source, identityClass, sessionID string) (SetupCompletion, error) {+ if subject == "" || source == "" || identityClass == "" || sessionID == "" {+ return SetupCompletion{}, ErrSetupSessionInvalid+ }+ customer, err := s.findCustomerReadOnly(ctx, subject)+ if errors.Is(err, ErrCustomerNotFound) {+ return SetupCompletion{}, ErrSetupSessionNotOwned+ }+ if err != nil {+ return SetupCompletion{}, err+ }+ session, err := s.gateway.RetrieveSetupSession(ctx, sessionID)+ if err != nil {+ return SetupCompletion{}, err+ }+ if session.CustomerID != customer.ID ||+ session.SetupIntentCustomerID != customer.ID ||+ session.Metadata[MetadataSubject] != subject {+ return SetupCompletion{}, ErrSetupSessionNotOwned+ }+ if session.ID != sessionID || session.Mode != "setup" ||+ session.Metadata["purpose"] != SetupPurpose ||+ session.Metadata[MetadataSetupSource] != source ||+ session.Metadata[MetadataIdentityClass] != identityClass ||+ session.SetupIntentID == "" ||+ session.Metadata[MetadataSetupGeneration] == "" {+ return SetupCompletion{}, ErrSetupSessionInvalid+ }+ if session.Status != "complete" || session.SetupIntentStatus != "succeeded" {+ return SetupCompletion{}, ErrSetupSessionIncomplete+ }+ if session.PaymentMethodID == "" {+ return SetupCompletion{}, ErrSetupSessionInvalid+ }+ applied, err := s.SetDefaultPaymentMethodForSetupGeneration(+ ctx,+ customer.ID,+ session.PaymentMethodID,+ session.Metadata[MetadataSetupGeneration],+ )+ if err != nil {+ return SetupCompletion{}, err+ }+ return SetupCompletion{Applied: applied, SetupIntentID: session.SetupIntentID}, nil+}+func (s *Service) CreatePortalSession(ctx context.Context, subject, returnURL string) (string, error) {customer, err := s.FindCustomer(ctx, subject)if err != nil {diff --git a/libs/fleet/backend/billing/service_test.go b/libs/fleet/backend/billing/service_test.goindex 3b23d0b495..07953607e8 100644--- a/libs/fleet/backend/billing/service_test.go+++ b/libs/fleet/backend/billing/service_test.go@@ -33,6 +33,9 @@ type fakeGateway struct {defaultGeneration stringdefaultApplied boolsetupRequest SetupSessionRequest+ setupSession SetupSession+ setupSessionID string+ setupSessionErr errorportalRequest PortalSessionRequestpreviewInvoice *InvoicepreviewErr error@@ -93,6 +96,11 @@ func (f *fakeGateway) CreateSetupSession(_ context.Context, request SetupSessionreturn "https://checkout.stripe.test/session", nil}+func (f *fakeGateway) RetrieveSetupSession(_ context.Context, sessionID string) (SetupSession, error) {+ f.setupSessionID = sessionID+ return f.setupSession, f.setupSessionErr+}+func (f *fakeGateway) CreatePortalSession(_ context.Context, request PortalSessionRequest) (string, error) {f.portalRequest = requestreturn "https://billing.stripe.test/session", nil@@ -349,9 +357,10 @@ func TestCreateSetupSessionUsesServerRequestAndOwnedCustomer(t *testing.T) {service := NewService(gateway)url, err := service.CreateSetupSession(context.Background(), "subject-123", SetupOptions{- SuccessURL: "https://run.example.test/billing?checkout=success",- CancelURL: "https://run.example.test/billing?checkout=cancelled",- Source: "spa",+ SuccessURL: "https://run.example.test/billing?checkout=success",+ CancelURL: "https://run.example.test/billing?checkout=cancelled",+ Source: "spa",+ IdentityClass: "external",})if err != nil {t.Fatalf("CreateSetupSession() error = %v", err)@@ -366,6 +375,7 @@ func TestCreateSetupSessionUsesServerRequestAndOwnedCustomer(t *testing.T) {SetupGeneration: gateway.updatedMetadata[MetadataSetupGeneration],Subject: "subject-123",Source: "spa",+ IdentityClass: "external",}if want.SetupGeneration == "" || !reflect.DeepEqual(gateway.setupRequest, want) {t.Fatalf("setup request = %#v, want %#v", gateway.setupRequest, want)@@ -405,6 +415,123 @@ func TestSetDefaultPaymentMethodForSetupGenerationDelegatesToGateway(t *testing.}}+func successfulSetupSession() SetupSession {+ return SetupSession{+ ID: "cs_test_owned",+ Mode: "setup",+ Status: "complete",+ CustomerID: "cus_owned",+ SetupIntentID: "seti_owned",+ SetupIntentStatus: "succeeded",+ SetupIntentCustomerID: "cus_owned",+ PaymentMethodID: "pm_card",+ Metadata: map[string]string{+ "purpose": SetupPurpose,+ MetadataSubject: "subject-123",+ MetadataSetupSource: "spa",+ MetadataIdentityClass: "external",+ MetadataSetupGeneration: "current",+ },+ }+}++func TestCompleteSetupSessionVerifiesOwnershipAndAppliesCurrentGeneration(t *testing.T) {+ gateway := &fakeGateway{+ customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}},+ setupSession: successfulSetupSession(),+ defaultApplied: true,+ }++ result, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "external", "cs_test_owned")+ if err != nil {+ t.Fatalf("CompleteSetupSession() error = %v", err)+ }+ if result != (SetupCompletion{Applied: true, SetupIntentID: "seti_owned"}) {+ t.Fatalf("result = %#v", result)+ }+ if gateway.setupSessionID != "cs_test_owned" || gateway.defaultCustomerID != "cus_owned" ||+ gateway.defaultPaymentMethodID != "pm_card" || gateway.defaultGeneration != "current" {+ t.Fatalf("retrieval/default update = %q/%q/%q/%q", gateway.setupSessionID, gateway.defaultCustomerID, gateway.defaultPaymentMethodID, gateway.defaultGeneration)+ }+}++func TestCompleteSetupSessionRejectsUnownedSessionWithoutUpdatingCustomer(t *testing.T) {+ session := successfulSetupSession()+ session.CustomerID = "cus_attacker"+ gateway := &fakeGateway{+ customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}},+ setupSession: session,+ }++ _, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "external", "cs_test_owned")+ if !errors.Is(err, ErrSetupSessionNotOwned) || gateway.defaultCustomerID != "" {+ t.Fatalf("error/default customer = %v/%q, want ownership rejection/no update", err, gateway.defaultCustomerID)+ }+}++func TestCompleteSetupSessionRejectsMismatchedTrustedMetadata(t *testing.T) {+ tests := []struct {+ name string+ mutate func(*SetupSession)+ want error+ }{+ {name: "subject", mutate: func(session *SetupSession) { session.Metadata[MetadataSubject] = "other" }, want: ErrSetupSessionNotOwned},+ {name: "source", mutate: func(session *SetupSession) { session.Metadata[MetadataSetupSource] = "user_key" }, want: ErrSetupSessionInvalid},+ {name: "identity class", mutate: func(session *SetupSession) { session.Metadata[MetadataIdentityClass] = "internal" }, want: ErrSetupSessionInvalid},+ {name: "purpose", mutate: func(session *SetupSession) { session.Metadata["purpose"] = "other" }, want: ErrSetupSessionInvalid},+ {name: "generation", mutate: func(session *SetupSession) { delete(session.Metadata, MetadataSetupGeneration) }, want: ErrSetupSessionInvalid},+ }+ for _, testCase := range tests {+ t.Run(testCase.name, func(t *testing.T) {+ session := successfulSetupSession()+ testCase.mutate(&session)+ gateway := &fakeGateway{+ customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}},+ setupSession: session,+ }+ _, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "external", "cs_test_owned")+ if !errors.Is(err, testCase.want) || gateway.defaultCustomerID != "" {+ t.Fatalf("error/default customer = %v/%q, want %v/no update", err, gateway.defaultCustomerID, testCase.want)+ }+ })+ }+}++func TestCompleteSetupSessionRequiresTerminalSuccess(t *testing.T) {+ tests := []struct {+ name string+ mutate func(*SetupSession)+ }{+ {name: "checkout open", mutate: func(session *SetupSession) { session.Status = "open" }},+ {name: "setup intent processing", mutate: func(session *SetupSession) { session.SetupIntentStatus = "processing" }},+ }+ for _, testCase := range tests {+ t.Run(testCase.name, func(t *testing.T) {+ session := successfulSetupSession()+ testCase.mutate(&session)+ gateway := &fakeGateway{+ customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}},+ setupSession: session,+ }+ _, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "external", "cs_test_owned")+ if !errors.Is(err, ErrSetupSessionIncomplete) || gateway.defaultCustomerID != "" {+ t.Fatalf("error/default customer = %v/%q, want incomplete/no update", err, gateway.defaultCustomerID)+ }+ })+ }+}++func TestCompleteSetupSessionDuplicateIsSuccessfulWithoutReapplying(t *testing.T) {+ gateway := &fakeGateway{+ customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}},+ setupSession: successfulSetupSession(),+ }+ result, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "external", "cs_test_owned")+ if err != nil || result.Applied || result.SetupIntentID != "seti_owned" {+ t.Fatalf("result/error = %#v/%v, want safe duplicate", result, err)+ }+}+func TestCreateSetupSessionStoresLatestOpaqueGeneration(t *testing.T) {gateway := &fakeGateway{createdCustomer: Customer{ID: "cus_owned"}}service := NewService(gateway)diff --git a/libs/fleet/backend/billing/stripe_gateway.go b/libs/fleet/backend/billing/stripe_gateway.goindex 79f189e4ae..7477556d62 100644--- a/libs/fleet/backend/billing/stripe_gateway.go+++ b/libs/fleet/backend/billing/stripe_gateway.go@@ -167,6 +167,7 @@ func setupSessionParams(request SetupSessionRequest) *stripe.CheckoutSessionCreasetupIntentData.AddMetadata(MetadataSetupGeneration, request.SetupGeneration)setupIntentData.AddMetadata(MetadataSubject, request.Subject)setupIntentData.AddMetadata(MetadataSetupSource, request.Source)+ setupIntentData.AddMetadata(MetadataIdentityClass, request.IdentityClass)return &stripe.CheckoutSessionCreateParams{Mode: stripe.String(string(stripe.CheckoutSessionModeSetup)),Customer: stripe.String(request.CustomerID),@@ -185,6 +186,41 @@ func (g *StripeGateway) CreateSetupSession(ctx context.Context, request SetupSesreturn session.URL, nil}+func setupSessionRetrieveParams() *stripe.CheckoutSessionRetrieveParams {+ params := &stripe.CheckoutSessionRetrieveParams{}+ params.AddExpand("setup_intent")+ return params+}++func (g *StripeGateway) RetrieveSetupSession(ctx context.Context, sessionID string) (SetupSession, error) {+ session, err := g.client.V1CheckoutSessions.Retrieve(ctx, sessionID, setupSessionRetrieveParams())+ if err != nil {+ var stripeErr *stripe.Error+ if errors.As(err, &stripeErr) && stripeErr.Code == stripe.ErrorCodeResourceMissing {+ return SetupSession{}, errors.Join(ErrSetupSessionNotFound, err)+ }+ return SetupSession{}, err+ }+ result := SetupSession{+ ID: session.ID, Mode: string(session.Mode), Status: string(session.Status),+ }+ if session.Customer != nil {+ result.CustomerID = session.Customer.ID+ }+ if session.SetupIntent != nil {+ result.SetupIntentID = session.SetupIntent.ID+ result.SetupIntentStatus = string(session.SetupIntent.Status)+ result.Metadata = session.SetupIntent.Metadata+ if session.SetupIntent.Customer != nil {+ result.SetupIntentCustomerID = session.SetupIntent.Customer.ID+ }+ if session.SetupIntent.PaymentMethod != nil {+ result.PaymentMethodID = session.SetupIntent.PaymentMethod.ID+ }+ }+ return result, nil+}+func (g *StripeGateway) CreatePortalSession(ctx context.Context, request PortalSessionRequest) (string, error) {session, err := g.client.V1BillingPortalSessions.Create(ctx, &stripe.BillingPortalSessionCreateParams{Customer: stripe.String(request.CustomerID),diff --git a/libs/fleet/backend/billing/stripe_gateway_test.go b/libs/fleet/backend/billing/stripe_gateway_test.goindex 6458dc8a0d..9eed6c6da5 100644--- a/libs/fleet/backend/billing/stripe_gateway_test.go+++ b/libs/fleet/backend/billing/stripe_gateway_test.go@@ -121,6 +121,7 @@ func TestSetupSessionParamsCopyLatestCustomerGenerationToSetupIntent(t *testing.SetupGeneration: "server-generated-token",Subject: "subject-1",Source: "spa",+ IdentityClass: "external",})if got := params.SetupIntentData.Metadata[MetadataSetupGeneration]; got != "server-generated-token" {@@ -132,6 +133,60 @@ func TestSetupSessionParamsCopyLatestCustomerGenerationToSetupIntent(t *testing.if got := params.SetupIntentData.Metadata[MetadataSetupSource]; got != "spa" {t.Fatalf("setup intent source = %q, want spa", got)}+ if got := params.SetupIntentData.Metadata[MetadataIdentityClass]; got != "external" {+ t.Fatalf("setup intent identity class = %q, want external", got)+ }+}++func TestRetrieveSetupSessionExpandsAndSanitizesSetupIntent(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/v1/checkout/sessions/cs_test_owned" {+ t.Fatalf("request = %s %s", r.Method, r.URL.Path)+ }+ if expanded := r.URL.Query()["expand[0]"]; !reflect.DeepEqual(expanded, []string{"setup_intent"}) {+ t.Fatalf("expand = %#v, want setup_intent", r.URL.Query())+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{+ "id":"cs_test_owned","object":"checkout.session","mode":"setup","status":"complete",+ "customer":"cus_owned",+ "setup_intent":{+ "id":"seti_owned","object":"setup_intent","status":"succeeded",+ "customer":"cus_owned","payment_method":"pm_card",+ "metadata":{"purpose":"fleet_default_card","fleet_subject":"subject-123","fleet_source":"spa","fleet_identity_class":"external","fleet_setup_generation":"current"}+ }+ }`)+ }))+ defer server.Close()++ backend := stripe.GetBackendWithConfig(stripe.APIBackend, &stripe.BackendConfig{URL: stripe.String(server.URL)})+ client := stripe.NewClient("sk_test", stripe.WithBackends(&stripe.Backends{API: backend, Connect: backend, Uploads: backend, MeterEvents: backend}))+ gateway := &StripeGateway{client: client}++ got, err := gateway.RetrieveSetupSession(context.Background(), "cs_test_owned")+ if err != nil {+ t.Fatalf("RetrieveSetupSession() error = %v", err)+ }+ want := successfulSetupSession()+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("session = %#v, want %#v", got, want)+ }+}++func TestRetrieveSetupSessionMapsMissingStripeResource(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusNotFound)+ _, _ = io.WriteString(w, `{"error":{"code":"resource_missing","message":"No such checkout session","type":"invalid_request_error"}}`)+ }))+ defer server.Close()++ backend := stripe.GetBackendWithConfig(stripe.APIBackend, &stripe.BackendConfig{URL: stripe.String(server.URL)})+ client := stripe.NewClient("sk_test", stripe.WithBackends(&stripe.Backends{API: backend, Connect: backend, Uploads: backend, MeterEvents: backend}))+ _, err := (&StripeGateway{client: client}).RetrieveSetupSession(context.Background(), "cs_test_missing")+ if !errors.Is(err, ErrSetupSessionNotFound) {+ t.Fatalf("error = %v, want %v", err, ErrSetupSessionNotFound)+ }}func TestCurrentSetupGenerationRejectsStaleAndMalformedValues(t *testing.T) {diff --git a/libs/fleet/backend/billing/webhook.go b/libs/fleet/backend/billing/webhook.goindex 7db140e2e0..eb00495f1d 100644--- a/libs/fleet/backend/billing/webhook.go+++ b/libs/fleet/backend/billing/webhook.go@@ -14,6 +14,7 @@ type WebhookEvent struct {Purpose stringSubject stringSource string+ IdentityClass stringCustomerID stringPaymentMethodID stringSetupGeneration string@@ -55,6 +56,10 @@ func (StripeWebhookVerifier) Verify(payload []byte, signature, secret string) (Wevent.Subject = subjectevent.Source = source}+ identityClass := productanalytics.IdentityClass(setupIntent.Metadata[MetadataIdentityClass])+ if identityClass == productanalytics.IdentityExternal || identityClass == productanalytics.IdentityInternal || identityClass == productanalytics.IdentityUnknown {+ event.IdentityClass = string(identityClass)+ }if setupIntent.Customer != nil {event.CustomerID = setupIntent.Customer.ID}diff --git a/libs/fleet/backend/billing/webhook_test.go b/libs/fleet/backend/billing/webhook_test.goindex 97209b7546..a5b8f3b00d 100644--- a/libs/fleet/backend/billing/webhook_test.go+++ b/libs/fleet/backend/billing/webhook_test.go@@ -26,7 +26,7 @@ func TestVerifyParsesFleetSetupIntentSucceeded(t *testing.T) {"object":"setup_intent","customer":"cus_owned","payment_method":"pm_card",- "metadata":{"purpose":"fleet_default_card","fleet_subject":"subject-1","fleet_source":"spa"}+ "metadata":{"purpose":"fleet_default_card","fleet_subject":"subject-1","fleet_source":"spa","fleet_identity_class":"external"}}}}`)signature := billingStripeSignature(payload, secret, time.Now().Unix())@@ -37,7 +37,7 @@ func TestVerifyParsesFleetSetupIntentSucceeded(t *testing.T) {}want := WebhookEvent{ID: "evt_setup", Type: "setup_intent.succeeded",- Purpose: SetupPurpose, Subject: "subject-1", Source: "spa", CustomerID: "cus_owned", PaymentMethodID: "pm_card",+ Purpose: SetupPurpose, Subject: "subject-1", Source: "spa", IdentityClass: "external", CustomerID: "cus_owned", PaymentMethodID: "pm_card",}if event != want {t.Fatalf("event = %#v, want %#v", event, want)diff --git a/libs/fleet/backend/docs/docs.go b/libs/fleet/backend/docs/docs.goindex 1a290dd244..3290b7b274 100644--- a/libs/fleet/backend/docs/docs.go+++ b/libs/fleet/backend/docs/docs.go@@ -496,6 +496,108 @@ const docTemplate = `{}}},+ "/api/billing/setup-session/complete": {+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Reconciles an authenticated subject's completed Stripe Checkout Session and configures its card as the default payment method.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Complete Stripe card setup Session",+ "parameters": [+ {+ "description": "Completed Checkout Session",+ "name": "request",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.BillingSetupCompletionRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.BillingSetupCompletionResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "409": {+ "description": "Conflict",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },"/api/billing/summary": {"get": {"security": [@@ -2162,6 +2264,22 @@ const docTemplate = `{}}},+ "handlers.BillingSetupCompletionRequest": {+ "type": "object",+ "properties": {+ "session_id": {+ "type": "string"+ }+ }+ },+ "handlers.BillingSetupCompletionResponse": {+ "type": "object",+ "properties": {+ "applied": {+ "type": "boolean"+ }+ }+ },"handlers.ConfigResponse": {"type": "object","properties": {diff --git a/libs/fleet/backend/docs/swagger.json b/libs/fleet/backend/docs/swagger.jsonindex 28c23d65a2..4d69f36a3f 100644--- a/libs/fleet/backend/docs/swagger.json+++ b/libs/fleet/backend/docs/swagger.json@@ -489,6 +489,108 @@}}},+ "/api/billing/setup-session/complete": {+ "post": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "description": "Reconciles an authenticated subject's completed Stripe Checkout Session and configures its card as the default payment method.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "billing"+ ],+ "summary": "Complete Stripe card setup Session",+ "parameters": [+ {+ "description": "Completed Checkout Session",+ "name": "request",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.BillingSetupCompletionRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/handlers.BillingSetupCompletionResponse"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "409": {+ "description": "Conflict",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "502": {+ "description": "Bad Gateway",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ }+ }+ }+ }+ },"/api/billing/summary": {"get": {"security": [@@ -2155,6 +2257,22 @@}}},+ "handlers.BillingSetupCompletionRequest": {+ "type": "object",+ "properties": {+ "session_id": {+ "type": "string"+ }+ }+ },+ "handlers.BillingSetupCompletionResponse": {+ "type": "object",+ "properties": {+ "applied": {+ "type": "boolean"+ }+ }+ },"handlers.ConfigResponse": {"type": "object","properties": {diff --git a/libs/fleet/backend/docs/swagger.yaml b/libs/fleet/backend/docs/swagger.yamlindex 4b994587ed..43c1a24e15 100644--- a/libs/fleet/backend/docs/swagger.yaml+++ b/libs/fleet/backend/docs/swagger.yaml@@ -225,6 +225,16 @@ definitions:url:type: stringtype: object+ handlers.BillingSetupCompletionRequest:+ properties:+ session_id:+ type: string+ type: object+ handlers.BillingSetupCompletionResponse:+ properties:+ applied:+ type: boolean+ type: objecthandlers.ConfigResponse:properties:admin:@@ -785,6 +795,73 @@ paths:summary: Create Stripe card setup Sessiontags:- billing+ /api/billing/setup-session/complete:+ post:+ consumes:+ - application/json+ description: Reconciles an authenticated subject's completed Stripe Checkout+ Session and configures its card as the default payment method.+ parameters:+ - description: Completed Checkout Session+ in: body+ name: request+ required: true+ schema:+ $ref: '#/definitions/handlers.BillingSetupCompletionRequest'+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/handlers.BillingSetupCompletionResponse'+ "400":+ description: Bad Request+ schema:+ additionalProperties:+ type: string+ type: object+ "401":+ description: Unauthorized+ schema:+ additionalProperties:+ type: string+ type: object+ "403":+ description: Forbidden+ schema:+ additionalProperties:+ type: string+ type: object+ "404":+ description: Not Found+ schema:+ additionalProperties:+ type: string+ type: object+ "409":+ description: Conflict+ schema:+ additionalProperties:+ type: string+ type: object+ "502":+ description: Bad Gateway+ schema:+ additionalProperties:+ type: string+ type: object+ "503":+ description: Service Unavailable+ schema:+ additionalProperties:+ type: string+ type: object+ security:+ - BearerAuth: []+ summary: Complete Stripe card setup Session+ tags:+ - billing/api/billing/summary:get:description: Returns a sanitized Stripe-backed billing summary for the authenticateddiff --git a/libs/fleet/backend/handlers/billing.go b/libs/fleet/backend/handlers/billing.goindex bedd3875d8..ae6e515f01 100644--- a/libs/fleet/backend/handlers/billing.go+++ b/libs/fleet/backend/handlers/billing.go@@ -2,6 +2,7 @@ package handlersimport ("context"+ "encoding/json""errors""io""log/slog"@@ -28,10 +29,22 @@ type BillingUsageService interface {Usage(ctx context.Context, subject string, months int, now time.Time) (billing.Usage, error)}+type BillingSetupCompletionService interface {+ CompleteSetupSession(ctx context.Context, subject, source, identityClass, sessionID string) (billing.SetupCompletion, error)+}+type BillingSessionResponse struct {URL string `json:"url"`}+type BillingSetupCompletionRequest struct {+ SessionID string `json:"session_id"`+}++type BillingSetupCompletionResponse struct {+ Applied bool `json:"applied"`+}+func (h Handlers) billingAvailable(w http.ResponseWriter) bool {if h.Billing == nil || h.Stripe.SecretKey == "" {writeErr(w, http.StatusServiceUnavailable, "Stripe billing is not configured")@@ -80,6 +93,44 @@ func requireEmptyBillingBody(w http.ResponseWriter, r *http.Request) bool {return true}+func decodeBillingSetupCompletion(w http.ResponseWriter, r *http.Request) (BillingSetupCompletionRequest, bool) {+ r.Body = http.MaxBytesReader(w, r.Body, 512)+ decoder := json.NewDecoder(r.Body)+ decoder.DisallowUnknownFields()+ var request BillingSetupCompletionRequest+ if err := decoder.Decode(&request); err != nil {+ var maxErr *http.MaxBytesError+ if errors.As(err, &maxErr) {+ writeErr(w, http.StatusRequestEntityTooLarge, "billing setup completion request is too large")+ return BillingSetupCompletionRequest{}, false+ }+ writeErr(w, http.StatusBadRequest, "invalid billing setup completion request")+ return BillingSetupCompletionRequest{}, false+ }+ if err := decoder.Decode(&struct{}{}); err != io.EOF {+ writeErr(w, http.StatusBadRequest, "invalid billing setup completion request")+ return BillingSetupCompletionRequest{}, false+ }+ request.SessionID = strings.TrimSpace(request.SessionID)+ if !validCheckoutSessionID(request.SessionID) {+ writeErr(w, http.StatusBadRequest, "invalid billing setup completion request")+ return BillingSetupCompletionRequest{}, false+ }+ return request, true+}++func validCheckoutSessionID(sessionID string) bool {+ if len(sessionID) < len("cs_x") || len(sessionID) > 255 || !strings.HasPrefix(sessionID, "cs_") {+ return false+ }+ for _, char := range sessionID {+ if (char < 'a' || char > 'z') && (char < 'A' || char > 'Z') && (char < '0' || char > '9') && char != '_' {+ return false+ }+ }+ return true+}+// poolCreateCardRequired resolves the advisory pool_create_card_required// summary field from the same admission policy /api/k8s enforces. The field// only pre-warns the dashboard — the policy still denies bypassing creates —@@ -182,15 +233,17 @@ func (h Handlers) CreateBillingSetupSession(w http.ResponseWriter, r *http.Requeif !ok || !requireEmptyBillingBody(w, r) || !h.billingAvailable(w) {return}- if h.Stripe.CheckoutSuccessURL == "" || h.Stripe.CheckoutCancelURL == "" {- writeErr(w, http.StatusServiceUnavailable, "Stripe card setup is not configured; redirect URLs are required")+ if h.Stripe.CheckoutSuccessURL == "" || h.Stripe.CheckoutCancelURL == "" ||+ strings.Count(h.Stripe.CheckoutSuccessURL, "{CHECKOUT_SESSION_ID}") != 1 {+ writeErr(w, http.StatusServiceUnavailable, "Stripe card setup is not configured; a session-aware success URL and cancel URL are required")return}source, sourceOK := productanalytics.SourceForUser(user, h.AuthCfg.SPAClientID)+ if !sourceOK || source != productanalytics.SourceSPA {+ writeErr(w, http.StatusForbidden, "Fleet browser session is required")+ return+ }captureSetupStart := func(outcome string, statusCode int, errorClass string) {- if !sourceOK {- return- }traceID, _ := r.Context().Value(middlewares.ContextKey("traceId")).(string)capturer := h.Analyticsif capturer == nil {@@ -212,9 +265,10 @@ func (h Handlers) CreateBillingSetupSession(w http.ResponseWriter, r *http.Reque})}url, err := h.Billing.CreateSetupSession(r.Context(), user.ID, billing.SetupOptions{- SuccessURL: h.Stripe.CheckoutSuccessURL,- CancelURL: h.Stripe.CheckoutCancelURL,- Source: source,+ SuccessURL: h.Stripe.CheckoutSuccessURL,+ CancelURL: h.Stripe.CheckoutCancelURL,+ Source: source,+ IdentityClass: string(productanalytics.ClassifyIdentity(user)),})if err != nil {captureSetupStart(productanalytics.OutcomeFailure, http.StatusBadGateway, "payment_provider")@@ -225,6 +279,78 @@ func (h Handlers) CreateBillingSetupSession(w http.ResponseWriter, r *http.RequewriteJSON(w, http.StatusOK, BillingSessionResponse{URL: url})}+// CompleteBillingSetupSession godoc+// @Summary Complete Stripe card setup Session+// @Description Reconciles an authenticated subject's completed Stripe Checkout Session and configures its card as the default payment method.+// @Tags billing+// @Accept json+// @Produce json+// @Param request body BillingSetupCompletionRequest true "Completed Checkout Session"+// @Success 200 {object} BillingSetupCompletionResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 403 {object} map[string]string+// @Failure 404 {object} map[string]string+// @Failure 409 {object} map[string]string+// @Failure 502 {object} map[string]string+// @Failure 503 {object} map[string]string+// @Security BearerAuth+// @Router /api/billing/setup-session/complete [post]+func (h Handlers) CompleteBillingSetupSession(w http.ResponseWriter, r *http.Request) {+ user, ok := requireBillingEnabled(w, r)+ if !ok || !h.billingAvailable(w) {+ return+ }+ source, sourceOK := productanalytics.SourceForUser(user, h.AuthCfg.SPAClientID)+ if !sourceOK || source != productanalytics.SourceSPA {+ writeErr(w, http.StatusForbidden, "Fleet browser session is required")+ return+ }+ request, ok := decodeBillingSetupCompletion(w, r)+ if !ok {+ return+ }+ completionService, ok := h.Billing.(BillingSetupCompletionService)+ if !ok {+ writeErr(w, http.StatusServiceUnavailable, "billing setup completion is not configured")+ return+ }+ result, err := completionService.CompleteSetupSession(+ r.Context(), user.ID, source, string(productanalytics.ClassifyIdentity(user)), request.SessionID,+ )+ switch {+ case errors.Is(err, billing.ErrSetupSessionNotFound), errors.Is(err, billing.ErrSetupSessionNotOwned):+ writeErr(w, http.StatusNotFound, "billing setup session was not found")+ return+ case errors.Is(err, billing.ErrSetupSessionIncomplete):+ writeErr(w, http.StatusConflict, "Stripe card setup is not complete")+ return+ case errors.Is(err, billing.ErrSetupSessionInvalid):+ writeErr(w, http.StatusBadRequest, "invalid Stripe card setup session")+ return+ case err != nil:+ writeErr(w, http.StatusBadGateway, "could not complete Stripe card setup")+ return+ }+ if result.Applied {+ capturer := h.Analytics+ if capturer == nil {+ capturer = productanalytics.Nop()+ }+ capturer.Capture(productanalytics.Event{+ Name: productanalytics.EventPaymentMethodSetup, DistinctID: user.ID,+ InsertID: "fleet-payment-setup:" + result.SetupIntentID,+ Properties: map[string]any{+ "outcome": productanalytics.OutcomeSuccess,+ "source": source,+ "principal_type": user.PrincipalType,+ "identity_class": productanalytics.ClassifyIdentity(user),+ },+ })+ }+ writeJSON(w, http.StatusOK, BillingSetupCompletionResponse{Applied: result.Applied})+}+// CreateBillingPortalSession godoc// @Summary Create Stripe Billing Portal Session// @Description Creates a Stripe-hosted Billing Portal Session for the customer owned by the authenticated Cyclops subject.diff --git a/libs/fleet/backend/handlers/billing_test.go b/libs/fleet/backend/handlers/billing_test.goindex d1e3a6c748..7aaeeb9c65 100644--- a/libs/fleet/backend/handlers/billing_test.go+++ b/libs/fleet/backend/handlers/billing_test.go@@ -37,6 +37,13 @@ type fakeBillingService struct {defaultApplied booldefaultCalls intdefaultErr error+ completeSubject string+ completeSource string+ completeIdentityClass string+ completeSessionID string+ completeResult billing.SetupCompletion+ completeCalls int+ completeErr errorusageMonths intusageSubject stringusageResponse billing.Usage@@ -87,6 +94,15 @@ func (f *fakeBillingService) CreatePortalSession(_ context.Context, subject, retreturn "https://billing.stripe.test/session", nil}+func (f *fakeBillingService) CompleteSetupSession(_ context.Context, subject, source, identityClass, sessionID string) (billing.SetupCompletion, error) {+ f.completeCalls+++ f.completeSubject = subject+ f.completeSource = source+ f.completeIdentityClass = identityClass+ f.completeSessionID = sessionID+ return f.completeResult, f.completeErr+}+func (f *fakeBillingService) Usage(_ context.Context, subject string, months int, _ time.Time) (billing.Usage, error) {f.usageSubject = subjectf.usageMonths = months@@ -280,7 +296,7 @@ func TestCreateSetupSessionUsesAuthenticatedSubjectAndNoClientInput(t *testing.TAuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},Stripe: config.StripeConfiguration{SecretKey: "sk_test",- CheckoutSuccessURL: "https://run.example.test/settings?setup=success",+ CheckoutSuccessURL: "https://run.example.test/settings?checkout=success&session_id={CHECKOUT_SESSION_ID}",CheckoutCancelURL: "https://run.example.test/settings?setup=cancelled",},}@@ -328,6 +344,114 @@ func TestCreateSetupSessionUsesAuthenticatedSubjectAndNoClientInput(t *testing.T}}+func TestCompleteSetupSessionUsesAuthenticatedOwnershipAndEmitsPrivacySafeSuccess(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{completeResult: billing.SetupCompletion{Applied: true, SetupIntentID: "seti_owned"}}+ capture := &analyticsCapture{}+ h := Handlers{+ Billing: service, Analytics: capture,+ AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},+ Stripe: config.StripeConfiguration{SecretKey: "sk_test"},+ }+ response := httptest.NewRecorder()+ h.CompleteBillingSetupSession(response, newBillingRequest(+ http.MethodPost,+ "/api/billing/setup-session/complete",+ `{"session_id":"cs_test_owned"}`,+ billingAlice,+ ))++ if response.Code != http.StatusOK || service.completeCalls != 1 {+ t.Fatalf("status/calls = %d/%d; body = %s", response.Code, service.completeCalls, response.Body.String())+ }+ if service.completeSubject != billingAlice.ID || service.completeSource != productanalytics.SourceSPA ||+ service.completeIdentityClass != string(productanalytics.IdentityExternal) || service.completeSessionID != "cs_test_owned" {+ t.Fatalf("completion ownership = %q/%q/%q/%q", service.completeSubject, service.completeSource, service.completeIdentityClass, service.completeSessionID)+ }+ var body BillingSetupCompletionResponse+ if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || !body.Applied {+ t.Fatalf("response = %#v, error = %v", body, err)+ }+ if len(capture.events) != 1 {+ t.Fatalf("events = %#v", capture.events)+ }+ event := capture.events[0]+ if event.Name != productanalytics.EventPaymentMethodSetup || event.DistinctID != billingAlice.ID ||+ event.InsertID != "fleet-payment-setup:seti_owned" ||+ event.Properties["outcome"] != productanalytics.OutcomeSuccess ||+ event.Properties["source"] != productanalytics.SourceSPA ||+ event.Properties["principal_type"] != auth.PrincipalTypeUser ||+ event.Properties["identity_class"] != productanalytics.IdentityExternal {+ t.Fatalf("event = %#v", event)+ }+ if err := productanalytics.ValidateEvent(event); err != nil {+ t.Fatalf("privacy-safe event validation failed: %v", err)+ }+}++func TestCompleteSetupSessionDoesNotEmitForIdempotentReplay(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{completeResult: billing.SetupCompletion{SetupIntentID: "seti_owned"}}+ capture := &analyticsCapture{}+ h := Handlers{+ Billing: service, Analytics: capture,+ AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},+ Stripe: config.StripeConfiguration{SecretKey: "sk_test"},+ }+ response := httptest.NewRecorder()+ h.CompleteBillingSetupSession(response, newBillingRequest(http.MethodPost, "/api/billing/setup-session/complete", `{"session_id":"cs_test_owned"}`, billingAlice))+ if response.Code != http.StatusOK || len(capture.events) != 0 {+ t.Fatalf("status/events = %d/%#v", response.Code, capture.events)+ }+}++func TestCompleteSetupSessionRejectsUnownedAndIncompleteSessions(t *testing.T) {+ setBillingFlag(t, true)+ for _, testCase := range []struct {+ name string+ err error+ want int+ }{+ {name: "unowned", err: billing.ErrSetupSessionNotOwned, want: http.StatusNotFound},+ {name: "incomplete", err: billing.ErrSetupSessionIncomplete, want: http.StatusConflict},+ {name: "invalid", err: billing.ErrSetupSessionInvalid, want: http.StatusBadRequest},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ service := &fakeBillingService{completeErr: testCase.err}+ h := Handlers{+ Billing: service,+ AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},+ Stripe: config.StripeConfiguration{SecretKey: "sk_test"},+ }+ response := httptest.NewRecorder()+ h.CompleteBillingSetupSession(response, newBillingRequest(http.MethodPost, "/api/billing/setup-session/complete", `{"session_id":"cs_test_owned"}`, billingAlice))+ if response.Code != testCase.want {+ t.Fatalf("status = %d, want %d; body = %s", response.Code, testCase.want, response.Body.String())+ }+ })+ }+}++func TestCompleteSetupSessionRejectsClientControlledFields(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{}+ h := Handlers{+ Billing: service,+ AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},+ Stripe: config.StripeConfiguration{SecretKey: "sk_test"},+ }+ response := httptest.NewRecorder()+ h.CompleteBillingSetupSession(response, newBillingRequest(+ http.MethodPost,+ "/api/billing/setup-session/complete",+ `{"session_id":"cs_test_owned","customer":"cus_attacker"}`,+ billingAlice,+ ))+ if response.Code != http.StatusBadRequest || service.completeCalls != 0 {+ t.Fatalf("status/calls = %d/%d; body = %s", response.Code, service.completeCalls, response.Body.String())+ }+}+func TestCreatePortalSessionDerivesOwnedCustomerFromCurrentUser(t *testing.T) {setBillingFlag(t, true)service := &fakeBillingService{}@@ -387,6 +511,15 @@ func TestBillingEndpointsRejectWhenFlagDisabled(t *testing.T) {return service.portalCalls},},+ {+ name: "setup completion",+ handle: func(h Handlers, w http.ResponseWriter, r *http.Request) { h.CompleteBillingSetupSession(w, r) },+ method: http.MethodPost,+ path: "/api/billing/setup-session/complete",+ invoked: func(service *fakeBillingService) int {+ return service.completeCalls+ },+ },}for _, test := range tests {@@ -396,7 +529,7 @@ func TestBillingEndpointsRejectWhenFlagDisabled(t *testing.T) {Billing: service,Stripe: config.StripeConfiguration{SecretKey: "sk_test",- CheckoutSuccessURL: "https://run.example.test/settings?setup=success",+ CheckoutSuccessURL: "https://run.example.test/settings?checkout=success&session_id={CHECKOUT_SESSION_ID}",CheckoutCancelURL: "https://run.example.test/settings?setup=cancelled",PortalReturnURL: "https://run.example.test/billing",},@@ -423,7 +556,7 @@ func TestCreateSetupSessionProviderFailureEmitsFailureEvent(t *testing.T) {Billing: service,Analytics: capture,AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},- Stripe: config.StripeConfiguration{SecretKey: "sk_test", CheckoutSuccessURL: "https://run.example.test/success", CheckoutCancelURL: "https://run.example.test/cancel"},+ Stripe: config.StripeConfiguration{SecretKey: "sk_test", CheckoutSuccessURL: "https://run.example.test/success?session_id={CHECKOUT_SESSION_ID}", CheckoutCancelURL: "https://run.example.test/cancel"},}response := httptest.NewRecorder()h.CreateBillingSetupSession(response, newBillingRequest(http.MethodPost, "/api/billing/setup-session", "", billingAlice))@@ -442,7 +575,7 @@ func TestCreateSetupSessionProviderFailureEmitsFailureEvent(t *testing.T) {}}-func TestCreateSetupSessionDoesNotCaptureUnknownSource(t *testing.T) {+func TestCreateSetupSessionRejectsUnknownSource(t *testing.T) {setBillingFlag(t, true)service := &fakeBillingService{}capture := &analyticsCapture{}@@ -452,13 +585,13 @@ func TestCreateSetupSessionDoesNotCaptureUnknownSource(t *testing.T) {Billing: service,Analytics: capture,AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},- Stripe: config.StripeConfiguration{SecretKey: "sk_test", CheckoutSuccessURL: "https://run.example.test/success", CheckoutCancelURL: "https://run.example.test/cancel"},+ Stripe: config.StripeConfiguration{SecretKey: "sk_test", CheckoutSuccessURL: "https://run.example.test/success?session_id={CHECKOUT_SESSION_ID}", CheckoutCancelURL: "https://run.example.test/cancel"},}response := httptest.NewRecorder()h.CreateBillingSetupSession(response, newBillingRequest(http.MethodPost, "/api/billing/setup-session", "", &user))- if response.Code != http.StatusOK || len(capture.events) != 0 {- t.Fatalf("status/events = %d/%#v, want 200/no events", response.Code, capture.events)+ if response.Code != http.StatusForbidden || service.setupCalls != 0 || len(capture.events) != 0 {+ t.Fatalf("status/calls/events = %d/%d/%#v, want 403/no calls/no events", response.Code, service.setupCalls, capture.events)}}diff --git a/libs/fleet/backend/handlers/billing_webhook.go b/libs/fleet/backend/handlers/billing_webhook.goindex 28ae29094e..c3d092b162 100644--- a/libs/fleet/backend/handlers/billing_webhook.go+++ b/libs/fleet/backend/handlers/billing_webhook.go@@ -119,6 +119,9 @@ func capturePaymentSetup(capturer productanalytics.Capturer, event billing.Webhoproperties := map[string]any{"outcome": outcome, "source": event.Source, "principal_type": principalType,}+ if event.IdentityClass != "" {+ properties["identity_class"] = productanalytics.IdentityClass(event.IdentityClass)+ }if errorClass != "" {properties["error_class"] = errorClass}diff --git a/libs/fleet/backend/handlers/billing_webhook_test.go b/libs/fleet/backend/handlers/billing_webhook_test.goindex fadf028f3d..e0d1992ad5 100644--- a/libs/fleet/backend/handlers/billing_webhook_test.go+++ b/libs/fleet/backend/handlers/billing_webhook_test.go@@ -207,12 +207,12 @@ func runBillingWebhookWithAnalytics(t *testing.T, service *fakeBillingService, efunc TestBillingWebhookEmitsAppliedPaymentSuccess(t *testing.T) {service := &fakeBillingService{defaultApplied: true}capture := &analyticsCapture{}- response := runBillingWebhookWithAnalytics(t, service, billing.WebhookEvent{ID: "evt_123", Type: "setup_intent.succeeded", Purpose: billing.SetupPurpose, Subject: "subject-1", Source: productanalytics.SourceSPA, CustomerID: "cus_owned", PaymentMethodID: "pm_card", SetupGeneration: "current"}, capture)+ response := runBillingWebhookWithAnalytics(t, service, billing.WebhookEvent{ID: "evt_123", Type: "setup_intent.succeeded", Purpose: billing.SetupPurpose, Subject: "subject-1", Source: productanalytics.SourceSPA, IdentityClass: string(productanalytics.IdentityExternal), CustomerID: "cus_owned", PaymentMethodID: "pm_card", SetupGeneration: "current"}, capture)if response.Code != http.StatusNoContent || len(capture.events) != 1 {t.Fatalf("status/events = %d/%#v", response.Code, capture.events)}event := capture.events[0]- if event.Name != productanalytics.EventPaymentMethodSetup || event.DistinctID != "subject-1" || event.InsertID != "evt_123" || event.Properties["outcome"] != productanalytics.OutcomeSuccess {+ if event.Name != productanalytics.EventPaymentMethodSetup || event.DistinctID != "subject-1" || event.InsertID != "evt_123" || event.Properties["outcome"] != productanalytics.OutcomeSuccess || event.Properties["identity_class"] != productanalytics.IdentityExternal {t.Fatalf("event = %#v", event)}}diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.goindex 8c3702d966..a53783976b 100644--- a/libs/fleet/backend/main.go+++ b/libs/fleet/backend/main.go@@ -184,6 +184,8 @@ func setupRouter(c handlers.Handlers) http.Handler {withAuthenticatedMiddlewares("/api/billing/usage", c.GetBillingUsage))r.Handle("POST /api/billing/setup-session",withAuthenticatedMiddlewares("/api/billing/setup-session", c.CreateBillingSetupSession))+ r.Handle("POST /api/billing/setup-session/complete",+ withAuthenticatedMiddlewares("/api/billing/setup-session/complete", c.CompleteBillingSetupSession))r.Handle("POST /api/billing/portal-session",withAuthenticatedMiddlewares("/api/billing/portal-session", c.CreateBillingPortalSession))r.Handle("POST /api/billing/webhook",diff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.goindex 00f45f5af4..161e700110 100644--- a/libs/fleet/backend/main_test.go+++ b/libs/fleet/backend/main_test.go@@ -206,6 +206,9 @@ func TestSwaggerUsesBillingSetupSessionRoute(t *testing.T) {if _, ok := spec.Paths["/api/billing/setup-session"]; !ok {t.Fatal("swagger.json missing /api/billing/setup-session")}+ if _, ok := spec.Paths["/api/billing/setup-session/complete"]; !ok {+ t.Fatal("swagger.json missing /api/billing/setup-session/complete")+ }if _, ok := spec.Paths["/api/billing/usage"]; !ok {t.Fatal("swagger.json missing /api/billing/usage")}@@ -459,6 +462,10 @@ func (routerBillingService) CreatePortalSession(context.Context, string, string)return "https://billing.stripe.test/session", nil}+func (routerBillingService) CompleteSetupSession(context.Context, string, string, string, string) (billing.SetupCompletion, error) {+ return billing.SetupCompletion{Applied: true, SetupIntentID: "seti_router"}, nil+}+func (routerBillingService) SetDefaultPaymentMethodForSetupGeneration(context.Context, string, string, string) (bool, error) {return true, nil}@@ -505,6 +512,7 @@ func TestBillingRouterAuthorizationBoundaries(t *testing.T) {path string}{{name: "setup", path: "/api/billing/setup-session"},+ {name: "setup completion", path: "/api/billing/setup-session/complete"},{name: "portal", path: "/api/billing/portal-session"},} {t.Run(tc.name, func(t *testing.T) {diff --git a/libs/fleet/docs/stripe-billing-mvp-plan.md b/libs/fleet/docs/stripe-billing-mvp-plan.mdindex 596d115987..0ccc2b617a 100644--- a/libs/fleet/docs/stripe-billing-mvp-plan.md+++ b/libs/fleet/docs/stripe-billing-mvp-plan.md@@ -4,7 +4,7 @@- Stripe-hosted card setup in Checkout `setup` mode.- Fleet-owned Customer metadata derived from the authenticated Cyclops subject.-- Signed SetupIntent webhook default-card configuration.+- Signed SetupIntent webhook default-card configuration in production, with authenticated Checkout-return reconciliation where no webhook endpoint exists.- Sanitized saved-card status for the authenticated fleet owner.- Billing Portal card replacement and removal.@@ -12,6 +12,7 @@- `GET /api/billing/summary` returns the authenticated fleet owner's sanitized saved-card status.- `POST /api/billing/setup-session` accepts an empty request body and returns a Stripe-hosted card setup URL.+- `POST /api/billing/setup-session/complete` accepts only the returned Checkout Session ID, verifies it belongs to the authenticated subject and represents the current successful Fleet setup generation, then idempotently configures the default card.- `POST /api/billing/portal-session` accepts an empty request body and returns the authenticated fleet owner's Billing Portal URL.- `POST /api/billing/webhook` verifies the bounded raw Stripe body and configures the fleet's default card from signed SetupIntent events.@@ -20,4 +21,5 @@- The browser never receives a Stripe secret key or submits card details to Cyclops.- The backend derives fleet ownership from the authenticated request context and controlled Customer metadata.- Setup and portal sessions use only the Customer owned by the authenticated subject.+- Checkout-return reconciliation rejects sessions with mismatched ownership, purpose, source, state, or setup generation.- Webhook verification uses the unparsed raw body and rejects missing, invalid, or oversized signatures.diff --git a/libs/fleet/e2e/billing.spec.ts b/libs/fleet/e2e/billing.spec.tsindex eaccd81359..ced24a008d 100644--- a/libs/fleet/e2e/billing.spec.ts+++ b/libs/fleet/e2e/billing.spec.ts@@ -247,6 +247,53 @@ test("settings displays the saved default card", async ({ page }) => {).toHaveCount(0);});+test("settings reconciles a returned Checkout Session before showing the saved card", async ({+ page,+}) => {+ await setBillingFlag(page, true);+ let completionCalls = 0;+ await page.route("**/api/billing/setup-session/complete", async (route) => {+ completionCalls++;+ expect(route.request().method()).toBe("POST");+ expect(route.request().postDataJSON()).toEqual({+ session_id: "cs_test_owned",+ });+ await new Promise((resolve) => setTimeout(resolve, 150));+ await route.fulfill({ json: { applied: true } });+ });+ await page.route("**/api/billing/summary", (route) =>+ route.fulfill({+ json: {+ payment_method_present: true,+ card: { brand: "visa", last4: "4242", exp_month: 12, exp_year: 2030 },+ },+ }),+ );++ await page.goto(+ "/settings?checkout=success&session_id=cs_test_owned&utm_source=github",+ );+ await expect(page.getByText("Confirming payment method")).toBeVisible();+ await expect(page.getByText("Visa ending in 4242")).toBeVisible();+ await expect(page.getByText("Payment method saved")).toBeVisible();+ await expect(page).toHaveURL(/\/settings\?utm_source=github$/);+ expect(completionCalls).toBe(1);+});++test("settings removes a failed Checkout Session ID without claiming success", async ({+ page,+}) => {+ await setBillingFlag(page, true);+ await page.route("**/api/billing/setup-session/complete", (route) =>+ route.fulfill({ status: 409, json: { error: "setup is incomplete" } }),+ );++ await page.goto("/settings?checkout=success&session_id=cs_test_incomplete");+ await expect(page.getByText("Billing is temporarily unavailable")).toBeVisible();+ await expect(page.getByText("Payment method saved")).toHaveCount(0);+ await expect(page).toHaveURL(/\/settings$/);+});+test("settings shows a billing load error", async ({ page }) => {await setBillingFlag(page, true);await page.route("**/api/billing/summary", (route) =>diff --git a/libs/fleet/src/api/billing.ts b/libs/fleet/src/api/billing.tsindex 01b669d21e..b880d058d3 100644--- a/libs/fleet/src/api/billing.ts+++ b/libs/fleet/src/api/billing.ts@@ -55,11 +55,17 @@ export interface BillingUsage {async function billingRequest<T>(path: string,method: "GET" | "POST",+ body?: unknown,): Promise<T> {const token = await getToken();+ const headers: Record<string, string> = {+ Authorization: token ? `Bearer ${token}` : "",+ };+ if (body !== undefined) headers["Content-Type"] = "application/json";const response = await fetch(path, {method,- headers: { Authorization: token ? `Bearer ${token}` : "" },+ headers,+ body: body === undefined ? undefined : JSON.stringify(body),});if (!response.ok)throw new Error(`billing request failed: ${response.status}`);@@ -81,6 +87,12 @@ export const billingApi = {url: localVisualPreviewPath("/settings?billing=setup-preview"),}): billingRequest<{ url: string }>("/api/billing/setup-session", "POST"),+ completeSetup: (sessionID: string) =>+ billingRequest<{ applied: boolean }>(+ "/api/billing/setup-session/complete",+ "POST",+ { session_id: sessionID },+ ),portal: () =>isLocalVisualPreview()? Promise.resolve({diff --git a/libs/fleet/src/pages/Billing.tsx b/libs/fleet/src/pages/Billing.tsxindex 46f531d76f..374bb8c3a5 100644--- a/libs/fleet/src/pages/Billing.tsx+++ b/libs/fleet/src/pages/Billing.tsx@@ -7,7 +7,8 @@ import Container from "@cloudscape-design/components/container";import Header from "@cloudscape-design/components/header";import SpaceBetween from "@cloudscape-design/components/space-between";import Spinner from "@cloudscape-design/components/spinner";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";+import { useLocation, useNavigate } from "react-router-dom";import { CuaButton } from "../components/CuaButton";import { billingApi, type BillingSummary } from "../api/billing";@@ -16,16 +17,51 @@ function cardBrand(brand: string) {}export function BillingSettings() {+ const location = useLocation();+ const navigate = useNavigate();const [summary, setSummary] = useState<BillingSummary | null>(null);const [error, setError] = useState(false);const [redirecting, setRedirecting] = useState(false);+ const [setupComplete, setSetupComplete] = useState(false);+ const completionAttempt = useRef<string | null>(null);useEffect(() => {+ const params = new URLSearchParams(location.search);+ const sessionID = params.get("session_id");+ if (params.get("checkout") !== "success" || !sessionID) {+ billingApi+ .summary()+ .then(setSummary)+ .catch(() => setError(true));+ return;+ }+ if (completionAttempt.current === sessionID) return;+ completionAttempt.current = sessionID;+ setSummary(null);+ setRedirecting(true);+ setError(false);billingApi- .summary()- .then(setSummary)- .catch(() => setError(true));- }, []);+ .completeSetup(sessionID)+ .then(() => billingApi.summary())+ .then((nextSummary) => {+ if (!nextSummary.payment_method_present) {+ throw new Error("payment method was not confirmed");+ }+ setSummary(nextSummary);+ setSetupComplete(true);+ })+ .catch(() => setError(true))+ .finally(() => {+ params.delete("checkout");+ params.delete("session_id");+ const search = params.toString();+ navigate(+ { pathname: location.pathname, search: search ? `?${search}` : "" },+ { replace: true },+ );+ setRedirecting(false);+ });+ }, [location.pathname, location.search, navigate]);const redirect = async (kind: "setup" | "portal") => {setRedirecting(true);@@ -43,13 +79,18 @@ export function BillingSettings() {if (error) {return (<Alert type="error" header="Billing is temporarily unavailable">- Try again later. No billing changes were made.+ Refresh and try again. Card details remain securely with Stripe.</Alert>);}return (<SpaceBetween size="l">+ {setupComplete && (+ <Alert type="success" header="Payment method saved">+ Your card is ready for Fleet usage charges.+ </Alert>+ )}<Containerheader={<Header@@ -76,7 +117,10 @@ export function BillingSettings() {}>{!summary ? (- <Spinner />+ <SpaceBetween direction="horizontal" size="xs">+ <Spinner />+ <Box>{redirecting ? "Confirming payment method" : "Loading"}</Box>+ </SpaceBetween>) : summary.payment_method_present && summary.card ? (<SpaceBetween size="xs"><Box variant="h3">