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
feat(analytics): instrument Fleet payment funnel (#7348)
Francesco Bonacci9ca49791fd42
diff --git a/libs/fleet/backend/auth/authz_config.rego b/libs/fleet/backend/auth/authz_config.regoindex 53bf15622b..644656903f 100644--- a/libs/fleet/backend/auth/authz_config.rego+++ b/libs/fleet/backend/auth/authz_config.rego@@ -28,3 +28,9 @@ allow {input.method == "POST"input.user.azp == "cyclops-cs-spa"}++allow {+ input.route == "/api/analytics/payment-gate"+ input.method == "POST"+ input.user.azp == "cyclops-cs-spa"+}diff --git a/libs/fleet/backend/auth/authz_config_test.rego b/libs/fleet/backend/auth/authz_config_test.regoindex 10a3a1a64a..854ca9b098 100644--- a/libs/fleet/backend/auth/authz_config_test.rego+++ b/libs/fleet/backend/auth/authz_config_test.rego@@ -64,3 +64,23 @@ test_user_key_analytics_attribution_denied if {"user": {"sub": "user-123", "azp": "ukey-test", "namespace": "", "email": ""},}}++test_spa_payment_gate_allowed if {+ route_allow with input as {+ "route": "/api/analytics/payment-gate",+ "method": "POST",+ "path": "/api/analytics/payment-gate",+ "params": {},+ "user": {"sub": "user-123", "azp": "cyclops-cs-spa", "namespace": "", "email": ""},+ }+}++test_user_key_payment_gate_denied if {+ not route_allow with input as {+ "route": "/api/analytics/payment-gate",+ "method": "POST",+ "path": "/api/analytics/payment-gate",+ "params": {},+ "user": {"sub": "user-123", "azp": "ukey-test", "namespace": "", "email": ""},+ }+}diff --git a/libs/fleet/backend/auth/policy_card_admission_test.go b/libs/fleet/backend/auth/policy_card_admission_test.goindex b4a1acae44..c38db65fc2 100644--- a/libs/fleet/backend/auth/policy_card_admission_test.go+++ b/libs/fleet/backend/auth/policy_card_admission_test.go@@ -142,7 +142,7 @@ func TestK8sCardAdmissionReturnsBillingMessage(t *testing.T) {if response.Code != http.StatusForbidden || reached {t.Fatalf("status, reached = %d, %v; want %d, false", response.Code, reached, http.StatusForbidden)}- const want = "A payment method is required to create this resource. Add one in Billing and try again."+ const want = BillingSetupRequiredMessageif got := policyErrorMessage(t, response); got != want {t.Fatalf("error = %q, want %q", got, want)}diff --git a/libs/fleet/backend/auth/policy_characterization_test.go b/libs/fleet/backend/auth/policy_characterization_test.goindex 4b880d0fda..eaa43101ef 100644--- a/libs/fleet/backend/auth/policy_characterization_test.go+++ b/libs/fleet/backend/auth/policy_characterization_test.go@@ -174,6 +174,7 @@ func characterizationCases() map[string][]routeCase {simple("/api/config", "/api/config")simple("/api/analytics/session", "/api/analytics/session")simple("/api/analytics/attribution", "/api/analytics/attribution")+ simple("/api/analytics/payment-gate", "/api/analytics/payment-gate")simple("/api/state/query", "/api/state/query")simple("/api/usage/overview", "/api/usage/overview")simple("/api/usage/pool", "/api/usage/pool")diff --git a/libs/fleet/backend/auth/policy_routes.go b/libs/fleet/backend/auth/policy_routes.goindex a9674e8d15..61ce305b17 100644--- a/libs/fleet/backend/auth/policy_routes.go+++ b/libs/fleet/backend/auth/policy_routes.go@@ -174,7 +174,7 @@ func StateQueryRoutePolicy() Node {return All(BasePolicy(), surfaceLeaf("authz-state-query", "data.authz_state_query.allow"))}-const billingSetupRequiredMessage = "A payment method is required to create this resource. Add one in Billing and try again."+const BillingSetupRequiredMessage = "A payment method is required to create this resource. Add one in Billing and try again."// FeatureFlagsRoutePolicy guards the admin-only feature-flag management API.func FeatureFlagsRoutePolicy() Node {@@ -217,7 +217,7 @@ func K8sRoutePolicy() Node {return All(BasePolicy(),surfaceLeaf("authz-k8s", "data.authz_k8s.allow"),- Because(CustomResourceCreationAdmissionPolicy(), billingSetupRequiredMessage),+ Because(CustomResourceCreationAdmissionPolicy(), BillingSetupRequiredMessage),Policy(Modules(Registered("authz"),@@ -285,13 +285,14 @@ var surfacePolicies = map[string]surfacePolicy{// memoized per surface: the three billing routes share one module, one tree,// and one compiled plan.var routeSurfaces = map[string]string{- "/api/config": "config",- "/api/analytics/session": "config",- "/api/analytics/attribution": "config",- "/api/state/query": "state-query",- "/api/usage/overview": "usage",- "/api/usage/pool": "usage",- "/api/usage/browser-timings": "usage",+ "/api/config": "config",+ "/api/analytics/session": "config",+ "/api/analytics/attribution": "config",+ "/api/analytics/payment-gate": "config",+ "/api/state/query": "state-query",+ "/api/usage/overview": "usage",+ "/api/usage/pool": "usage",+ "/api/usage/browser-timings": "usage","/api/chat/conversations": "chat","/api/chat/conversations/{id}": "chat",diff --git a/libs/fleet/backend/auth/testdata/route-authorization-table.txt b/libs/fleet/backend/auth/testdata/route-authorization-table.txtindex c72b8c3074..e209e5117f 100644--- a/libs/fleet/backend/auth/testdata/route-authorization-table.txt+++ b/libs/fleet/backend/auth/testdata/route-authorization-table.txt@@ -163,6 +163,61 @@/api/analytics/attribution | plain | QUERY | spa = deny/api/analytics/attribution | plain | QUERY | user-key = deny/api/analytics/attribution | plain | QUERY | user-key-verified = deny+/api/analytics/payment-gate | plain | DELETE | admin-spa = deny+/api/analytics/payment-gate | plain | DELETE | cua-cli = deny+/api/analytics/payment-gate | plain | DELETE | dcr-client = deny+/api/analytics/payment-gate | plain | DELETE | empty-sub = deny+/api/analytics/payment-gate | plain | DELETE | github-oidc = deny+/api/analytics/payment-gate | plain | DELETE | oauth2-proxy = deny+/api/analytics/payment-gate | plain | DELETE | per-key-other-ns = deny+/api/analytics/payment-gate | plain | DELETE | per-key-owned-ns = deny+/api/analytics/payment-gate | plain | DELETE | spa = deny+/api/analytics/payment-gate | plain | DELETE | user-key = deny+/api/analytics/payment-gate | plain | DELETE | user-key-verified = deny+/api/analytics/payment-gate | plain | GET | admin-spa = deny+/api/analytics/payment-gate | plain | GET | cua-cli = deny+/api/analytics/payment-gate | plain | GET | dcr-client = deny+/api/analytics/payment-gate | plain | GET | empty-sub = deny+/api/analytics/payment-gate | plain | GET | github-oidc = deny+/api/analytics/payment-gate | plain | GET | oauth2-proxy = deny+/api/analytics/payment-gate | plain | GET | per-key-other-ns = deny+/api/analytics/payment-gate | plain | GET | per-key-owned-ns = deny+/api/analytics/payment-gate | plain | GET | spa = deny+/api/analytics/payment-gate | plain | GET | user-key = deny+/api/analytics/payment-gate | plain | GET | user-key-verified = deny+/api/analytics/payment-gate | plain | PATCH | admin-spa = deny+/api/analytics/payment-gate | plain | PATCH | cua-cli = deny+/api/analytics/payment-gate | plain | PATCH | dcr-client = deny+/api/analytics/payment-gate | plain | PATCH | empty-sub = deny+/api/analytics/payment-gate | plain | PATCH | github-oidc = deny+/api/analytics/payment-gate | plain | PATCH | oauth2-proxy = deny+/api/analytics/payment-gate | plain | PATCH | per-key-other-ns = deny+/api/analytics/payment-gate | plain | PATCH | per-key-owned-ns = deny+/api/analytics/payment-gate | plain | PATCH | spa = deny+/api/analytics/payment-gate | plain | PATCH | user-key = deny+/api/analytics/payment-gate | plain | PATCH | user-key-verified = deny+/api/analytics/payment-gate | plain | POST | admin-spa = allow+/api/analytics/payment-gate | plain | POST | cua-cli = deny+/api/analytics/payment-gate | plain | POST | dcr-client = deny+/api/analytics/payment-gate | plain | POST | empty-sub = deny+/api/analytics/payment-gate | plain | POST | github-oidc = deny+/api/analytics/payment-gate | plain | POST | oauth2-proxy = deny+/api/analytics/payment-gate | plain | POST | per-key-other-ns = deny+/api/analytics/payment-gate | plain | POST | per-key-owned-ns = deny+/api/analytics/payment-gate | plain | POST | spa = allow+/api/analytics/payment-gate | plain | POST | user-key = deny+/api/analytics/payment-gate | plain | POST | user-key-verified = deny+/api/analytics/payment-gate | plain | QUERY | admin-spa = deny+/api/analytics/payment-gate | plain | QUERY | cua-cli = deny+/api/analytics/payment-gate | plain | QUERY | dcr-client = deny+/api/analytics/payment-gate | plain | QUERY | empty-sub = deny+/api/analytics/payment-gate | plain | QUERY | github-oidc = deny+/api/analytics/payment-gate | plain | QUERY | oauth2-proxy = deny+/api/analytics/payment-gate | plain | QUERY | per-key-other-ns = deny+/api/analytics/payment-gate | plain | QUERY | per-key-owned-ns = deny+/api/analytics/payment-gate | plain | QUERY | spa = deny+/api/analytics/payment-gate | plain | QUERY | user-key = deny+/api/analytics/payment-gate | plain | QUERY | user-key-verified = deny/api/analytics/session | plain | DELETE | admin-spa = allow/api/analytics/session | plain | DELETE | cua-cli = deny/api/analytics/session | plain | DELETE | dcr-client = denydiff --git a/libs/fleet/backend/handlers/analytics_payment_gate.go b/libs/fleet/backend/handlers/analytics_payment_gate.gonew file mode 100644index 0000000000..e15eed90e3--- /dev/null+++ b/libs/fleet/backend/handlers/analytics_payment_gate.go@@ -0,0 +1,80 @@+package handlers++import (+ "encoding/json"+ "errors"+ "io"+ "net/http"++ "cyclops-cs-backend/middlewares"+ "cyclops-cs-backend/productanalytics"+ "go.opentelemetry.io/otel/trace"+)++const fleetPaymentGateBodyMaxBytes = 256++type fleetPaymentGateRecord struct {+ Reason string `json:"reason"`+}++func (h Handlers) RecordFleetPaymentGate(w http.ResponseWriter, r *http.Request) {+ // The browser reports which bounded gate it rendered. The backend owns the+ // authenticated identity fields; browser-side dedup is best-effort.+ user := currentUser(r)+ if user == nil || user.ID == "" {+ writeErr(w, http.StatusUnauthorized, "authenticated user is required")+ return+ }+ source, ok := productanalytics.SourceForUser(user, h.AuthCfg.SPAClientID)+ if !ok || source != productanalytics.SourceSPA {+ writeErr(w, http.StatusForbidden, "Fleet browser session is required")+ return+ }++ r.Body = http.MaxBytesReader(w, r.Body, fleetPaymentGateBodyMaxBytes)+ decoder := json.NewDecoder(r.Body)+ decoder.DisallowUnknownFields()+ var record fleetPaymentGateRecord+ if err := decoder.Decode(&record); err != nil {+ var maxBytesError *http.MaxBytesError+ if errors.As(err, &maxBytesError) {+ writeErr(w, http.StatusRequestEntityTooLarge, "payment gate record is too large")+ return+ }+ writeErr(w, http.StatusBadRequest, "invalid payment gate record")+ return+ }+ if err := decoder.Decode(&struct{}{}); err != io.EOF {+ writeErr(w, http.StatusBadRequest, "invalid payment gate record")+ return+ }+ if record.Reason != productanalytics.ReasonNoPaymentMethod && record.Reason != productanalytics.ReasonCardAdmissionRequired {+ writeErr(w, http.StatusBadRequest, "invalid payment gate record")+ return+ }+ if productanalytics.ClassifyIdentity(user) != productanalytics.IdentityExternal {+ w.WriteHeader(http.StatusNoContent)+ return+ }++ traceID := trace.SpanContextFromContext(r.Context()).TraceID().String()+ if traceID == "00000000000000000000000000000000" {+ traceID, _ = r.Context().Value(middlewares.ContextKey("traceId")).(string)+ }+ capturer := h.Analytics+ if capturer == nil {+ capturer = productanalytics.Nop()+ }+ capturer.Capture(productanalytics.Event{+ Name: productanalytics.EventPaymentGateShown, DistinctID: user.ID, InsertID: traceID,+ Properties: map[string]any{+ "outcome": productanalytics.OutcomeSuccess,+ "source": source,+ "principal_type": user.PrincipalType,+ "identity_class": productanalytics.IdentityExternal,+ "resource_type": "pool",+ "reason": record.Reason,+ },+ })+ w.WriteHeader(http.StatusNoContent)+}diff --git a/libs/fleet/backend/handlers/analytics_payment_gate_test.go b/libs/fleet/backend/handlers/analytics_payment_gate_test.gonew file mode 100644index 0000000000..ad0e300765--- /dev/null+++ b/libs/fleet/backend/handlers/analytics_payment_gate_test.go@@ -0,0 +1,161 @@+package handlers++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "cyclops-cs-backend/auth"+ "cyclops-cs-backend/middlewares"+ "cyclops-cs-backend/productanalytics"+)++func paymentGateRequest(body string, user *auth.User) *http.Request {+ request := httptest.NewRequest(http.MethodPost, "/api/analytics/payment-gate", strings.NewReader(body))+ if user == nil {+ return request+ }+ ctx := context.WithValue(request.Context(), auth.UserKey, user)+ ctx = context.WithValue(ctx, middlewares.ContextKey("traceId"), "trace-payment-gate")+ return request.WithContext(ctx)+}++func TestRecordFleetPaymentGateCapturesExternalGate(t *testing.T) {+ for _, reason := range []string{+ productanalytics.ReasonNoPaymentMethod,+ productanalytics.ReasonCardAdmissionRequired,+ } {+ t.Run(reason, func(t *testing.T) {+ capture := &analyticsCapture{}+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}+ user := &auth.User{+ ID: "subject-1", Email: "[email protected]", EmailVerified: true,+ AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser,+ }+ response := httptest.NewRecorder()++ h.RecordFleetPaymentGate(response, paymentGateRequest(`{"reason":"`+reason+`"}`, user))++ 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.EventPaymentGateShown || event.DistinctID != user.ID || event.InsertID != "trace-payment-gate" {+ t.Fatalf("event = %#v", event)+ }+ wantProperties := map[string]any{+ "outcome": productanalytics.OutcomeSuccess,+ "source": productanalytics.SourceSPA,+ "principal_type": auth.PrincipalTypeUser,+ "identity_class": productanalytics.IdentityExternal,+ "resource_type": "pool",+ "reason": reason,+ }+ if len(event.Properties) != len(wantProperties) {+ t.Fatalf("properties = %#v, want %#v", event.Properties, wantProperties)+ }+ for key, want := range wantProperties {+ if got := event.Properties[key]; got != want {+ t.Fatalf("property %q = %#v, want %#v", key, got, want)+ }+ }+ })+ }+}++func TestRecordFleetPaymentGateExcludesVerifiedInternalIdentity(t *testing.T) {+ capture := &analyticsCapture{}+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}+ response := httptest.NewRecorder()+ user := &auth.User{+ ID: "internal-1", Email: "[email protected]", EmailVerified: true,+ AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser,+ }++ h.RecordFleetPaymentGate(response, paymentGateRequest(`{"reason":"no_payment_method"}`, user))++ if response.Code != http.StatusNoContent || len(capture.events) != 0 {+ t.Fatalf("status/events = %d/%#v", response.Code, capture.events)+ }+}++func TestRecordFleetPaymentGatePreservesAuthenticatedPrincipalType(t *testing.T) {+ capture := &analyticsCapture{}+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}+ response := httptest.NewRecorder()+ user := &auth.User{+ ID: "subject-1", AZP: "cyclops-cs-spa",+ PrincipalType: auth.PrincipalTypeGitHubOIDC,+ }++ h.RecordFleetPaymentGate(response, paymentGateRequest(`{"reason":"no_payment_method"}`, user))++ if response.Code != http.StatusNoContent || len(capture.events) != 1 {+ t.Fatalf("status/events = %d/%#v", response.Code, capture.events)+ }+ if got := capture.events[0].Properties["principal_type"]; got != auth.PrincipalTypeGitHubOIDC {+ t.Fatalf("principal_type = %#v, want authenticated value", got)+ }+}++func TestRecordFleetPaymentGateEnforcesAuthenticationAndSPASource(t *testing.T) {+ tests := []struct {+ name string+ user *auth.User+ want int+ }{+ {name: "missing user", want: http.StatusUnauthorized},+ {+ name: "CLI user",+ user: &auth.User{ID: "subject-1", AZP: "cua-cli", PrincipalType: auth.PrincipalTypeUser},+ want: http.StatusForbidden,+ },+ {+ name: "user key",+ user: &auth.User{ID: "subject-1", AZP: "ukey-demo", PrincipalType: auth.PrincipalTypeUserKey},+ want: http.StatusForbidden,+ },+ }+ for _, testCase := range tests {+ t.Run(testCase.name, func(t *testing.T) {+ capture := &analyticsCapture{}+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}+ response := httptest.NewRecorder()++ h.RecordFleetPaymentGate(response, paymentGateRequest(`{"reason":"no_payment_method"}`, testCase.user))++ if response.Code != testCase.want || len(capture.events) != 0 {+ t.Fatalf("status/events = %d/%#v, want %d/no events", response.Code, capture.events, testCase.want)+ }+ })+ }+}++func TestRecordFleetPaymentGateRejectsInvalidRecords(t *testing.T) {+ tests := []struct {+ name string+ body string+ want int+ }{+ {name: "unknown reason", body: `{"reason":"payment_required"}`, want: http.StatusBadRequest},+ {name: "unknown field", body: `{"reason":"no_payment_method","email":"[email protected]"}`, want: http.StatusBadRequest},+ {name: "trailing content", body: `{"reason":"no_payment_method"}{}`, want: http.StatusBadRequest},+ {name: "oversized", body: `{"reason":"` + strings.Repeat("x", fleetPaymentGateBodyMaxBytes) + `"}`, want: http.StatusRequestEntityTooLarge},+ }+ user := &auth.User{ID: "subject-1", AZP: "cyclops-cs-spa", PrincipalType: auth.PrincipalTypeUser}+ for _, testCase := range tests {+ t.Run(testCase.name, func(t *testing.T) {+ capture := &analyticsCapture{}+ h := Handlers{Analytics: capture, AuthCfg: configAuthForAnalytics()}+ response := httptest.NewRecorder()++ h.RecordFleetPaymentGate(response, paymentGateRequest(testCase.body, user))++ if response.Code != testCase.want || len(capture.events) != 0 {+ t.Fatalf("status/events = %d/%#v, want %d/no events", response.Code, capture.events, testCase.want)+ }+ })+ }+}diff --git a/libs/fleet/backend/handlers/billing.go b/libs/fleet/backend/handlers/billing.goindex 872886371d..bedd3875d8 100644--- a/libs/fleet/backend/handlers/billing.go+++ b/libs/fleet/backend/handlers/billing.go@@ -187,30 +187,41 @@ func (h Handlers) CreateBillingSetupSession(w http.ResponseWriter, r *http.Requereturn}source, sourceOK := productanalytics.SourceForUser(user, h.AuthCfg.SPAClientID)+ captureSetupStart := func(outcome string, statusCode int, errorClass string) {+ if !sourceOK {+ return+ }+ traceID, _ := r.Context().Value(middlewares.ContextKey("traceId")).(string)+ capturer := h.Analytics+ if capturer == nil {+ capturer = productanalytics.Nop()+ }+ properties := map[string]any{+ "outcome": outcome,+ "source": source,+ "principal_type": user.PrincipalType,+ "identity_class": productanalytics.ClassifyIdentity(user),+ "status_code": statusCode,+ }+ if errorClass != "" {+ properties["error_class"] = errorClass+ }+ capturer.Capture(productanalytics.Event{+ Name: productanalytics.EventPaymentSetupStart, DistinctID: user.ID, InsertID: traceID,+ Properties: properties,+ })+ }url, err := h.Billing.CreateSetupSession(r.Context(), user.ID, billing.SetupOptions{SuccessURL: h.Stripe.CheckoutSuccessURL,CancelURL: h.Stripe.CheckoutCancelURL,Source: source,})if err != nil {- if sourceOK {- traceID, _ := r.Context().Value(middlewares.ContextKey("traceId")).(string)- capturer := h.Analytics- if capturer == nil {- capturer = productanalytics.Nop()- }- capturer.Capture(productanalytics.Event{- Name: productanalytics.EventPaymentMethodSetup, DistinctID: user.ID, InsertID: traceID,- Properties: map[string]any{- "outcome": productanalytics.OutcomeFailure, "source": source,- "principal_type": user.PrincipalType, "status_code": http.StatusBadGateway,- "error_class": "payment_provider",- },- })- }+ captureSetupStart(productanalytics.OutcomeFailure, http.StatusBadGateway, "payment_provider")writeErr(w, http.StatusBadGateway, "could not create Stripe card setup Session")return}+ captureSetupStart(productanalytics.OutcomeSuccess, http.StatusOK, "")writeJSON(w, http.StatusOK, BillingSessionResponse{URL: url})}diff --git a/libs/fleet/backend/handlers/billing_test.go b/libs/fleet/backend/handlers/billing_test.goindex a2613ce8c9..d1e3a6c748 100644--- a/libs/fleet/backend/handlers/billing_test.go+++ b/libs/fleet/backend/handlers/billing_test.go@@ -273,9 +273,11 @@ func TestCreateSetupSessionReturns503WithoutRedirectURLs(t *testing.T) {func TestCreateSetupSessionUsesAuthenticatedSubjectAndNoClientInput(t *testing.T) {setBillingFlag(t, true)service := &fakeBillingService{}+ capture := &analyticsCapture{}h := Handlers{- Billing: service,- AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},+ Billing: service,+ Analytics: capture,+ AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},Stripe: config.StripeConfiguration{SecretKey: "sk_test",CheckoutSuccessURL: "https://run.example.test/settings?setup=success",@@ -310,6 +312,20 @@ func TestCreateSetupSessionUsesAuthenticatedSubjectAndNoClientInput(t *testing.Tif response.URL != "https://checkout.stripe.test/session" {t.Fatalf("response URL = %q", response.URL)}+ if len(capture.events) != 1 {+ t.Fatalf("events = %#v, want one setup-start event", capture.events)+ }+ event := capture.events[0]+ if event.Name != productanalytics.EventPaymentSetupStart || event.DistinctID != billingAlice.ID {+ t.Fatalf("event = %#v", event)+ }+ if event.Properties["outcome"] != productanalytics.OutcomeSuccess ||+ event.Properties["source"] != productanalytics.SourceSPA ||+ event.Properties["principal_type"] != auth.PrincipalTypeUser ||+ event.Properties["identity_class"] != productanalytics.IdentityExternal ||+ event.Properties["status_code"] != http.StatusOK {+ t.Fatalf("properties = %#v", event.Properties)+ }}func TestCreatePortalSessionDerivesOwnedCustomerFromCurrentUser(t *testing.T) {@@ -415,7 +431,34 @@ func TestCreateSetupSessionProviderFailureEmitsFailureEvent(t *testing.T) {t.Fatalf("status/events = %d/%#v", response.Code, capture.events)}event := capture.events[0]- if event.Name != productanalytics.EventPaymentMethodSetup || event.DistinctID != billingAlice.ID || event.Properties["outcome"] != productanalytics.OutcomeFailure || event.Properties["error_class"] != "payment_provider" {+ if event.Name != productanalytics.EventPaymentSetupStart || event.DistinctID != billingAlice.ID ||+ event.Properties["outcome"] != productanalytics.OutcomeFailure ||+ event.Properties["source"] != productanalytics.SourceSPA ||+ event.Properties["principal_type"] != auth.PrincipalTypeUser ||+ event.Properties["identity_class"] != productanalytics.IdentityExternal ||+ event.Properties["status_code"] != http.StatusBadGateway ||+ event.Properties["error_class"] != "payment_provider" {t.Fatalf("event = %#v", event)}}++func TestCreateSetupSessionDoesNotCaptureUnknownSource(t *testing.T) {+ setBillingFlag(t, true)+ service := &fakeBillingService{}+ capture := &analyticsCapture{}+ user := *billingAlice+ user.AZP = "unknown-client"+ h := Handlers{+ 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"},+ }+ 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)+ }+}diff --git a/libs/fleet/backend/handlers/billing_webhook.go b/libs/fleet/backend/handlers/billing_webhook.goindex 4924697fdc..28ae29094e 100644--- a/libs/fleet/backend/handlers/billing_webhook.go+++ b/libs/fleet/backend/handlers/billing_webhook.go@@ -104,6 +104,8 @@ func (h Handlers) HandleBillingWebhook(w http.ResponseWriter, r *http.Request) {}func capturePaymentSetup(capturer productanalytics.Capturer, event billing.WebhookEvent, outcome, errorClass string) {+ // This event represents a terminal Stripe outcome; setup-session launch+ // attempts are recorded separately by the authenticated billing handler.if event.Subject == "" || (event.Source != productanalytics.SourceSPA && event.Source != productanalytics.SourceUserKey) {return}diff --git a/libs/fleet/backend/handlers/billing_webhook_test.go b/libs/fleet/backend/handlers/billing_webhook_test.goindex bdd890f5ab..fadf028f3d 100644--- a/libs/fleet/backend/handlers/billing_webhook_test.go+++ b/libs/fleet/backend/handlers/billing_webhook_test.go@@ -233,7 +233,7 @@ func TestBillingWebhookEmitsTrustedTerminalPaymentFailure(t *testing.T) {t.Fatalf("status/events = %d/%#v", response.Code, capture.events)}event := capture.events[0]- if event.InsertID != "evt_failed" || event.Properties["outcome"] != productanalytics.OutcomeFailure || event.Properties["error_class"] != "payment_provider" {+ if event.Name != productanalytics.EventPaymentMethodSetup || event.InsertID != "evt_failed" || event.Properties["outcome"] != productanalytics.OutcomeFailure || event.Properties["error_class"] != "payment_provider" {t.Fatalf("event = %#v", event)}}diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.goindex 6edcef7469..8c3702d966 100644--- a/libs/fleet/backend/main.go+++ b/libs/fleet/backend/main.go@@ -152,6 +152,8 @@ func setupRouter(c handlers.Handlers) http.Handler {withAuthenticatedMiddlewares("/api/analytics/session", c.RecordAnalyticsSession))r.Handle("POST /api/analytics/attribution",withAuthenticatedMiddlewares("/api/analytics/attribution", c.RecordFleetAttribution))+ r.Handle("POST /api/analytics/payment-gate",+ withAuthenticatedMiddlewares("/api/analytics/payment-gate", c.RecordFleetPaymentGate))r.Handle("POST /api/chat/conversations",withAuthenticatedMiddlewares("/api/chat/conversations", c.CreateConversation))diff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.goindex f0d40ebc53..00f45f5af4 100644--- a/libs/fleet/backend/main_test.go+++ b/libs/fleet/backend/main_test.go@@ -402,6 +402,30 @@ func TestRouterEmitsOneCLILoginAcrossFleetRoutes(t *testing.T) {}}+func TestRouterRecordsSPAPaymentGate(t *testing.T) {+ capture := &routerAnalyticsCapture{}+ router := setupRouter(handlers.Handlers{+ Analytics: capture,+ AuthCfg: config.AuthConfiguration{SPAClientID: "cyclops-cs-spa"},+ })+ response := httptest.NewRecorder()++ router.ServeHTTP(response, authorizedRequest(+ t,+ http.MethodPost,+ "/api/analytics/payment-gate",+ strings.NewReader(`{"reason":"no_payment_method"}`),+ ))++ if response.Code != http.StatusNoContent {+ t.Fatalf("status = %d, want 204; body = %s", response.Code, response.Body.String())+ }+ events := capture.eventsNamed(productanalytics.EventPaymentGateShown)+ if len(events) != 1 || events[0].Properties["reason"] != productanalytics.ReasonNoPaymentMethod {+ t.Fatalf("payment gate events = %#v", events)+ }+}+func bigEndianBytes(v int) []byte {if v == 0 {return []byte{0}diff --git a/libs/fleet/backend/productanalytics/client_test.go b/libs/fleet/backend/productanalytics/client_test.goindex f4b5bb5da9..6e5d1a970f 100644--- a/libs/fleet/backend/productanalytics/client_test.go+++ b/libs/fleet/backend/productanalytics/client_test.go@@ -133,8 +133,8 @@ func TestClientDoesNotLeakRawLoginIdentity(t *testing.T) {}}-func TestClientPseudonymizesAttributionIdentityAndStableInsertID(t *testing.T) {- requests := make(chan map[string]any, 1)+func TestClientPseudonymizesStableIdentityEventInsertIDs(t *testing.T) {+ requests := make(chan map[string]any, 2)server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {defer r.Body.Close()var payload map[string]any@@ -169,6 +169,27 @@ func TestClientPseudonymizesAttributionIdentityAndStableInsertID(t *testing.T) {case <-time.After(2 * time.Second):t.Fatal("timed out waiting for attribution capture")}++ client.Capture(Event{+ Name: EventFleetActivation, DistinctID: "subject-1",+ Properties: map[string]any{"outcome": OutcomeSuccess, "source": SourceSPA, "principal_type": "user", "identity_class": IdentityExternal},+ SetOnce: map[string]any{firstActivationProperty: time.Now().UTC().Format(time.RFC3339)},+ })+ select {+ case payload := <-requests:+ encoded, _ := json.Marshal(payload)+ if bytes.Contains(encoded, []byte("subject-1")) {+ t.Fatalf("payload contains raw subject: %s", encoded)+ }+ item := payload["batch"].([]any)[0].(map[string]any)+ pseudonym := PseudonymForUserID("subject-1", "identity-test-key")+ properties := item["properties"].(map[string]any)+ if item["distinct_id"] != pseudonym || properties["$insert_id"] != "fleet-activation:"+pseudonym {+ t.Fatalf("item = %#v", item)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("timed out waiting for activation capture")+ }ctx, cancel := context.WithTimeout(context.Background(), time.Second)defer cancel()if err := client.Shutdown(ctx); err != nil {diff --git a/libs/fleet/backend/productanalytics/events.go b/libs/fleet/backend/productanalytics/events.goindex 83c0d40c8f..bb79366dd6 100644--- a/libs/fleet/backend/productanalytics/events.go+++ b/libs/fleet/backend/productanalytics/events.go@@ -61,6 +61,8 @@ func loginSessionKey(user *auth.User) string {const (EventLoginSucceeded = "fleet_login_succeeded"+ EventPaymentGateShown = "fleet_payment_gate_shown"+ EventPaymentSetupStart = "fleet_payment_setup_start"EventPaymentMethodSetup = "fleet_payment_method_setup"EventPoolCreate = "fleet_pool_create"EventClaimCreate = "fleet_claim_create"@@ -83,10 +85,13 @@ const (SourceCLI = "cli"SourceUserKey = "user_key"Version = "1"++ ReasonNoPaymentMethod = "no_payment_method"+ ReasonCardAdmissionRequired = "card_admission_required")var allowedEvents = map[string]struct{}{- EventLoginSucceeded: {}, EventPaymentMethodSetup: {}, EventPoolCreate: {},+ EventLoginSucceeded: {}, EventPaymentGateShown: {}, EventPaymentSetupStart: {}, EventPaymentMethodSetup: {}, EventPoolCreate: {},EventClaimCreate: {}, EventHTTPProxyRequest: {},EventFleetActivation: {},EventQualifyingWorkload: {},@@ -103,7 +108,7 @@ var allowedProperties = map[string]struct{}{var allowedResourceTypes = map[string]struct{}{"pool": {}, "template": {}, "claim": {}}var allowedReasons = map[string]struct{}{- "payment_required": {}, "authorization": {}, "validation": {}, "quota": {}, "timeout": {}, "internal": {},+ "payment_required": {}, ReasonNoPaymentMethod: {}, ReasonCardAdmissionRequired: {}, "authorization": {}, "validation": {}, "quota": {}, "timeout": {}, "internal": {},"not_svc_route": {}, "invalid_method": {}, "upgrade_request": {}, "binding_lookup_failed": {}, "claim_missing": {},"claim_mismatch": {}, "claim_not_bound": {}, "sandbox_missing": {},"service_mismatch": {}, "pool_lookup_failed": {}, "pool_missing": {}, "non_2xx": {}, "probe_request": {}, "facts_unavailable": {},@@ -208,10 +213,20 @@ func ValidateEvent(event Event) error {if _, valid := allowedReasons[value]; !valid {return fmt.Errorf("unsupported analytics reason")}+ if event.Name != EventPaymentGateShown && (value == ReasonNoPaymentMethod || value == ReasonCardAdmissionRequired) {+ return fmt.Errorf("payment gate reason requires payment gate event")+ }}if event.Name == EventResourceBlocked && (!hasResourceType || !hasReason) {return fmt.Errorf("resource block event requires resource type and reason")}+ if event.Name == EventPaymentGateShown {+ resource, resourceOK := resourceType.(string)+ reasonValue, reasonOK := reason.(string)+ if !hasResourceType || !hasReason || !resourceOK || resource != "pool" || !reasonOK || (reasonValue != ReasonNoPaymentMethod && reasonValue != ReasonCardAdmissionRequired) {+ return fmt.Errorf("payment gate event requires pool resource type and payment gate reason")+ }+ }if event.Name == EventQualificationRejected && !hasReason {return fmt.Errorf("qualification rejection event requires reason")}diff --git a/libs/fleet/backend/productanalytics/events_test.go b/libs/fleet/backend/productanalytics/events_test.goindex 84bbccf654..4e797d7834 100644--- a/libs/fleet/backend/productanalytics/events_test.go+++ b/libs/fleet/backend/productanalytics/events_test.go@@ -132,3 +132,59 @@ func TestValidateEventRejectsUnsafeProperties(t *testing.T) {}}}++func TestValidatePaymentFunnelEvents(t *testing.T) {+ setupStart := Event{+ Name: EventPaymentSetupStart, DistinctID: "subject-1",+ Properties: map[string]any{+ "outcome": OutcomeSuccess, "source": SourceSPA,+ "principal_type": auth.PrincipalTypeUser, "identity_class": IdentityExternal,+ "status_code": 200,+ },+ }+ if err := ValidateEvent(setupStart); err != nil {+ t.Fatalf("ValidateEvent(setup start) error = %v", err)+ }++ gate := Event{+ Name: EventPaymentGateShown, DistinctID: "subject-1",+ Properties: map[string]any{+ "outcome": OutcomeSuccess, "source": SourceSPA,+ "principal_type": auth.PrincipalTypeUser, "identity_class": IdentityExternal,+ "resource_type": "pool", "reason": ReasonNoPaymentMethod,+ },+ }+ if err := ValidateEvent(gate); err != nil {+ t.Fatalf("ValidateEvent(payment gate) error = %v", err)+ }+ gate.Properties["reason"] = ReasonCardAdmissionRequired+ if err := ValidateEvent(gate); err != nil {+ t.Fatalf("ValidateEvent(card admission gate) error = %v", err)+ }++ invalid := []struct {+ name string+ properties map[string]any+ }{+ {name: "missing reason", properties: map[string]any{"resource_type": "pool"}},+ {name: "missing resource", properties: map[string]any{"reason": ReasonNoPaymentMethod}},+ {name: "wrong resource", properties: map[string]any{"resource_type": "claim", "reason": ReasonNoPaymentMethod}},+ {name: "wrong reason", properties: map[string]any{"resource_type": "pool", "reason": "payment_required"}},+ }+ for _, testCase := range invalid {+ t.Run(testCase.name, func(t *testing.T) {+ event := Event{Name: EventPaymentGateShown, DistinctID: "subject-1", Properties: testCase.properties}+ if err := ValidateEvent(event); err == nil {+ t.Fatalf("ValidateEvent() accepted properties %#v", testCase.properties)+ }+ })+ }++ blocked := Event{+ Name: EventResourceBlocked, DistinctID: "subject-1",+ Properties: map[string]any{"resource_type": "pool", "reason": ReasonNoPaymentMethod},+ }+ if err := ValidateEvent(blocked); err == nil {+ t.Fatal("ValidateEvent() accepted a payment-gate-only reason on a resource block")+ }+}diff --git a/libs/fleet/backend/productanalytics/middleware.go b/libs/fleet/backend/productanalytics/middleware.goindex fe04df8305..23a014de5a 100644--- a/libs/fleet/backend/productanalytics/middleware.go+++ b/libs/fleet/backend/productanalytics/middleware.go@@ -165,7 +165,10 @@ func routeObserver(route string, capturer Capturer, spaClientID string, qualifieProperties: properties,})capturer.Capture(Event{- Name: EventFleetActivation, DistinctID: user.ID, InsertID: "fleet-activation:" + user.ID,+ // This marker is emitted for every qualifying request. Activation+ // queries must take each identity's earliest timestamp until the+ // backend has durable once-per-user state.+ Name: EventFleetActivation, DistinctID: user.ID,SetOnce: map[string]any{firstActivationProperty: time.Now().UTC().Format(time.RFC3339)},Properties: properties,})@@ -309,7 +312,7 @@ func (rw *analyticsResponseWriter) Write(body []byte) (int, error) {remaining = len(body)}rw.bodySample = append(rw.bodySample, body[:remaining]...)- if bytes.Contains(rw.bodySample, []byte("A payment method is required to create this resource")) {+ if bytes.Contains(rw.bodySample, []byte(auth.BillingSetupRequiredMessage)) {rw.paymentRequired = true}}diff --git a/libs/fleet/backend/productanalytics/middleware_test.go b/libs/fleet/backend/productanalytics/middleware_test.goindex 927007d7bb..dd3a194c17 100644--- a/libs/fleet/backend/productanalytics/middleware_test.go+++ b/libs/fleet/backend/productanalytics/middleware_test.go@@ -160,7 +160,7 @@ func TestRouteObserverEmitsActivationForAuthenticatedNonInternalIdentity(t *testif workload == nil {t.Fatalf("qualifying workload event missing: %#v", events)}- if activation == nil || activation.InsertID != "fleet-activation:"+test.user.ID || activation.SetOnce[firstActivationProperty] == nil {+ if activation == nil || activation.InsertID != "" || activation.SetOnce[firstActivationProperty] == nil {t.Fatalf("activation event = %#v", activation)}}@@ -335,7 +335,7 @@ func TestRouteObserverClassifiesPaymentRequiredWithoutChangingResponse(t *testinhandler := RouteObserver("/api/k8s/{path...}", sink, "cyclops-cs-spa")(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {w.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusForbidden)- _, _ = w.Write([]byte(`{"message":"A payment method is required to create this resource. Add one in Billing and try again."}`))+ _, _ = w.Write([]byte(`{"message":"` + auth.BillingSetupRequiredMessage + `"}`))}))response := httptest.NewRecorder()handler.ServeHTTP(response, observedRequest(http.MethodPost, "/api/k8s/{path...}", "apis/cua.ai/v1/namespaces/ns-a/osgymworkspacepools", &auth.User{ID: "u-1", AZP: "cyclops-cs-spa"}))diff --git a/libs/fleet/e2e/fixtures/mock-api.ts b/libs/fleet/e2e/fixtures/mock-api.tsindex 9981227c64..ec8ae9d77d 100644--- a/libs/fleet/e2e/fixtures/mock-api.ts+++ b/libs/fleet/e2e/fixtures/mock-api.ts@@ -116,6 +116,7 @@ export async function mockAuth(this.realmAccess = { roles: [] };this.resourceAccess = {};this.subject = "test-user-id";+ this.sessionId = "test-session-id";}async init(options) {window.__MOCK_KEYCLOAK__.initOptions = options;diff --git a/libs/fleet/e2e/pools.spec.ts b/libs/fleet/e2e/pools.spec.tsindex ce91a4879e..cd60ea274e 100644--- a/libs/fleet/e2e/pools.spec.ts+++ b/libs/fleet/e2e/pools.spec.ts@@ -412,6 +412,11 @@ test.describe("Pool creation", () => {await mockAuth(page, { billing: true })await mockNamespacesApi(page)await mockPoolsApi(page)+ const paymentGateRequests: Array<{ reason: string }> = []+ await page.route("**/api/analytics/payment-gate", async route => {+ paymentGateRequests.push(route.request().postDataJSON() as { reason: string })+ await route.fulfill({ status: 204 })+ })await page.route("**/api/billing/summary", (route) =>route.fulfill({contentType: "application/json",@@ -429,6 +434,9 @@ test.describe("Pool creation", () => {await page.goto("/pools/new")await expect(page.getByText("Payment method required")).toBeVisible()+ await expect.poll(() => paymentGateRequests).toEqual([+ { reason: "no_payment_method" },+ ])// Cloudscape renders reason-carrying disabled buttons with aria-disabled// (kept focusable for the tooltip) rather than the disabled attribute.await expect(page.getByRole("button", { name: "Create" })).toHaveAttribute(@@ -442,16 +450,84 @@ test.describe("Pool creation", () => {.getByText("Add a payment method in Settings to create pools."),).toBeVisible()+ await page.goto("/pools")+ await page.goto("/pools/new")+ await expect(page.getByText("Payment method required")).toBeVisible()+ await expect.poll(() => paymentGateRequests).toHaveLength(1)+await page.getByRole("button", { name: "Add payment method" }).click()await expect(page).toHaveURL(/\/settings$/)})+ test("payment policy gate reports the admission reason", async ({ page }) => {+ await mockAuth(page, { billing: true })+ await mockNamespacesApi(page)+ await mockPoolsApi(page)+ const paymentGateRequests: Array<{ reason: string }> = []+ await page.route("**/api/analytics/payment-gate", async route => {+ paymentGateRequests.push(route.request().postDataJSON() as { reason: string })+ await route.fulfill({ status: 204 })+ })+ await page.route("**/api/billing/summary", route =>+ route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({+ payment_method_present: true,+ card: { brand: "visa", last4: "4242", exp_month: 12, exp_year: 2030 },+ pool_create_card_required: true,+ }),+ }),+ )++ await page.goto("/pools/new")++ await expect(page.getByText("Payment method required")).toBeVisible()+ await expect.poll(() => paymentGateRequests).toEqual([+ { reason: "card_admission_required" },+ ])+ })++ test("missing payment method takes priority over the admission reason", async ({+ page,+ }) => {+ await mockAuth(page, { billing: true })+ await mockNamespacesApi(page)+ await mockPoolsApi(page)+ const paymentGateRequests: Array<{ reason: string }> = []+ await page.route("**/api/analytics/payment-gate", async route => {+ paymentGateRequests.push(route.request().postDataJSON() as { reason: string })+ await route.fulfill({ status: 204 })+ })+ await page.route("**/api/billing/summary", route =>+ route.fulfill({+ contentType: "application/json",+ body: JSON.stringify({+ payment_method_present: false,+ card: null,+ pool_create_card_required: true,+ }),+ }),+ )++ await page.goto("/pools/new")++ await expect(page.getByText("Payment method required")).toBeVisible()+ await expect.poll(() => paymentGateRequests).toEqual([+ { reason: "no_payment_method" },+ ])+ })+test("create stays enabled once a payment card is on file", async ({page,}) => {await mockAuth(page, { billing: true })await mockNamespacesApi(page)await mockPoolsApi(page)+ let paymentGateRequests = 0+ await page.route("**/api/analytics/payment-gate", async route => {+ paymentGateRequests += 1+ await route.fulfill({ status: 204 })+ })await page.route("**/api/billing/summary", (route) =>route.fulfill({contentType: "application/json",@@ -468,6 +544,31 @@ test.describe("Pool creation", () => {await expect(page.getByPlaceholder("my-pool")).toBeVisible()await expect(page.getByText("Payment method required")).toHaveCount(0)await expect(page.getByRole("button", { name: "Create" })).toBeEnabled()+ expect(paymentGateRequests).toBe(0)+ })++ test("payment gate analytics stays off when billing is disabled", async ({+ page,+ }) => {+ await mockAuth(page)+ await mockNamespacesApi(page)+ await mockPoolsApi(page)+ let summaryRequests = 0+ let paymentGateRequests = 0+ await page.route("**/api/billing/summary", route => {+ summaryRequests += 1+ return route.fulfill({ status: 500 })+ })+ await page.route("**/api/analytics/payment-gate", route => {+ paymentGateRequests += 1+ return route.fulfill({ status: 204 })+ })++ await page.goto("/pools/new")++ await expect(page.getByPlaceholder("my-pool")).toBeVisible()+ expect(summaryRequests).toBe(0)+ expect(paymentGateRequests).toBe(0)})test("create failure pipes the backend error into the flash message", async ({diff --git a/libs/fleet/src/auth/analytics.ts b/libs/fleet/src/auth/analytics.tsindex 4a1972d783..1f987e3b81 100644--- a/libs/fleet/src/auth/analytics.ts+++ b/libs/fleet/src/auth/analytics.ts@@ -13,6 +13,12 @@ interface AnalyticsDependencies {}const storagePrefix = "fleet-login-recorded:"+const paymentGateStoragePrefix = "fleet-payment-gate-recorded:"+const paymentGateInFlight = new Map<string, Promise<void>>()++export type FleetPaymentGateReason =+ | "no_payment_method"+ | "card_admission_required"function defaultDependencies(): AnalyticsDependencies {return {@@ -44,6 +50,42 @@ export async function recordFleetLogin(dependencies.storage.setItem(marker, "true")}+export async function recordFleetPaymentGate(+ reason: FleetPaymentGateReason,+ sessionID: string | undefined,+ dependencies: AnalyticsDependencies = defaultDependencies(),+): Promise<void> {+ const marker = `${paymentGateStoragePrefix}${sessionID || "authenticated"}:${reason}`+ if (dependencies.storage.getItem(marker) === "true") return+ const pending = paymentGateInFlight.get(marker)+ if (pending) return pending++ const request = (async () => {+ const token = await dependencies.getToken()+ if (!token) throw new Error("Authentication token is unavailable")+ const response = await dependencies.fetch("/api/analytics/payment-gate", {+ method: "POST",+ headers: {+ Authorization: `Bearer ${token}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ reason }),+ })+ if (!response.ok) {+ throw new Error(`Fleet payment gate analytics request failed: ${response.status}`)+ }+ dependencies.storage.setItem(marker, "true")+ })()+ paymentGateInFlight.set(marker, request)+ try {+ await request+ } finally {+ if (paymentGateInFlight.get(marker) === request) {+ paymentGateInFlight.delete(marker)+ }+ }+}+export async function bindFleetAttribution(dependencies: AnalyticsDependencies = defaultDependencies(),): Promise<void> {diff --git a/libs/fleet/src/pages/PoolNew.tsx b/libs/fleet/src/pages/PoolNew.tsxindex 63ef8f2a10..7394fd6f07 100644--- a/libs/fleet/src/pages/PoolNew.tsx+++ b/libs/fleet/src/pages/PoolNew.tsx@@ -13,6 +13,8 @@ import Select from "@cloudscape-design/components/select"import SpaceBetween from "@cloudscape-design/components/space-between"import Toggle from "@cloudscape-design/components/toggle"import { billingApi } from "../api/billing"+import { recordFleetPaymentGate, type FleetPaymentGateReason } from "../auth/analytics"+import { kc } from "../auth/keycloak"import { useFeatureFlags } from "../components/FeatureFlagContext"import { useFlash } from "../components/FlashContext"import { errorMessage } from "../error-message"@@ -127,7 +129,7 @@ export function PoolNew() {// card-admission policy would deny this user's pool create. Stays false// while loading or when the lookup fails: the backend policy is still the// enforcement point, so the gate fails open on a billing hiccup.- const [cardRequired, setCardRequired] = useState(false)+ const [paymentGateReason, setPaymentGateReason] = useState<FleetPaymentGateReason | null>(null)const nameRef = useRef<InputProps.Ref>(null)const ttlRef = useRef<InputProps.Ref>(null)@@ -138,9 +140,15 @@ export function PoolNew() {.summary().then(summary => {if (!cancelled) {- setCardRequired(+ const cardRequired =!summary.payment_method_present ||- summary.pool_create_card_required === true,+ summary.pool_create_card_required === true+ setPaymentGateReason(+ !cardRequired+ ? null+ : !summary.payment_method_present+ ? "no_payment_method"+ : "card_admission_required",)}})@@ -150,6 +158,13 @@ export function PoolNew() {}}, [billingEnabled, paymentMethodGateEnabled])+ useEffect(() => {+ if (!paymentGateReason) return+ void recordFleetPaymentGate(paymentGateReason, kc.sessionId).catch(() => undefined)+ }, [paymentGateReason])++ const cardRequired = paymentGateReason !== null+useBeforeUnload(event => {if (!dirty || submitting) returnevent.preventDefault()diff --git a/libs/fleet/tests/auth-analytics.test.ts b/libs/fleet/tests/auth-analytics.test.tsindex 0c3a9cd196..eb97afb4e3 100644--- a/libs/fleet/tests/auth-analytics.test.ts+++ b/libs/fleet/tests/auth-analytics.test.ts@@ -1,6 +1,10 @@import assert from "node:assert/strict"import test from "node:test"-import { bindFleetAttribution, recordFleetLogin } from "../src/auth/analytics.ts"+import {+ bindFleetAttribution,+ recordFleetLogin,+ recordFleetPaymentGate,+} from "../src/auth/analytics.ts"import { ATTRIBUTION_STORAGE_KEY } from "../src/auth/fleet-attribution.ts"test("records one Fleet login per Keycloak browser session", async () => {@@ -42,6 +46,110 @@ test("analytics failure does not mark the session as recorded", async () => {assert.equal(stored.size, 0)})+test("records a privacy-safe payment gate for the authenticated session", async () => {+ const stored = new Map<string, string>()+ const calls: Array<{ input: string; init?: RequestInit }> = []+ await recordFleetPaymentGate("no_payment_method", "payment-session-1", {+ getToken: async () => "token-1",+ fetch: async (input, init) => {+ calls.push({ input, init })+ return new Response(null, { status: 204 })+ },+ storage: {+ getItem: key => stored.get(key) ?? null,+ setItem: (key, value) => stored.set(key, value),+ },+ })++ assert.equal(calls.length, 1)+ assert.equal(calls[0]?.input, "/api/analytics/payment-gate")+ assert.equal(calls[0]?.init?.method, "POST")+ assert.deepEqual(calls[0]?.init?.headers, {+ Authorization: "Bearer token-1",+ "Content-Type": "application/json",+ })+ assert.deepEqual(JSON.parse(String(calls[0]?.init?.body)), {+ reason: "no_payment_method",+ })+ assert.equal(stored.size, 1)+})++test("deduplicates concurrent and repeated payment gates within one session", async () => {+ const stored = new Map<string, string>()+ let calls = 0+ let releaseRequest: () => void = () => undefined+ const requestReleased = new Promise<void>(resolve => {+ releaseRequest = resolve+ })+ const dependencies = {+ getToken: async () => "token-1",+ fetch: async () => {+ calls += 1+ await requestReleased+ return new Response(null, { status: 204 })+ },+ storage: {+ getItem: (key: string) => stored.get(key) ?? null,+ setItem: (key: string, value: string) => stored.set(key, value),+ },+ }++ const first = recordFleetPaymentGate("no_payment_method", "payment-session-2", dependencies)+ const concurrent = recordFleetPaymentGate("no_payment_method", "payment-session-2", dependencies)+ releaseRequest()+ await Promise.all([first, concurrent])+ await recordFleetPaymentGate("no_payment_method", "payment-session-2", dependencies)++ assert.equal(calls, 1)+ assert.equal(stored.size, 1)+})++test("retries a payment gate after a failed request", async () => {+ const stored = new Map<string, string>()+ let calls = 0+ const dependencies = {+ getToken: async () => "token-1",+ fetch: async () => {+ calls += 1+ return new Response(null, { status: calls === 1 ? 503 : 204 })+ },+ storage: {+ getItem: (key: string) => stored.get(key) ?? null,+ setItem: (key: string, value: string) => stored.set(key, value),+ },+ }++ await assert.rejects(recordFleetPaymentGate("no_payment_method", "payment-session-3", dependencies))+ assert.equal(stored.size, 0)+ await recordFleetPaymentGate("no_payment_method", "payment-session-3", dependencies)++ assert.equal(calls, 2)+ assert.equal(stored.size, 1)+})++test("records separate payment gates for separate sessions and reasons", async () => {+ const stored = new Map<string, string>()+ let calls = 0+ const dependencies = {+ getToken: async () => "token-1",+ fetch: async () => {+ calls += 1+ return new Response(null, { status: 204 })+ },+ storage: {+ getItem: (key: string) => stored.get(key) ?? null,+ setItem: (key: string, value: string) => stored.set(key, value),+ },+ }++ await recordFleetPaymentGate("no_payment_method", "payment-session-4", dependencies)+ await recordFleetPaymentGate("no_payment_method", "payment-session-5", dependencies)+ await recordFleetPaymentGate("card_admission_required", "payment-session-4", dependencies)++ assert.equal(calls, 3)+ assert.equal(stored.size, 3)+})+test("binds validated first-touch attribution after authentication", async () => {const capturedAt = Date.now()const stored = new Map<string, string>([[ATTRIBUTION_STORAGE_KEY, JSON.stringify({