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(billing): decouple setup completion from analytics classification (#7535)
Francesco Bonacci5cd40c1d0222
diff --git a/libs/fleet/backend/billing/service.go b/libs/fleet/backend/billing/service.goindex a0afa778af..9ad92b4090 100644--- a/libs/fleet/backend/billing/service.go+++ b/libs/fleet/backend/billing/service.go@@ -408,8 +408,8 @@ 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 == "" {+func (s *Service) CompleteSetupSession(ctx context.Context, subject, source, sessionID string) (SetupCompletion, error) {+ if subject == "" || source == "" || sessionID == "" {return SetupCompletion{}, ErrSetupSessionInvalid}customer, err := s.findCustomerReadOnly(ctx, subject)@@ -428,10 +428,12 @@ func (s *Service) CompleteSetupSession(ctx context.Context, subject, source, idesession.Metadata[MetadataSubject] != subject {return SetupCompletion{}, ErrSetupSessionNotOwned}+ // Analytics classification can change after setup starts (for example, when+ // admin membership becomes unavailable). It is not an ownership credential+ // and must not prevent an otherwise valid payment-method setup.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{}, ErrSetupSessionInvaliddiff --git a/libs/fleet/backend/billing/service_test.go b/libs/fleet/backend/billing/service_test.goindex 07953607e8..d7da003c0f 100644--- a/libs/fleet/backend/billing/service_test.go+++ b/libs/fleet/backend/billing/service_test.go@@ -442,7 +442,7 @@ func TestCompleteSetupSessionVerifiesOwnershipAndAppliesCurrentGeneration(t *tesdefaultApplied: true,}- result, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "external", "cs_test_owned")+ result, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "cs_test_owned")if err != nil {t.Fatalf("CompleteSetupSession() error = %v", err)}@@ -463,12 +463,34 @@ func TestCompleteSetupSessionRejectsUnownedSessionWithoutUpdatingCustomer(t *tessetupSession: session,}- _, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "external", "cs_test_owned")+ _, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "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 TestCompleteSetupSessionDoesNotRequireAnalyticsClassification(t *testing.T) {+ for _, storedClass := range []string{"external", "internal", "unknown", "", "unrecognized"} {+ t.Run(storedClass, func(t *testing.T) {+ session := successfulSetupSession()+ delete(session.Metadata, MetadataIdentityClass)+ if storedClass != "" {+ session.Metadata[MetadataIdentityClass] = storedClass+ }+ gateway := &fakeGateway{+ customers: []Customer{{ID: "cus_owned", Metadata: map[string]string{MetadataSubject: "subject-123"}}},+ setupSession: session,+ defaultApplied: true,+ }+ result, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "cs_test_owned")+ if err != nil || result != (SetupCompletion{Applied: true, SetupIntentID: "seti_owned"}) ||+ gateway.defaultCustomerID != "cus_owned" || gateway.defaultPaymentMethodID != "pm_card" || gateway.defaultGeneration != "current" {+ t.Fatalf("classification must not gate owned successful setup: result=%#v, error=%v", result, err)+ }+ })+ }+}+func TestCompleteSetupSessionRejectsMismatchedTrustedMetadata(t *testing.T) {tests := []struct {name string@@ -477,7 +499,12 @@ func TestCompleteSetupSessionRejectsMismatchedTrustedMetadata(t *testing.T) {}{{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: "checkout customer", mutate: func(session *SetupSession) { session.CustomerID = "cus_other" }, want: ErrSetupSessionNotOwned},+ {name: "setup intent customer", mutate: func(session *SetupSession) { session.SetupIntentCustomerID = "cus_other" }, want: ErrSetupSessionNotOwned},+ {name: "session ID", mutate: func(session *SetupSession) { session.ID = "cs_other" }, want: ErrSetupSessionInvalid},+ {name: "mode", mutate: func(session *SetupSession) { session.Mode = "payment" }, want: ErrSetupSessionInvalid},+ {name: "setup intent ID", mutate: func(session *SetupSession) { session.SetupIntentID = "" }, want: ErrSetupSessionInvalid},+ {name: "payment method", mutate: func(session *SetupSession) { session.PaymentMethodID = "" }, 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},}@@ -489,7 +516,7 @@ func TestCompleteSetupSessionRejectsMismatchedTrustedMetadata(t *testing.T) {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")+ _, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "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)}@@ -513,7 +540,7 @@ func TestCompleteSetupSessionRequiresTerminalSuccess(t *testing.T) {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")+ _, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "cs_test_owned")if !errors.Is(err, ErrSetupSessionIncomplete) || gateway.defaultCustomerID != "" {t.Fatalf("error/default customer = %v/%q, want incomplete/no update", err, gateway.defaultCustomerID)}@@ -526,7 +553,7 @@ func TestCompleteSetupSessionDuplicateIsSuccessfulWithoutReapplying(t *testing.Tcustomers: []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")+ result, err := NewService(gateway).CompleteSetupSession(context.Background(), "subject-123", "spa", "cs_test_owned")if err != nil || result.Applied || result.SetupIntentID != "seti_owned" {t.Fatalf("result/error = %#v/%v, want safe duplicate", result, err)}diff --git a/libs/fleet/backend/handlers/billing.go b/libs/fleet/backend/handlers/billing.goindex ae6e515f01..d5c5359b38 100644--- a/libs/fleet/backend/handlers/billing.go+++ b/libs/fleet/backend/handlers/billing.go@@ -30,7 +30,7 @@ type BillingUsageService interface {}type BillingSetupCompletionService interface {- CompleteSetupSession(ctx context.Context, subject, source, identityClass, sessionID string) (billing.SetupCompletion, error)+ CompleteSetupSession(ctx context.Context, subject, source, sessionID string) (billing.SetupCompletion, error)}type BillingSessionResponse struct {@@ -316,7 +316,7 @@ func (h Handlers) CompleteBillingSetupSession(w http.ResponseWriter, r *http.Reqreturn}result, err := completionService.CompleteSetupSession(- r.Context(), user.ID, source, string(productanalytics.ClassifyIdentity(user)), request.SessionID,+ r.Context(), user.ID, source, request.SessionID,)switch {case errors.Is(err, billing.ErrSetupSessionNotFound), errors.Is(err, billing.ErrSetupSessionNotOwned):diff --git a/libs/fleet/backend/handlers/billing_test.go b/libs/fleet/backend/handlers/billing_test.goindex 7aaeeb9c65..71bda4c04e 100644--- a/libs/fleet/backend/handlers/billing_test.go+++ b/libs/fleet/backend/handlers/billing_test.go@@ -39,7 +39,6 @@ type fakeBillingService struct {defaultErr errorcompleteSubject stringcompleteSource string- completeIdentityClass stringcompleteSessionID stringcompleteResult billing.SetupCompletioncompleteCalls int@@ -94,11 +93,10 @@ 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) {+func (f *fakeBillingService) CompleteSetupSession(_ context.Context, subject, source, sessionID string) (billing.SetupCompletion, error) {f.completeCalls++f.completeSubject = subjectf.completeSource = source- f.completeIdentityClass = identityClassf.completeSessionID = sessionIDreturn f.completeResult, f.completeErr}@@ -365,8 +363,8 @@ func TestCompleteSetupSessionUsesAuthenticatedOwnershipAndEmitsPrivacySafeSuccest.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)+ service.completeSessionID != "cs_test_owned" {+ t.Fatalf("completion ownership = %q/%q/%q", service.completeSubject, service.completeSource, service.completeSessionID)}var body BillingSetupCompletionResponseif err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || !body.Applied {@@ -405,6 +403,82 @@ func TestCompleteSetupSessionDoesNotEmitForIdempotentReplay(t *testing.T) {}}+// Use the real billing service so this covers the handler/service boundary,+// not just a fake that accepts any completion arguments.+type classificationSetupGateway struct {+ billing.Gateway+ storedClass string+ defaultCalls int+}++func (g *classificationSetupGateway) SearchCustomers(_ context.Context, subject string) ([]billing.Customer, error) {+ return []billing.Customer{{ID: "cus_owned", Metadata: map[string]string{billing.MetadataSubject: subject}}}, nil+}++func (g *classificationSetupGateway) RetrieveSetupSession(_ context.Context, sessionID string) (billing.SetupSession, error) {+ return billing.SetupSession{+ ID: sessionID, Mode: "setup", Status: "complete", CustomerID: "cus_owned",+ SetupIntentID: "seti_owned", SetupIntentStatus: "succeeded", SetupIntentCustomerID: "cus_owned",+ PaymentMethodID: "pm_card",+ Metadata: map[string]string{+ "purpose": billing.SetupPurpose, billing.MetadataSubject: billingAlice.ID,+ billing.MetadataSetupSource: productanalytics.SourceSPA,+ billing.MetadataSetupGeneration: "current", billing.MetadataIdentityClass: g.storedClass,+ },+ }, nil+}++func (g *classificationSetupGateway) SetDefaultPaymentMethodForSetupGeneration(_ context.Context, customerID, paymentMethodID, generation string) (bool, error) {+ if customerID != "cus_owned" || paymentMethodID != "pm_card" || generation != "current" {+ return false, errors.New("unexpected default payment method arguments")+ }+ g.defaultCalls+++ return true, nil+}++func TestCompleteSetupSessionClassificationChangesDoNotBlockPayment(t *testing.T) {+ setBillingFlag(t, true)+ for _, storedClass := range []string{"external", "internal", "unknown", ""} {+ for _, current := range []struct {+ class productanalytics.IdentityClass+ admins string+ }{+ {productanalytics.IdentityExternal, `[]`},+ {productanalytics.IdentityInternal, `["user-alice"]`},+ {productanalytics.IdentityUnknown, `{"invalid":"not a list"}`},+ } {+ t.Run(storedClass+"_to_"+string(current.class), func(t *testing.T) {+ t.Setenv("CYCLOPS_CS_ADMIN_SUBS", current.admins)+ auth.InvalidateFeatureFlags()+ t.Cleanup(auth.InvalidateFeatureFlags)+ gateway := &classificationSetupGateway{storedClass: storedClass}+ capture := &analyticsCapture{}+ h := Handlers{+ Billing: billing.NewService(gateway), 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 || gateway.defaultCalls != 1 {+ t.Fatalf("status/default calls = %d/%d, body=%s", response.Code, gateway.defaultCalls, response.Body.String())+ }+ if len(capture.events) != 1 {+ t.Fatalf("events = %#v", capture.events)+ }+ event := capture.events[0]+ if event.Properties["identity_class"] != current.class || event.Name != productanalytics.EventPaymentMethodSetup ||+ event.InsertID != "fleet-payment-setup:seti_owned" || event.DistinctID != billingAlice.ID {+ t.Fatalf("completion must keep current analytics classification and deduplication: %#v", event)+ }+ if err := productanalytics.ValidateEvent(event); err != nil {+ t.Fatalf("privacy-safe event validation failed: %v", err)+ }+ })+ }+ }+}+func TestCompleteSetupSessionRejectsUnownedAndIncompleteSessions(t *testing.T) {setBillingFlag(t, true)for _, testCase := range []struct {